blob: e8d2cad84973dde5c2549e561012fbe446d90f03 [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"
Benjamin Kramer064414532010-04-12 19:45:50 +000025#include "clang/Basic/Diagnostic.h"
26#include "clang/Frontend/ASTUnit.h"
27#include "clang/Frontend/CompilerInstance.h"
Douglas Gregorba965fb2010-01-28 00:56:43 +000028#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenek2a43fd52010-01-06 23:43:31 +000029#include "clang/Lex/Lexer.h"
Benjamin Kramer064414532010-04-12 19:45:50 +000030#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor562c1f92010-01-22 19:49:59 +000031#include "clang/Lex/Preprocessor.h"
Douglas Gregord3d923a2009-10-16 21:24:31 +000032#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor8ef4c802010-08-09 21:00:09 +000033#include "llvm/Support/Timer.h"
Benjamin Kramer2836c4c2009-10-18 11:19:36 +000034#include "llvm/System/Program.h"
Douglas Gregor1e21cc72010-02-18 23:07:20 +000035#include "llvm/System/Signals.h"
Ted Kremenek428c6372009-10-19 21:44:57 +000036
Benjamin Kramerf156b9d2010-03-13 21:22:49 +000037// Needed to define L_TMPNAM on some systems.
38#include <cstdio>
39
Steve Naroffa1c72842009-08-28 15:28:48 +000040using namespace clang;
Ted Kremenek87553c42010-01-15 20:35:54 +000041using namespace clang::cxcursor;
Ted Kremenek5cca6eb2010-02-17 00:41:08 +000042using namespace clang::cxstring;
Steve Naroffa1c72842009-08-28 15:28:48 +000043
Ted Kremenek991eb3f2010-01-06 03:42:32 +000044//===----------------------------------------------------------------------===//
45// Crash Reporting.
46//===----------------------------------------------------------------------===//
47
Ted Kremenekea465e12010-05-22 00:06:46 +000048#ifdef USE_CRASHTRACER
Ted Kremenek991eb3f2010-01-06 03:42:32 +000049#include "clang/Analysis/Support/SaveAndRestore.h"
50// Integrate with crash reporter.
Daniel Dunbar6ac7d7d2010-05-20 23:50:23 +000051static const char *__crashreporter_info__ = 0;
52asm(".desc ___crashreporter_info__, 0x10");
Ted Kremenek896e1642010-02-17 21:12:23 +000053#define NUM_CRASH_STRINGS 32
Ted Kremenek7a5ede22010-01-07 22:49:05 +000054static unsigned crashtracer_counter = 0;
Ted Kremenek32b79312010-01-07 23:13:53 +000055static unsigned crashtracer_counter_id[NUM_CRASH_STRINGS] = { 0 };
Ted Kremenek7a5ede22010-01-07 22:49:05 +000056static const char *crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
57static const char *agg_crashtracer_strings[NUM_CRASH_STRINGS] = { 0 };
58
59static unsigned SetCrashTracerInfo(const char *str,
60 llvm::SmallString<1024> &AggStr) {
Ted Kremenekf441baf2010-02-17 00:41:40 +000061
Ted Kremenek32b79312010-01-07 23:13:53 +000062 unsigned slot = 0;
Ted Kremenek7a5ede22010-01-07 22:49:05 +000063 while (crashtracer_strings[slot]) {
64 if (++slot == NUM_CRASH_STRINGS)
65 slot = 0;
66 }
67 crashtracer_strings[slot] = str;
Ted Kremenek32b79312010-01-07 23:13:53 +000068 crashtracer_counter_id[slot] = ++crashtracer_counter;
Ted Kremenek7a5ede22010-01-07 22:49:05 +000069
70 // We need to create an aggregate string because multiple threads
71 // may be in this method at one time. The crash reporter string
72 // will attempt to overapproximate the set of in-flight invocations
73 // of this function. Race conditions can still cause this goal
74 // to not be achieved.
75 {
Ted Kremenekf441baf2010-02-17 00:41:40 +000076 llvm::raw_svector_ostream Out(AggStr);
Ted Kremenek7a5ede22010-01-07 22:49:05 +000077 for (unsigned i = 0; i < NUM_CRASH_STRINGS; ++i)
78 if (crashtracer_strings[i]) Out << crashtracer_strings[i] << '\n';
79 }
80 __crashreporter_info__ = agg_crashtracer_strings[slot] = AggStr.c_str();
81 return slot;
82}
83
84static void ResetCrashTracerInfo(unsigned slot) {
Ted Kremenek32b79312010-01-07 23:13:53 +000085 unsigned max_slot = 0;
86 unsigned max_value = 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +000087
Ted Kremenek32b79312010-01-07 23:13:53 +000088 crashtracer_strings[slot] = agg_crashtracer_strings[slot] = 0;
89
90 for (unsigned i = 0 ; i < NUM_CRASH_STRINGS; ++i)
91 if (agg_crashtracer_strings[i] &&
92 crashtracer_counter_id[i] > max_value) {
93 max_slot = i;
94 max_value = crashtracer_counter_id[i];
Ted Kremenek7a5ede22010-01-07 22:49:05 +000095 }
Ted Kremenek32b79312010-01-07 23:13:53 +000096
97 __crashreporter_info__ = agg_crashtracer_strings[max_slot];
Ted Kremenek7a5ede22010-01-07 22:49:05 +000098}
99
100namespace {
101class ArgsCrashTracerInfo {
102 llvm::SmallString<1024> CrashString;
103 llvm::SmallString<1024> AggregateString;
104 unsigned crashtracerSlot;
105public:
106 ArgsCrashTracerInfo(llvm::SmallVectorImpl<const char*> &Args)
107 : crashtracerSlot(0)
108 {
109 {
110 llvm::raw_svector_ostream Out(CrashString);
Ted Kremenekb3908402010-03-05 22:43:25 +0000111 Out << "ClangCIndex [" << getClangFullVersion() << "]"
112 << "[createTranslationUnitFromSourceFile]: clang";
Ted Kremenek7a5ede22010-01-07 22:49:05 +0000113 for (llvm::SmallVectorImpl<const char*>::iterator I=Args.begin(),
114 E=Args.end(); I!=E; ++I)
115 Out << ' ' << *I;
116 }
117 crashtracerSlot = SetCrashTracerInfo(CrashString.c_str(),
118 AggregateString);
119 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000120
Ted Kremenek7a5ede22010-01-07 22:49:05 +0000121 ~ArgsCrashTracerInfo() {
122 ResetCrashTracerInfo(crashtracerSlot);
123 }
124};
125}
126#endif
Ted Kremenek991eb3f2010-01-06 03:42:32 +0000127
Douglas Gregor562c1f92010-01-22 19:49:59 +0000128/// \brief The result of comparing two source ranges.
129enum RangeComparisonResult {
130 /// \brief Either the ranges overlap or one of the ranges is invalid.
131 RangeOverlap,
Ted Kremenekf441baf2010-02-17 00:41:40 +0000132
Douglas Gregor562c1f92010-01-22 19:49:59 +0000133 /// \brief The first range ends before the second range starts.
134 RangeBefore,
Ted Kremenekf441baf2010-02-17 00:41:40 +0000135
Douglas Gregor562c1f92010-01-22 19:49:59 +0000136 /// \brief The first range starts after the second range ends.
137 RangeAfter
138};
139
Ted Kremenekf441baf2010-02-17 00:41:40 +0000140/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor562c1f92010-01-22 19:49:59 +0000141/// the translation unit.
Ted Kremenekf441baf2010-02-17 00:41:40 +0000142static RangeComparisonResult RangeCompare(SourceManager &SM,
143 SourceRange R1,
Douglas Gregor562c1f92010-01-22 19:49:59 +0000144 SourceRange R2) {
145 assert(R1.isValid() && "First range is invalid?");
146 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000147 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbar02968e52010-02-14 10:02:57 +0000148 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor562c1f92010-01-22 19:49:59 +0000149 return RangeBefore;
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000150 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbar02968e52010-02-14 10:02:57 +0000151 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor562c1f92010-01-22 19:49:59 +0000152 return RangeAfter;
153 return RangeOverlap;
154}
155
Ted Kremenek680fe512010-05-05 00:55:23 +0000156/// \brief Determine if a source location falls within, before, or after a
157/// a given source range.
158static RangeComparisonResult LocationCompare(SourceManager &SM,
159 SourceLocation L, SourceRange R) {
160 assert(R.isValid() && "First range is invalid?");
161 assert(L.isValid() && "Second range is invalid?");
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000162 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenek680fe512010-05-05 00:55:23 +0000163 return RangeOverlap;
Ted Kremenek680fe512010-05-05 00:55:23 +0000164 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
165 return RangeBefore;
166 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
167 return RangeAfter;
168 return RangeOverlap;
169}
170
Daniel Dunbar474b2072010-02-14 01:47:29 +0000171/// \brief Translate a Clang source range into a CIndex source range.
172///
173/// Clang internally represents ranges where the end location points to the
174/// start of the token at the end. However, for external clients it is more
175/// useful to have a CXSourceRange be a proper half-open interval. This routine
176/// does the appropriate translation.
Ted Kremenekf441baf2010-02-17 00:41:40 +0000177CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar474b2072010-02-14 01:47:29 +0000178 const LangOptions &LangOpts,
Chris Lattnered8b6b72010-06-18 22:45:06 +0000179 const CharSourceRange &R) {
Daniel Dunbar474b2072010-02-14 01:47:29 +0000180 // We want the last character in this location, so we will adjust the
Douglas Gregoraae92242010-03-19 21:51:54 +0000181 // location accordingly.
182 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar474b2072010-02-14 01:47:29 +0000183 SourceLocation EndLoc = R.getEnd();
Chris Lattnered8b6b72010-06-18 22:45:06 +0000184 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregoraae92242010-03-19 21:51:54 +0000185 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar474b2072010-02-14 01:47:29 +0000186 EndLoc = EndLoc.getFileLocWithOffset(Length);
187 }
188
189 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
190 R.getBegin().getRawEncoding(),
191 EndLoc.getRawEncoding() };
192 return Result;
193}
Douglas Gregor4f46e782010-01-19 21:36:55 +0000194
Ted Kremenek991eb3f2010-01-06 03:42:32 +0000195//===----------------------------------------------------------------------===//
Douglas Gregor562c1f92010-01-22 19:49:59 +0000196// Cursor visitor.
Ted Kremenek991eb3f2010-01-06 03:42:32 +0000197//===----------------------------------------------------------------------===//
198
Steve Naroff1054e602009-08-31 00:59:03 +0000199namespace {
Ted Kremenekf441baf2010-02-17 00:41:40 +0000200
Douglas Gregor71f3d942010-01-20 20:59:29 +0000201// Cursor visitor.
Douglas Gregor93f89952010-01-21 16:28:34 +0000202class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000203 public TypeLocVisitor<CursorVisitor, bool>,
204 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor93f89952010-01-21 16:28:34 +0000205{
Douglas Gregor562c1f92010-01-22 19:49:59 +0000206 /// \brief The translation unit we are traversing.
Douglas Gregorfed36b12010-01-20 23:57:43 +0000207 ASTUnit *TU;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000208
Douglas Gregor562c1f92010-01-22 19:49:59 +0000209 /// \brief The parent cursor whose children we are traversing.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000210 CXCursor Parent;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000211
Douglas Gregor562c1f92010-01-22 19:49:59 +0000212 /// \brief The declaration that serves at the parent of any statement or
213 /// expression nodes.
Douglas Gregord1824312010-01-21 17:29:07 +0000214 Decl *StmtParent;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000215
Douglas Gregor562c1f92010-01-22 19:49:59 +0000216 /// \brief The visitor function.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000217 CXCursorVisitor Visitor;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000218
Douglas Gregor562c1f92010-01-22 19:49:59 +0000219 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000220 CXClientData ClientData;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000221
Douglas Gregor16bef852009-10-16 20:01:17 +0000222 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
223 // to the visitor. Declarations with a PCH level greater than this value will
224 // be suppressed.
225 unsigned MaxPCHLevel;
Douglas Gregor562c1f92010-01-22 19:49:59 +0000226
227 /// \brief When valid, a source range to which the cursor should restrict
228 /// its search.
229 SourceRange RegionOfInterest;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000230
Douglas Gregor71f3d942010-01-20 20:59:29 +0000231 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor93f89952010-01-21 16:28:34 +0000232 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000233 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000234
235 /// \brief Determine whether this particular source range comes before, comes
236 /// after, or overlaps the region of interest.
Douglas Gregor562c1f92010-01-22 19:49:59 +0000237 ///
Daniel Dunbar02968e52010-02-14 10:02:57 +0000238 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf441baf2010-02-17 00:41:40 +0000239 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
240
Ted Kremenek12e0f292010-05-13 00:25:00 +0000241 class SetParentRAII {
242 CXCursor &Parent;
243 Decl *&StmtParent;
244 CXCursor OldParent;
245
246 public:
247 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
248 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
249 {
250 Parent = NewParent;
251 if (clang_isDeclaration(Parent.kind))
252 StmtParent = getCursorDecl(Parent);
253 }
254
255 ~SetParentRAII() {
256 Parent = OldParent;
257 if (clang_isDeclaration(Parent.kind))
258 StmtParent = getCursorDecl(Parent);
259 }
260 };
261
Steve Naroff1054e602009-08-31 00:59:03 +0000262public:
Ted Kremenekf441baf2010-02-17 00:41:40 +0000263 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
264 unsigned MaxPCHLevel,
Douglas Gregor562c1f92010-01-22 19:49:59 +0000265 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf441baf2010-02-17 00:41:40 +0000266 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Douglas Gregor562c1f92010-01-22 19:49:59 +0000267 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest)
Douglas Gregor71f3d942010-01-20 20:59:29 +0000268 {
269 Parent.kind = CXCursor_NoDeclFound;
270 Parent.data[0] = 0;
271 Parent.data[1] = 0;
272 Parent.data[2] = 0;
Douglas Gregord1824312010-01-21 17:29:07 +0000273 StmtParent = 0;
Douglas Gregor71f3d942010-01-20 20:59:29 +0000274 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000275
Douglas Gregor562c1f92010-01-22 19:49:59 +0000276 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor3dc10b52010-03-20 00:41:21 +0000277
278 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
279 getPreprocessedEntities();
280
Douglas Gregor71f3d942010-01-20 20:59:29 +0000281 bool VisitChildren(CXCursor Parent);
Ted Kremenekf441baf2010-02-17 00:41:40 +0000282
Douglas Gregor93f89952010-01-21 16:28:34 +0000283 // Declaration visitors
Ted Kremenek6ab9aa022010-02-18 05:46:33 +0000284 bool VisitAttributes(Decl *D);
Ted Kremenek33b9a422010-04-11 21:47:37 +0000285 bool VisitBlockDecl(BlockDecl *B);
Douglas Gregor71f3d942010-01-20 20:59:29 +0000286 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek7dff4162010-02-18 18:47:08 +0000287 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
288 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremeneke2110252010-02-18 22:36:18 +0000289 bool VisitTagDecl(TagDecl *D);
290 bool VisitEnumConstantDecl(EnumConstantDecl *D);
291 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
292 bool VisitFunctionDecl(FunctionDecl *ND);
293 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek7dff4162010-02-18 18:47:08 +0000294 bool VisitVarDecl(VarDecl *);
Ted Kremeneke2110252010-02-18 22:36:18 +0000295 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
296 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
297 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
298 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek49be9e02010-05-18 21:09:07 +0000299 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremeneke2110252010-02-18 22:36:18 +0000300 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
301 bool VisitObjCImplDecl(ObjCImplDecl *D);
302 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
303 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
304 // FIXME: ObjCPropertyDecl requires TypeSourceInfo, getter/setter locations,
305 // etc.
306 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
307 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
308 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremenekb80cba52010-05-07 01:04:29 +0000309 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenekbd67fb22010-05-06 23:38:21 +0000310 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor93f89952010-01-21 16:28:34 +0000311
312 // Type visitors
Douglas Gregord1824312010-01-21 17:29:07 +0000313 // FIXME: QualifiedTypeLoc doesn't provide any location information
314 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor93f89952010-01-21 16:28:34 +0000315 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregord1824312010-01-21 17:29:07 +0000316 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
317 bool VisitTagTypeLoc(TagTypeLoc TL);
318 // FIXME: TemplateTypeParmTypeLoc doesn't provide any location information
319 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCall8b07ec22010-05-15 11:32:37 +0000320 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregord1824312010-01-21 17:29:07 +0000321 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
322 bool VisitPointerTypeLoc(PointerTypeLoc TL);
323 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
324 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
325 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
326 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
327 bool VisitFunctionTypeLoc(FunctionTypeLoc TL);
328 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregor6479fc42010-01-21 20:48:56 +0000329 // FIXME: Implement for TemplateSpecializationTypeLoc
330 // FIXME: Implement visitors here when the unimplemented TypeLocs get
331 // implemented
332 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
333 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf441baf2010-02-17 00:41:40 +0000334
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000335 // Statement visitors
336 bool VisitStmt(Stmt *S);
337 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregore1084fa2010-01-22 01:00:11 +0000338 // FIXME: LabelStmt label?
339 bool VisitIfStmt(IfStmt *S);
340 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek12e0f292010-05-13 00:25:00 +0000341 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor7201f9f2010-01-25 16:12:32 +0000342 bool VisitWhileStmt(WhileStmt *S);
343 bool VisitForStmt(ForStmt *S);
Ted Kremenek12e0f292010-05-13 00:25:00 +0000344// bool VisitSwitchCase(SwitchCase *S);
Ted Kremenekf441baf2010-02-17 00:41:40 +0000345
Douglas Gregor625a5152010-01-23 00:40:08 +0000346 // Expression visitors
Douglas Gregorb59d21c2010-07-29 00:26:18 +0000347 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek33b9a422010-04-11 21:47:37 +0000348 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor625a5152010-01-23 00:40:08 +0000349 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek33b9a422010-04-11 21:47:37 +0000350 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorde4827d2010-03-08 16:40:19 +0000351 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregorabd9e962010-04-20 15:39:42 +0000352 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor882211c2010-04-28 22:16:22 +0000353 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek33b9a422010-04-11 21:47:37 +0000354 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Steve Naroff1054e602009-08-31 00:59:03 +0000355};
Ted Kremenekf441baf2010-02-17 00:41:40 +0000356
Ted Kremenek0ec2cca2010-01-05 19:32:54 +0000357} // end anonymous namespace
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +0000358
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000359static SourceRange getRawCursorExtent(CXCursor C);
360
Douglas Gregor562c1f92010-01-22 19:49:59 +0000361RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor562c1f92010-01-22 19:49:59 +0000362 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
363}
364
Douglas Gregor71f3d942010-01-20 20:59:29 +0000365/// \brief Visit the given cursor and, if requested by the visitor,
366/// its children.
367///
Douglas Gregor562c1f92010-01-22 19:49:59 +0000368/// \param Cursor the cursor to visit.
369///
370/// \param CheckRegionOfInterest if true, then the caller already checked that
371/// this cursor is within the region of interest.
372///
Douglas Gregor71f3d942010-01-20 20:59:29 +0000373/// \returns true if the visitation should be aborted, false if it
374/// should continue.
Douglas Gregor562c1f92010-01-22 19:49:59 +0000375bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregor71f3d942010-01-20 20:59:29 +0000376 if (clang_isInvalid(Cursor.kind))
377 return false;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000378
Douglas Gregor71f3d942010-01-20 20:59:29 +0000379 if (clang_isDeclaration(Cursor.kind)) {
380 Decl *D = getCursorDecl(Cursor);
381 assert(D && "Invalid declaration cursor");
382 if (D->getPCHLevel() > MaxPCHLevel)
383 return false;
384
385 if (D->isImplicit())
386 return false;
387 }
388
Douglas Gregor562c1f92010-01-22 19:49:59 +0000389 // If we have a range of interest, and this cursor doesn't intersect with it,
390 // we're done.
391 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000392 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbar2f4ba172010-02-14 08:32:05 +0000393 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor562c1f92010-01-22 19:49:59 +0000394 return false;
395 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000396
Douglas Gregor71f3d942010-01-20 20:59:29 +0000397 switch (Visitor(Cursor, Parent, ClientData)) {
398 case CXChildVisit_Break:
399 return true;
400
401 case CXChildVisit_Continue:
402 return false;
403
404 case CXChildVisit_Recurse:
405 return VisitChildren(Cursor);
406 }
407
Douglas Gregor33f16852010-01-25 16:45:46 +0000408 return false;
Douglas Gregor71f3d942010-01-20 20:59:29 +0000409}
410
Douglas Gregor3dc10b52010-03-20 00:41:21 +0000411std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
412CursorVisitor::getPreprocessedEntities() {
413 PreprocessingRecord &PPRec
414 = *TU->getPreprocessor().getPreprocessingRecord();
415
416 bool OnlyLocalDecls
417 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
418
419 // There is no region of interest; we have to walk everything.
420 if (RegionOfInterest.isInvalid())
421 return std::make_pair(PPRec.begin(OnlyLocalDecls),
422 PPRec.end(OnlyLocalDecls));
423
424 // Find the file in which the region of interest lands.
425 SourceManager &SM = TU->getSourceManager();
426 std::pair<FileID, unsigned> Begin
427 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
428 std::pair<FileID, unsigned> End
429 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
430
431 // The region of interest spans files; we have to walk everything.
432 if (Begin.first != End.first)
433 return std::make_pair(PPRec.begin(OnlyLocalDecls),
434 PPRec.end(OnlyLocalDecls));
435
436 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
437 = TU->getPreprocessedEntitiesByFile();
438 if (ByFileMap.empty()) {
439 // Build the mapping from files to sets of preprocessed entities.
440 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
441 EEnd = PPRec.end(OnlyLocalDecls);
442 E != EEnd; ++E) {
443 std::pair<FileID, unsigned> P
444 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
445 ByFileMap[P.first].push_back(*E);
446 }
447 }
448
449 return std::make_pair(ByFileMap[Begin.first].begin(),
450 ByFileMap[Begin.first].end());
451}
452
Douglas Gregor71f3d942010-01-20 20:59:29 +0000453/// \brief Visit the children of the given cursor.
454///
455/// \returns true if the visitation should be aborted, false if it
456/// should continue.
Ted Kremenekf441baf2010-02-17 00:41:40 +0000457bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000458 if (clang_isReference(Cursor.kind)) {
459 // By definition, references have no children.
460 return false;
461 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000462
463 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregor71f3d942010-01-20 20:59:29 +0000464 // done.
Ted Kremenek12e0f292010-05-13 00:25:00 +0000465 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf441baf2010-02-17 00:41:40 +0000466
Douglas Gregor71f3d942010-01-20 20:59:29 +0000467 if (clang_isDeclaration(Cursor.kind)) {
468 Decl *D = getCursorDecl(Cursor);
469 assert(D && "Invalid declaration cursor");
Ted Kremenek0e293092010-02-18 18:47:01 +0000470 return VisitAttributes(D) || Visit(D);
Douglas Gregor71f3d942010-01-20 20:59:29 +0000471 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000472
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000473 if (clang_isStatement(Cursor.kind))
474 return Visit(getCursorStmt(Cursor));
475 if (clang_isExpression(Cursor.kind))
476 return Visit(getCursorExpr(Cursor));
Ted Kremenekf441baf2010-02-17 00:41:40 +0000477
Douglas Gregor71f3d942010-01-20 20:59:29 +0000478 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorfed36b12010-01-20 23:57:43 +0000479 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor562c1f92010-01-22 19:49:59 +0000480 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
481 RegionOfInterest.isInvalid()) {
Douglas Gregore9db88f2010-08-03 19:06:41 +0000482 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
483 TLEnd = CXXUnit->top_level_end();
484 TL != TLEnd; ++TL) {
485 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregorbefc4a12010-01-20 21:13:59 +0000486 return true;
487 }
Douglas Gregor5272e802010-03-19 05:22:59 +0000488 } else if (VisitDeclContext(
489 CXXUnit->getASTContext().getTranslationUnitDecl()))
490 return true;
Bob Wilson4f559a32010-03-19 03:57:57 +0000491
Douglas Gregor5272e802010-03-19 05:22:59 +0000492 // Walk the preprocessing record.
Daniel Dunbaraef1db12010-03-20 01:11:56 +0000493 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor5272e802010-03-19 05:22:59 +0000494 // FIXME: Once we have the ability to deserialize a preprocessing record,
495 // do so.
Douglas Gregor3dc10b52010-03-20 00:41:21 +0000496 PreprocessingRecord::iterator E, EEnd;
497 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor5272e802010-03-19 05:22:59 +0000498 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
499 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
500 return true;
Douglas Gregor3dc10b52010-03-20 00:41:21 +0000501
Douglas Gregor5272e802010-03-19 05:22:59 +0000502 continue;
503 }
504
505 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
506 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
507 return true;
508
509 continue;
510 }
511 }
512 }
Douglas Gregorbefc4a12010-01-20 21:13:59 +0000513 return false;
Douglas Gregor71f3d942010-01-20 20:59:29 +0000514 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000515
Douglas Gregor71f3d942010-01-20 20:59:29 +0000516 // Nothing to visit at the moment.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000517 return false;
518}
519
Ted Kremenek33b9a422010-04-11 21:47:37 +0000520bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCalla3cecb62010-06-04 22:33:30 +0000521 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
522 return true;
Ted Kremenek33b9a422010-04-11 21:47:37 +0000523
Ted Kremenek60fe71a2010-07-22 11:30:19 +0000524 if (Stmt *Body = B->getBody())
525 return Visit(MakeCXCursor(Body, StmtParent, TU));
526
527 return false;
Ted Kremenek33b9a422010-04-11 21:47:37 +0000528}
529
Douglas Gregor71f3d942010-01-20 20:59:29 +0000530bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
Ted Kremenek78668fd2010-01-13 00:22:49 +0000531 for (DeclContext::decl_iterator
Douglas Gregor71f3d942010-01-20 20:59:29 +0000532 I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
Ted Kremenek6ab9aa022010-02-18 05:46:33 +0000533
Ted Kremenek49be9e02010-05-18 21:09:07 +0000534 Decl *D = *I;
535 if (D->getLexicalDeclContext() != DC)
536 continue;
537
538 CXCursor Cursor = MakeCXCursor(D, TU);
Daniel Dunbar02968e52010-02-14 10:02:57 +0000539
Douglas Gregor562c1f92010-01-22 19:49:59 +0000540 if (RegionOfInterest.isValid()) {
Douglas Gregorcd8bdd02010-07-22 20:22:31 +0000541 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbar02968e52010-02-14 10:02:57 +0000542 if (Range.isInvalid())
Douglas Gregor562c1f92010-01-22 19:49:59 +0000543 continue;
Daniel Dunbar02968e52010-02-14 10:02:57 +0000544
545 switch (CompareRegionOfInterest(Range)) {
Douglas Gregor562c1f92010-01-22 19:49:59 +0000546 case RangeBefore:
547 // This declaration comes before the region of interest; skip it.
548 continue;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000549
Douglas Gregor562c1f92010-01-22 19:49:59 +0000550 case RangeAfter:
551 // This declaration comes after the region of interest; we're done.
552 return false;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000553
Douglas Gregor562c1f92010-01-22 19:49:59 +0000554 case RangeOverlap:
555 // This declaration overlaps the region of interest; visit it.
556 break;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000557 }
Douglas Gregor562c1f92010-01-22 19:49:59 +0000558 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000559
Daniel Dunbar02968e52010-02-14 10:02:57 +0000560 if (Visit(Cursor, true))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000561 return true;
562 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000563
Douglas Gregor71f3d942010-01-20 20:59:29 +0000564 return false;
Ted Kremenek78668fd2010-01-13 00:22:49 +0000565}
566
Douglas Gregord824f882010-01-22 00:50:27 +0000567bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
568 llvm_unreachable("Translation units are visited directly by Visit()");
569 return false;
570}
571
572bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
573 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
574 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf441baf2010-02-17 00:41:40 +0000575
Douglas Gregord824f882010-01-22 00:50:27 +0000576 return false;
577}
578
579bool CursorVisitor::VisitTagDecl(TagDecl *D) {
580 return VisitDeclContext(D);
581}
582
583bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
584 if (Expr *Init = D->getInitExpr())
585 return Visit(MakeCXCursor(Init, StmtParent, TU));
586 return false;
587}
588
Douglas Gregor93f89952010-01-21 16:28:34 +0000589bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
590 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
591 if (Visit(TSInfo->getTypeLoc()))
592 return true;
593
594 return false;
595}
596
Douglas Gregor71f3d942010-01-20 20:59:29 +0000597bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregord1824312010-01-21 17:29:07 +0000598 if (VisitDeclaratorDecl(ND))
599 return true;
600
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000601 if (ND->isThisDeclarationADefinition() &&
602 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
603 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000604
Douglas Gregor71f3d942010-01-20 20:59:29 +0000605 return false;
606}
Ted Kremenek78668fd2010-01-13 00:22:49 +0000607
Douglas Gregord824f882010-01-22 00:50:27 +0000608bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
609 if (VisitDeclaratorDecl(D))
610 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000611
Douglas Gregord824f882010-01-22 00:50:27 +0000612 if (Expr *BitWidth = D->getBitWidth())
613 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf441baf2010-02-17 00:41:40 +0000614
Douglas Gregord824f882010-01-22 00:50:27 +0000615 return false;
616}
617
618bool CursorVisitor::VisitVarDecl(VarDecl *D) {
619 if (VisitDeclaratorDecl(D))
620 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000621
Douglas Gregord824f882010-01-22 00:50:27 +0000622 if (Expr *Init = D->getInit())
623 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf441baf2010-02-17 00:41:40 +0000624
Douglas Gregord824f882010-01-22 00:50:27 +0000625 return false;
626}
627
628bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor12852d92010-03-08 14:59:44 +0000629 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
630 if (Visit(TSInfo->getTypeLoc()))
631 return true;
632
Ted Kremenekf441baf2010-02-17 00:41:40 +0000633 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregord824f882010-01-22 00:50:27 +0000634 PEnd = ND->param_end();
635 P != PEnd; ++P) {
636 if (Visit(MakeCXCursor(*P, TU)))
637 return true;
638 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000639
Douglas Gregord824f882010-01-22 00:50:27 +0000640 if (ND->isThisDeclarationADefinition() &&
641 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
642 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000643
Douglas Gregord824f882010-01-22 00:50:27 +0000644 return false;
645}
646
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000647bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
648 return VisitDeclContext(D);
649}
650
Douglas Gregor71f3d942010-01-20 20:59:29 +0000651bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorfed36b12010-01-20 23:57:43 +0000652 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
653 TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000654 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000655
Douglas Gregoref6eb842010-01-16 15:44:18 +0000656 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
657 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
658 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorfed36b12010-01-20 23:57:43 +0000659 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000660 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000661
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000662 return VisitObjCContainerDecl(ND);
Ted Kremenek78668fd2010-01-13 00:22:49 +0000663}
664
Douglas Gregord824f882010-01-22 00:50:27 +0000665bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
666 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
667 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
668 E = PID->protocol_end(); I != E; ++I, ++PL)
669 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
670 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000671
Douglas Gregord824f882010-01-22 00:50:27 +0000672 return VisitObjCContainerDecl(PID);
673}
674
Ted Kremenek49be9e02010-05-18 21:09:07 +0000675bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
John McCalla3cecb62010-06-04 22:33:30 +0000676 if (Visit(PD->getTypeSourceInfo()->getTypeLoc()))
677 return true;
678
Ted Kremenek49be9e02010-05-18 21:09:07 +0000679 // FIXME: This implements a workaround with @property declarations also being
680 // installed in the DeclContext for the @interface. Eventually this code
681 // should be removed.
682 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
683 if (!CDecl || !CDecl->IsClassExtension())
684 return false;
685
686 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
687 if (!ID)
688 return false;
689
690 IdentifierInfo *PropertyId = PD->getIdentifier();
691 ObjCPropertyDecl *prevDecl =
692 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
693
694 if (!prevDecl)
695 return false;
696
697 // Visit synthesized methods since they will be skipped when visiting
698 // the @interface.
699 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
700 if (MD->isSynthesized())
701 if (Visit(MakeCXCursor(MD, TU)))
702 return true;
703
704 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
705 if (MD->isSynthesized())
706 if (Visit(MakeCXCursor(MD, TU)))
707 return true;
708
709 return false;
710}
711
Douglas Gregor71f3d942010-01-20 20:59:29 +0000712bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenek78668fd2010-01-13 00:22:49 +0000713 // Issue callbacks for super class.
Douglas Gregor71f3d942010-01-20 20:59:29 +0000714 if (D->getSuperClass() &&
715 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf441baf2010-02-17 00:41:40 +0000716 D->getSuperClassLoc(),
Douglas Gregorfed36b12010-01-20 23:57:43 +0000717 TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000718 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000719
Douglas Gregoref6eb842010-01-16 15:44:18 +0000720 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
721 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
722 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorfed36b12010-01-20 23:57:43 +0000723 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000724 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000725
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000726 return VisitObjCContainerDecl(D);
Ted Kremenek78668fd2010-01-13 00:22:49 +0000727}
728
Douglas Gregord824f882010-01-22 00:50:27 +0000729bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
730 return VisitObjCContainerDecl(D);
Ted Kremenek78668fd2010-01-13 00:22:49 +0000731}
732
Douglas Gregord824f882010-01-22 00:50:27 +0000733bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremeneke184ac52010-03-19 20:39:03 +0000734 // 'ID' could be null when dealing with invalid code.
735 if (ObjCInterfaceDecl *ID = D->getClassInterface())
736 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
737 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000738
Douglas Gregord824f882010-01-22 00:50:27 +0000739 return VisitObjCImplDecl(D);
740}
741
742bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
743#if 0
744 // Issue callbacks for super class.
745 // FIXME: No source location information!
746 if (D->getSuperClass() &&
747 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf441baf2010-02-17 00:41:40 +0000748 D->getSuperClassLoc(),
Douglas Gregord824f882010-01-22 00:50:27 +0000749 TU)))
750 return true;
751#endif
Ted Kremenekf441baf2010-02-17 00:41:40 +0000752
Douglas Gregord824f882010-01-22 00:50:27 +0000753 return VisitObjCImplDecl(D);
754}
755
756bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
757 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
758 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
759 E = D->protocol_end();
760 I != E; ++I, ++PL)
Douglas Gregorfed36b12010-01-20 23:57:43 +0000761 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregor71f3d942010-01-20 20:59:29 +0000762 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000763
764 return false;
Ted Kremenek78668fd2010-01-13 00:22:49 +0000765}
766
Douglas Gregord824f882010-01-22 00:50:27 +0000767bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
768 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
769 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
770 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +0000771
Douglas Gregord824f882010-01-22 00:50:27 +0000772 return false;
Ted Kremenek78668fd2010-01-13 00:22:49 +0000773}
774
Ted Kremenekbd67fb22010-05-06 23:38:21 +0000775bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
776 return VisitDeclContext(D);
777}
778
Ted Kremenekb80cba52010-05-07 01:04:29 +0000779bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
780 return VisitDeclContext(D);
781}
782
Douglas Gregord1824312010-01-21 17:29:07 +0000783bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
784 ASTContext &Context = TU->getASTContext();
785
786 // Some builtin types (such as Objective-C's "id", "sel", and
787 // "Class") have associated declarations. Create cursors for those.
788 QualType VisitType;
789 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000790 case BuiltinType::Void:
Douglas Gregord1824312010-01-21 17:29:07 +0000791 case BuiltinType::Bool:
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000792 case BuiltinType::Char_U:
793 case BuiltinType::UChar:
Douglas Gregord1824312010-01-21 17:29:07 +0000794 case BuiltinType::Char16:
795 case BuiltinType::Char32:
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000796 case BuiltinType::UShort:
Douglas Gregord1824312010-01-21 17:29:07 +0000797 case BuiltinType::UInt:
798 case BuiltinType::ULong:
799 case BuiltinType::ULongLong:
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000800 case BuiltinType::UInt128:
801 case BuiltinType::Char_S:
802 case BuiltinType::SChar:
Douglas Gregord1824312010-01-21 17:29:07 +0000803 case BuiltinType::WChar:
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000804 case BuiltinType::Short:
805 case BuiltinType::Int:
806 case BuiltinType::Long:
807 case BuiltinType::LongLong:
808 case BuiltinType::Int128:
809 case BuiltinType::Float:
810 case BuiltinType::Double:
811 case BuiltinType::LongDouble:
812 case BuiltinType::NullPtr:
813 case BuiltinType::Overload:
814 case BuiltinType::Dependent:
Douglas Gregord1824312010-01-21 17:29:07 +0000815 break;
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000816
817 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregord1824312010-01-21 17:29:07 +0000818 break;
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000819
Ted Kremenekfcb3db72010-02-18 18:52:18 +0000820 case BuiltinType::ObjCId:
821 VisitType = Context.getObjCIdType();
822 break;
Ted Kremenekaaaf2bf2010-02-18 22:32:43 +0000823
824 case BuiltinType::ObjCClass:
825 VisitType = Context.getObjCClassType();
826 break;
827
Douglas Gregord1824312010-01-21 17:29:07 +0000828 case BuiltinType::ObjCSel:
829 VisitType = Context.getObjCSelType();
830 break;
831 }
832
833 if (!VisitType.isNull()) {
834 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf441baf2010-02-17 00:41:40 +0000835 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregord1824312010-01-21 17:29:07 +0000836 TU));
837 }
838
839 return false;
840}
841
Douglas Gregor93f89952010-01-21 16:28:34 +0000842bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
843 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
844}
845
Douglas Gregord1824312010-01-21 17:29:07 +0000846bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
847 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
848}
849
850bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
851 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
852}
853
854bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
855 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
856 return true;
857
John McCall8b07ec22010-05-15 11:32:37 +0000858 return false;
859}
860
861bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
862 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
863 return true;
864
Douglas Gregord1824312010-01-21 17:29:07 +0000865 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
866 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
867 TU)))
868 return true;
869 }
870
871 return false;
872}
873
874bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCall8b07ec22010-05-15 11:32:37 +0000875 return Visit(TL.getPointeeLoc());
Douglas Gregord1824312010-01-21 17:29:07 +0000876}
877
878bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
879 return Visit(TL.getPointeeLoc());
880}
881
882bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
883 return Visit(TL.getPointeeLoc());
884}
885
886bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
887 return Visit(TL.getPointeeLoc());
888}
889
890bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf441baf2010-02-17 00:41:40 +0000891 return Visit(TL.getPointeeLoc());
Douglas Gregord1824312010-01-21 17:29:07 +0000892}
893
894bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf441baf2010-02-17 00:41:40 +0000895 return Visit(TL.getPointeeLoc());
Douglas Gregord1824312010-01-21 17:29:07 +0000896}
897
898bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
899 if (Visit(TL.getResultLoc()))
900 return true;
901
Douglas Gregord1824312010-01-21 17:29:07 +0000902 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek6ca136a2010-04-07 00:27:13 +0000903 if (Decl *D = TL.getArg(I))
904 if (Visit(MakeCXCursor(D, TU)))
905 return true;
Douglas Gregord1824312010-01-21 17:29:07 +0000906
907 return false;
908}
909
910bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
911 if (Visit(TL.getElementLoc()))
912 return true;
913
914 if (Expr *Size = TL.getSizeExpr())
915 return Visit(MakeCXCursor(Size, StmtParent, TU));
916
917 return false;
918}
919
Douglas Gregor6479fc42010-01-21 20:48:56 +0000920bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
921 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
922}
923
924bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
925 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
926 return Visit(TSInfo->getTypeLoc());
927
928 return false;
929}
930
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000931bool CursorVisitor::VisitStmt(Stmt *S) {
932 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
933 Child != ChildEnd; ++Child) {
Ted Kremenek12e0f292010-05-13 00:25:00 +0000934 if (Stmt *C = *Child)
935 if (Visit(MakeCXCursor(C, StmtParent, TU)))
936 return true;
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000937 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000938
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000939 return false;
940}
941
Ted Kremenek12e0f292010-05-13 00:25:00 +0000942bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
943 // Specially handle CaseStmts because they can be nested, e.g.:
944 //
945 // case 1:
946 // case 2:
947 //
948 // In this case the second CaseStmt is the child of the first. Walking
949 // these recursively can blow out the stack.
950 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
951 while (true) {
952 // Set the Parent field to Cursor, then back to its old value once we're
953 // done.
954 SetParentRAII SetParent(Parent, StmtParent, Cursor);
955
956 if (Stmt *LHS = S->getLHS())
957 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
958 return true;
959 if (Stmt *RHS = S->getRHS())
960 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
961 return true;
962 if (Stmt *SubStmt = S->getSubStmt()) {
963 if (!isa<CaseStmt>(SubStmt))
964 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
965
966 // Specially handle 'CaseStmt' so that we don't blow out the stack.
967 CaseStmt *CS = cast<CaseStmt>(SubStmt);
968 Cursor = MakeCXCursor(CS, StmtParent, TU);
969 if (RegionOfInterest.isValid()) {
970 SourceRange Range = CS->getSourceRange();
971 if (Range.isInvalid() || CompareRegionOfInterest(Range))
972 return false;
973 }
974
975 switch (Visitor(Cursor, Parent, ClientData)) {
976 case CXChildVisit_Break: return true;
977 case CXChildVisit_Continue: return false;
978 case CXChildVisit_Recurse:
979 // Perform tail-recursion manually.
980 S = CS;
981 continue;
982 }
983 }
984 return false;
985 }
986}
987
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000988bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
989 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
990 D != DEnd; ++D) {
Douglas Gregor7201f9f2010-01-25 16:12:32 +0000991 if (*D && Visit(MakeCXCursor(*D, TU)))
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000992 return true;
993 }
Ted Kremenekf441baf2010-02-17 00:41:40 +0000994
Douglas Gregor5e8cf372010-01-21 23:27:09 +0000995 return false;
996}
997
Douglas Gregore1084fa2010-01-22 01:00:11 +0000998bool CursorVisitor::VisitIfStmt(IfStmt *S) {
999 if (VarDecl *Var = S->getConditionVariable()) {
1000 if (Visit(MakeCXCursor(Var, TU)))
1001 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001002 }
1003
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001004 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1005 return true;
Douglas Gregore1084fa2010-01-22 01:00:11 +00001006 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1007 return true;
Douglas Gregore1084fa2010-01-22 01:00:11 +00001008 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1009 return true;
1010
1011 return false;
1012}
1013
1014bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1015 if (VarDecl *Var = S->getConditionVariable()) {
1016 if (Visit(MakeCXCursor(Var, TU)))
1017 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001018 }
1019
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001020 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1021 return true;
1022 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1023 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001024
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001025 return false;
1026}
1027
1028bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1029 if (VarDecl *Var = S->getConditionVariable()) {
1030 if (Visit(MakeCXCursor(Var, TU)))
1031 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001032 }
1033
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001034 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1035 return true;
1036 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregore1084fa2010-01-22 01:00:11 +00001037 return true;
1038
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001039 return false;
1040}
1041
1042bool CursorVisitor::VisitForStmt(ForStmt *S) {
1043 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1044 return true;
1045 if (VarDecl *Var = S->getConditionVariable()) {
1046 if (Visit(MakeCXCursor(Var, TU)))
1047 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001048 }
1049
Douglas Gregor7201f9f2010-01-25 16:12:32 +00001050 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1051 return true;
1052 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1053 return true;
Douglas Gregore1084fa2010-01-22 01:00:11 +00001054 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1055 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001056
Douglas Gregore1084fa2010-01-22 01:00:11 +00001057 return false;
1058}
1059
Douglas Gregorb59d21c2010-07-29 00:26:18 +00001060bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1061 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1062 return true;
1063
1064 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1065 return true;
1066
1067 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1068 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1069 return true;
1070
1071 return false;
1072}
1073
Ted Kremenek33b9a422010-04-11 21:47:37 +00001074bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1075 return Visit(B->getBlockDecl());
1076}
1077
Douglas Gregor882211c2010-04-28 22:16:22 +00001078bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
1079 // FIXME: Visit fields as well?
1080 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1081 return true;
1082
1083 return VisitExpr(E);
1084}
1085
Douglas Gregor625a5152010-01-23 00:40:08 +00001086bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1087 if (E->isArgumentType()) {
1088 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1089 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf441baf2010-02-17 00:41:40 +00001090
Douglas Gregor625a5152010-01-23 00:40:08 +00001091 return false;
1092 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001093
Douglas Gregor625a5152010-01-23 00:40:08 +00001094 return VisitExpr(E);
1095}
1096
1097bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1098 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1099 if (Visit(TSInfo->getTypeLoc()))
1100 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001101
Douglas Gregor625a5152010-01-23 00:40:08 +00001102 return VisitCastExpr(E);
1103}
1104
1105bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1106 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1107 if (Visit(TSInfo->getTypeLoc()))
1108 return true;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001109
Douglas Gregor625a5152010-01-23 00:40:08 +00001110 return VisitExpr(E);
1111}
1112
Douglas Gregorde4827d2010-03-08 16:40:19 +00001113bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor9a129192010-04-21 00:45:42 +00001114 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1115 if (Visit(TSInfo->getTypeLoc()))
1116 return true;
Douglas Gregorde4827d2010-03-08 16:40:19 +00001117
1118 return VisitExpr(E);
1119}
1120
Douglas Gregorabd9e962010-04-20 15:39:42 +00001121bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1122 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1123}
1124
1125
Ted Kremenek6ab9aa022010-02-18 05:46:33 +00001126bool CursorVisitor::VisitAttributes(Decl *D) {
1127 for (const Attr *A = D->getAttrs(); A; A = A->getNext())
1128 if (Visit(MakeCXCursor(A, D, TU)))
1129 return true;
1130
1131 return false;
1132}
1133
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +00001134extern "C" {
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001135CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
1136 int displayDiagnostics) {
Douglas Gregor87752492010-01-22 20:35:53 +00001137 CIndexer *CIdxr = new CIndexer();
Steve Naroff531e2842009-10-20 14:46:24 +00001138 if (excludeDeclarationsFromPCH)
1139 CIdxr->setOnlyLocalDecls();
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001140 if (displayDiagnostics)
1141 CIdxr->setDisplayDiagnostics();
Steve Naroff531e2842009-10-20 14:46:24 +00001142 return CIdxr;
Steve Naroffd5e8e862009-08-27 19:51:58 +00001143}
1144
Daniel Dunbar079203f2009-12-01 03:14:51 +00001145void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001146 if (CIdx)
1147 delete static_cast<CIndexer *>(CIdx);
Douglas Gregor8ef4c802010-08-09 21:00:09 +00001148 if (getenv("LIBCLANG_TIMING"))
1149 llvm::TimerGroup::printAll(llvm::errs());
Steve Naroff3aa2d732009-09-17 18:33:27 +00001150}
1151
Daniel Dunbar11089662009-12-03 01:54:28 +00001152void clang_setUseExternalASTGeneration(CXIndex CIdx, int value) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001153 if (CIdx) {
1154 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1155 CXXIdx->setUseExternalASTGeneration(value);
1156 }
Daniel Dunbar11089662009-12-03 01:54:28 +00001157}
1158
Daniel Dunbar079203f2009-12-01 03:14:51 +00001159CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001160 const char *ast_filename) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001161 if (!CIdx)
1162 return 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001163
Douglas Gregor16bef852009-10-16 20:01:17 +00001164 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001165
Douglas Gregor7f95d262010-04-05 23:52:57 +00001166 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1167 return ASTUnit::LoadFromPCHFile(ast_filename, Diags,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001168 CXXIdx->getOnlyLocalDecls(),
1169 0, 0, true);
Steve Naroffd5e8e862009-08-27 19:51:58 +00001170}
1171
Douglas Gregor4a47bca2010-08-09 22:28:58 +00001172unsigned clang_defaultEditingTranslationUnitOptions() {
1173 return CXTranslationUnit_PrecompiledPreamble;
1174}
1175
Daniel Dunbar079203f2009-12-01 03:14:51 +00001176CXTranslationUnit
1177clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
1178 const char *source_filename,
1179 int num_command_line_args,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001180 const char **command_line_args,
1181 unsigned num_unsaved_files,
Douglas Gregor33cdd812010-02-18 18:08:43 +00001182 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor99d2cf42010-07-21 18:52:53 +00001183 return clang_parseTranslationUnit(CIdx, source_filename,
1184 command_line_args, num_command_line_args,
1185 unsaved_files, num_unsaved_files,
1186 CXTranslationUnit_DetailedPreprocessingRecord);
1187}
1188
1189CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
1190 const char *source_filename,
1191 const char **command_line_args,
1192 int num_command_line_args,
1193 struct CXUnsavedFile *unsaved_files,
1194 unsigned num_unsaved_files,
1195 unsigned options) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001196 if (!CIdx)
1197 return 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001198
Steve Naroff531e2842009-10-20 14:46:24 +00001199 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
1200
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001201 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregor028d3e42010-08-09 20:45:32 +00001202 bool CompleteTranslationUnit
1203 = ((options & CXTranslationUnit_Incomplete) == 0);
1204
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001205 // Configure the diagnostics.
1206 DiagnosticOptions DiagOpts;
Douglas Gregor7f95d262010-04-05 23:52:57 +00001207 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
1208 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001209
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001210 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1211 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattner58c79342010-04-05 22:42:27 +00001212 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001213 const llvm::MemoryBuffer *Buffer
Chris Lattner58c79342010-04-05 22:42:27 +00001214 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001215 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1216 Buffer));
1217 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001218
Daniel Dunbar11089662009-12-03 01:54:28 +00001219 if (!CXXIdx->getUseExternalASTGeneration()) {
1220 llvm::SmallVector<const char *, 16> Args;
1221
1222 // The 'source_filename' argument is optional. If the caller does not
1223 // specify it then it is assumed that the source file is specified
1224 // in the actual argument list.
1225 if (source_filename)
1226 Args.push_back(source_filename);
Douglas Gregor79edde82010-07-09 18:39:07 +00001227
1228 // Since the Clang C library is primarily used by batch tools dealing with
1229 // (often very broken) source code, where spell-checking can have a
1230 // significant negative impact on performance (particularly when
1231 // precompiled headers are involved), we disable it by default.
1232 // Note that we place this argument early in the list, so that it can be
1233 // overridden by the caller with "-fspell-checking".
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00001234 Args.push_back("-fno-spell-checking");
Douglas Gregor79edde82010-07-09 18:39:07 +00001235
Daniel Dunbar11089662009-12-03 01:54:28 +00001236 Args.insert(Args.end(), command_line_args,
1237 command_line_args + num_command_line_args);
Douglas Gregor99d2cf42010-07-21 18:52:53 +00001238
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001239 // Do we need the detailed preprocessing record?
Douglas Gregor99d2cf42010-07-21 18:52:53 +00001240 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1241 Args.push_back("-Xclang");
1242 Args.push_back("-detailed-preprocessing-record");
1243 }
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001244
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001245 unsigned NumErrors = Diags->getNumErrors();
Ted Kremenekf441baf2010-02-17 00:41:40 +00001246
Ted Kremenek7a5ede22010-01-07 22:49:05 +00001247#ifdef USE_CRASHTRACER
1248 ArgsCrashTracerInfo ACTI(Args);
Ted Kremenek991eb3f2010-01-06 03:42:32 +00001249#endif
Ted Kremenekf441baf2010-02-17 00:41:40 +00001250
Daniel Dunbar72fe5b12009-12-05 02:17:18 +00001251 llvm::OwningPtr<ASTUnit> Unit(
1252 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
Douglas Gregord03e8232010-04-05 21:10:19 +00001253 Diags,
Daniel Dunbar8d4a2022009-12-13 03:46:13 +00001254 CXXIdx->getClangResourcesPath(),
Daniel Dunbar72fe5b12009-12-05 02:17:18 +00001255 CXXIdx->getOnlyLocalDecls(),
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001256 RemappedFiles.data(),
Douglas Gregor33cdd812010-02-18 18:08:43 +00001257 RemappedFiles.size(),
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001258 /*CaptureDiagnostics=*/true,
Douglas Gregor028d3e42010-08-09 20:45:32 +00001259 PrecompilePreamble,
1260 CompleteTranslationUnit));
Ted Kremenekf441baf2010-02-17 00:41:40 +00001261
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001262 if (NumErrors != Diags->getNumErrors()) {
Ted Kremeneka6d3ab32010-03-05 22:43:29 +00001263 // Make sure to check that 'Unit' is non-NULL.
1264 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
Douglas Gregora2433152010-04-05 18:10:21 +00001265 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
1266 DEnd = Unit->stored_diag_end();
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001267 D != DEnd; ++D) {
1268 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
Douglas Gregord770f732010-02-22 23:17:23 +00001269 CXString Msg = clang_formatDiagnostic(&Diag,
1270 clang_defaultDiagnosticDisplayOptions());
1271 fprintf(stderr, "%s\n", clang_getCString(Msg));
1272 clang_disposeString(Msg);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001273 }
Douglas Gregord770f732010-02-22 23:17:23 +00001274#ifdef LLVM_ON_WIN32
1275 // On Windows, force a flush, since there may be multiple copies of
1276 // stderr and stdout in the file system, all with different buffers
1277 // but writing to the same device.
1278 fflush(stderr);
Ted Kremenek014e70b2010-03-26 01:34:51 +00001279#endif
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001280 }
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001281 }
Daniel Dunbar72fe5b12009-12-05 02:17:18 +00001282
1283 return Unit.take();
Daniel Dunbar11089662009-12-03 01:54:28 +00001284 }
1285
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001286 // Build up the arguments for invoking 'clang'.
Ted Kremenek51d06bb2009-10-15 23:21:22 +00001287 std::vector<const char *> argv;
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001288
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001289 // First add the complete path to the 'clang' executable.
1290 llvm::sys::Path ClangPath = static_cast<CIndexer *>(CIdx)->getClangPath();
Benjamin Kramer61f5d0c2009-10-18 16:11:04 +00001291 argv.push_back(ClangPath.c_str());
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001292
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001293 // Add the '-emit-ast' option as our execution mode for 'clang'.
Ted Kremenek51d06bb2009-10-15 23:21:22 +00001294 argv.push_back("-emit-ast");
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001295
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001296 // The 'source_filename' argument is optional. If the caller does not
1297 // specify it then it is assumed that the source file is specified
1298 // in the actual argument list.
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001299 if (source_filename)
1300 argv.push_back(source_filename);
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001301
Steve Naroff1cfb96c2009-10-15 20:50:09 +00001302 // Generate a temporary name for the AST file.
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001303 argv.push_back("-o");
Benjamin Kramerf156b9d2010-03-13 21:22:49 +00001304 char astTmpFile[L_tmpnam];
1305 argv.push_back(tmpnam(astTmpFile));
Douglas Gregor79edde82010-07-09 18:39:07 +00001306
1307 // Since the Clang C library is primarily used by batch tools dealing with
1308 // (often very broken) source code, where spell-checking can have a
1309 // significant negative impact on performance (particularly when
1310 // precompiled headers are involved), we disable it by default.
1311 // Note that we place this argument early in the list, so that it can be
1312 // overridden by the caller with "-fspell-checking".
Douglas Gregor8ed0c0b2010-07-09 17:35:33 +00001313 argv.push_back("-fno-spell-checking");
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001314
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001315 // Remap any unsaved files to temporary files.
1316 std::vector<llvm::sys::Path> TemporaryFiles;
1317 std::vector<std::string> RemapArgs;
1318 if (RemapFiles(num_unsaved_files, unsaved_files, RemapArgs, TemporaryFiles))
1319 return 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001320
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001321 // The pointers into the elements of RemapArgs are stable because we
1322 // won't be adding anything to RemapArgs after this point.
1323 for (unsigned i = 0, e = RemapArgs.size(); i != e; ++i)
1324 argv.push_back(RemapArgs[i].c_str());
Ted Kremenekf441baf2010-02-17 00:41:40 +00001325
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001326 // Process the compiler options, stripping off '-o', '-c', '-fsyntax-only'.
1327 for (int i = 0; i < num_command_line_args; ++i)
1328 if (const char *arg = command_line_args[i]) {
1329 if (strcmp(arg, "-o") == 0) {
1330 ++i; // Also skip the matching argument.
1331 continue;
1332 }
1333 if (strcmp(arg, "-emit-ast") == 0 ||
1334 strcmp(arg, "-c") == 0 ||
1335 strcmp(arg, "-fsyntax-only") == 0) {
1336 continue;
1337 }
1338
1339 // Keep the argument.
1340 argv.push_back(arg);
Steve Naroff531e2842009-10-20 14:46:24 +00001341 }
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001342
Douglas Gregorac0605e2010-01-28 06:00:51 +00001343 // Generate a temporary name for the diagnostics file.
Benjamin Kramerf156b9d2010-03-13 21:22:49 +00001344 char tmpFileResults[L_tmpnam];
1345 char *tmpResultsFileName = tmpnam(tmpFileResults);
1346 llvm::sys::Path DiagnosticsFile(tmpResultsFileName);
Douglas Gregorac0605e2010-01-28 06:00:51 +00001347 TemporaryFiles.push_back(DiagnosticsFile);
1348 argv.push_back("-fdiagnostics-binary");
1349
Douglas Gregorbe2d8c62010-07-23 00:33:23 +00001350 // Do we need the detailed preprocessing record?
1351 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
1352 argv.push_back("-Xclang");
1353 argv.push_back("-detailed-preprocessing-record");
1354 }
1355
Ted Kremenek649bf5c2009-10-22 00:03:57 +00001356 // Add the null terminator.
Ted Kremenek51d06bb2009-10-15 23:21:22 +00001357 argv.push_back(NULL);
1358
Ted Kremenek12e678d2009-10-26 22:14:08 +00001359 // Invoke 'clang'.
1360 llvm::sys::Path DevNull; // leave empty, causes redirection to /dev/null
1361 // on Unix or NUL (Windows).
Ted Kremenek44886fd2009-10-22 03:24:01 +00001362 std::string ErrMsg;
Douglas Gregorac0605e2010-01-28 06:00:51 +00001363 const llvm::sys::Path *Redirects[] = { &DevNull, &DevNull, &DiagnosticsFile,
1364 NULL };
Ted Kremenek44886fd2009-10-22 03:24:01 +00001365 llvm::sys::Program::ExecuteAndWait(ClangPath, &argv[0], /* env */ NULL,
Douglas Gregorba965fb2010-01-28 00:56:43 +00001366 /* redirects */ &Redirects[0],
Ted Kremenek44886fd2009-10-22 03:24:01 +00001367 /* secondsToWait */ 0, /* memoryLimits */ 0, &ErrMsg);
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001368
Douglas Gregorba965fb2010-01-28 00:56:43 +00001369 if (!ErrMsg.empty()) {
1370 std::string AllArgs;
Ted Kremenek44886fd2009-10-22 03:24:01 +00001371 for (std::vector<const char*>::iterator I = argv.begin(), E = argv.end();
Douglas Gregorba965fb2010-01-28 00:56:43 +00001372 I != E; ++I) {
1373 AllArgs += ' ';
Ted Kremenekbf0690c2009-10-26 22:08:39 +00001374 if (*I)
Douglas Gregorba965fb2010-01-28 00:56:43 +00001375 AllArgs += *I;
Ted Kremenekbf0690c2009-10-26 22:08:39 +00001376 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001377
Daniel Dunbar253dbad2010-02-23 20:23:45 +00001378 Diags->Report(diag::err_fe_invoking) << AllArgs << ErrMsg;
Ted Kremenek44886fd2009-10-22 03:24:01 +00001379 }
Benjamin Kramer2836c4c2009-10-18 11:19:36 +00001380
Douglas Gregord03e8232010-04-05 21:10:19 +00001381 ASTUnit *ATU = ASTUnit::LoadFromPCHFile(astTmpFile, Diags,
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001382 CXXIdx->getOnlyLocalDecls(),
Douglas Gregoraa98ed92010-01-23 00:14:00 +00001383 RemappedFiles.data(),
Douglas Gregor33cdd812010-02-18 18:08:43 +00001384 RemappedFiles.size(),
1385 /*CaptureDiagnostics=*/true);
Douglas Gregor33cdd812010-02-18 18:08:43 +00001386 if (ATU) {
1387 LoadSerializedDiagnostics(DiagnosticsFile,
1388 num_unsaved_files, unsaved_files,
1389 ATU->getFileManager(),
1390 ATU->getSourceManager(),
Douglas Gregora2433152010-04-05 18:10:21 +00001391 ATU->getStoredDiagnostics());
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001392 } else if (CXXIdx->getDisplayDiagnostics()) {
1393 // We failed to load the ASTUnit, but we can still deserialize the
1394 // diagnostics and emit them.
1395 FileManager FileMgr;
Douglas Gregore0fbb832010-03-16 00:06:06 +00001396 Diagnostic Diag;
1397 SourceManager SourceMgr(Diag);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001398 // FIXME: Faked LangOpts!
1399 LangOptions LangOpts;
1400 llvm::SmallVector<StoredDiagnostic, 4> Diags;
1401 LoadSerializedDiagnostics(DiagnosticsFile,
1402 num_unsaved_files, unsaved_files,
1403 FileMgr, SourceMgr, Diags);
1404 for (llvm::SmallVector<StoredDiagnostic, 4>::iterator D = Diags.begin(),
1405 DEnd = Diags.end();
1406 D != DEnd; ++D) {
1407 CXStoredDiagnostic Diag(*D, LangOpts);
Douglas Gregord770f732010-02-22 23:17:23 +00001408 CXString Msg = clang_formatDiagnostic(&Diag,
1409 clang_defaultDiagnosticDisplayOptions());
1410 fprintf(stderr, "%s\n", clang_getCString(Msg));
1411 clang_disposeString(Msg);
Douglas Gregor1e21cc72010-02-18 23:07:20 +00001412 }
Douglas Gregord770f732010-02-22 23:17:23 +00001413
1414#ifdef LLVM_ON_WIN32
1415 // On Windows, force a flush, since there may be multiple copies of
1416 // stderr and stdout in the file system, all with different buffers
1417 // but writing to the same device.
1418 fflush(stderr);
1419#endif
Douglas Gregor33cdd812010-02-18 18:08:43 +00001420 }
Douglas Gregorac0605e2010-01-28 06:00:51 +00001421
Douglas Gregor6cb5ba42010-02-18 23:35:40 +00001422 if (ATU) {
1423 // Make the translation unit responsible for destroying all temporary files.
1424 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1425 ATU->addTemporaryFile(TemporaryFiles[i]);
1426 ATU->addTemporaryFile(llvm::sys::Path(ATU->getPCHFileName()));
1427 } else {
1428 // Destroy all of the temporary files now; they can't be referenced any
1429 // longer.
1430 llvm::sys::Path(astTmpFile).eraseFromDisk();
1431 for (unsigned i = 0, e = TemporaryFiles.size(); i != e; ++i)
1432 TemporaryFiles[i].eraseFromDisk();
1433 }
1434
Steve Naroff44cd60e2009-10-15 22:23:48 +00001435 return ATU;
Steve Naroff7781daa2009-10-15 20:04:39 +00001436}
1437
Daniel Dunbar079203f2009-12-01 03:14:51 +00001438void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001439 if (CTUnit)
1440 delete static_cast<ASTUnit *>(CTUnit);
Steve Naroff3aa2d732009-09-17 18:33:27 +00001441}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001442
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001443int clang_reparseTranslationUnit(CXTranslationUnit TU,
1444 unsigned num_unsaved_files,
1445 struct CXUnsavedFile *unsaved_files) {
1446 if (!TU)
1447 return 1;
1448
1449 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
1450 for (unsigned I = 0; I != num_unsaved_files; ++I) {
1451 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
1452 const llvm::MemoryBuffer *Buffer
Douglas Gregor8e984da2010-08-04 16:47:14 +00001453 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregoraa21cc42010-07-19 21:46:24 +00001454 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
1455 Buffer));
1456 }
1457
1458 return static_cast<ASTUnit *>(TU)->Reparse(RemappedFiles.data(),
1459 RemappedFiles.size())? 1 : 0;
1460}
Douglas Gregor028d3e42010-08-09 20:45:32 +00001461
Daniel Dunbar079203f2009-12-01 03:14:51 +00001462CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor69ff5dc2010-01-29 00:47:48 +00001463 if (!CTUnit)
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001464 return createCXString("");
Ted Kremenekf441baf2010-02-17 00:41:40 +00001465
Steve Naroffc0683b92009-09-03 18:19:54 +00001466 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001467 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroff38c1a7b2009-09-03 15:49:00 +00001468}
Daniel Dunbare58bd8b2009-08-28 16:30:07 +00001469
Douglas Gregord2fc7272010-01-20 00:23:15 +00001470CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00001471 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregord2fc7272010-01-20 00:23:15 +00001472 return Result;
1473}
1474
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001475} // end: extern "C"
Steve Naroffd5e8e862009-08-27 19:51:58 +00001476
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001477//===----------------------------------------------------------------------===//
Douglas Gregor4f46e782010-01-19 21:36:55 +00001478// CXSourceLocation and CXSourceRange Operations.
1479//===----------------------------------------------------------------------===//
1480
Douglas Gregor816fd362010-01-22 21:44:22 +00001481extern "C" {
1482CXSourceLocation clang_getNullLocation() {
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001483 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregor816fd362010-01-22 21:44:22 +00001484 return Result;
1485}
1486
1487unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar83a23542010-01-30 23:58:27 +00001488 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
1489 loc1.ptr_data[1] == loc2.ptr_data[1] &&
1490 loc1.int_data == loc2.int_data);
Douglas Gregor816fd362010-01-22 21:44:22 +00001491}
1492
1493CXSourceLocation clang_getLocation(CXTranslationUnit tu,
1494 CXFile file,
1495 unsigned line,
1496 unsigned column) {
Douglas Gregor0925fbc2010-04-30 19:45:53 +00001497 if (!tu || !file)
Douglas Gregor816fd362010-01-22 21:44:22 +00001498 return clang_getNullLocation();
Douglas Gregor0925fbc2010-04-30 19:45:53 +00001499
Douglas Gregor816fd362010-01-22 21:44:22 +00001500 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
1501 SourceLocation SLoc
1502 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf441baf2010-02-17 00:41:40 +00001503 static_cast<const FileEntry *>(file),
Douglas Gregor816fd362010-01-22 21:44:22 +00001504 line, column);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001505
Ted Kremenek54140272010-06-28 23:54:17 +00001506 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregor816fd362010-01-22 21:44:22 +00001507}
1508
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001509CXSourceRange clang_getNullRange() {
1510 CXSourceRange Result = { { 0, 0 }, 0, 0 };
1511 return Result;
1512}
Daniel Dunbar02968e52010-02-14 10:02:57 +00001513
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001514CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
1515 if (begin.ptr_data[0] != end.ptr_data[0] ||
1516 begin.ptr_data[1] != end.ptr_data[1])
1517 return clang_getNullRange();
Ted Kremenekf441baf2010-02-17 00:41:40 +00001518
1519 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001520 begin.int_data, end.int_data };
Douglas Gregor816fd362010-01-22 21:44:22 +00001521 return Result;
1522}
1523
Douglas Gregor9bd6db52010-01-26 19:19:08 +00001524void clang_getInstantiationLocation(CXSourceLocation location,
1525 CXFile *file,
1526 unsigned *line,
1527 unsigned *column,
1528 unsigned *offset) {
Douglas Gregor4f46e782010-01-19 21:36:55 +00001529 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
1530
Daniel Dunbarc4b4d392010-02-14 01:47:36 +00001531 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor9bd6db52010-01-26 19:19:08 +00001532 if (file)
1533 *file = 0;
1534 if (line)
1535 *line = 0;
1536 if (column)
1537 *column = 0;
1538 if (offset)
1539 *offset = 0;
1540 return;
1541 }
1542
Daniel Dunbarc4b4d392010-02-14 01:47:36 +00001543 const SourceManager &SM =
1544 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001545 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor4f46e782010-01-19 21:36:55 +00001546
1547 if (file)
1548 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
1549 if (line)
1550 *line = SM.getInstantiationLineNumber(InstLoc);
1551 if (column)
1552 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregor47751d62010-01-26 03:07:15 +00001553 if (offset)
Douglas Gregor9bd6db52010-01-26 19:19:08 +00001554 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregor47751d62010-01-26 03:07:15 +00001555}
1556
Douglas Gregor4f46e782010-01-19 21:36:55 +00001557CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf441baf2010-02-17 00:41:40 +00001558 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001559 range.begin_int_data };
Douglas Gregor4f46e782010-01-19 21:36:55 +00001560 return Result;
1561}
1562
1563CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarc4b4d392010-02-14 01:47:36 +00001564 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001565 range.end_int_data };
Douglas Gregor4f46e782010-01-19 21:36:55 +00001566 return Result;
1567}
1568
Douglas Gregor816fd362010-01-22 21:44:22 +00001569} // end: extern "C"
1570
Douglas Gregor4f46e782010-01-19 21:36:55 +00001571//===----------------------------------------------------------------------===//
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001572// CXFile Operations.
1573//===----------------------------------------------------------------------===//
1574
1575extern "C" {
Ted Kremenekc560b682010-02-17 00:41:20 +00001576CXString clang_getFileName(CXFile SFile) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001577 if (!SFile)
Ted Kremenekc560b682010-02-17 00:41:20 +00001578 return createCXString(NULL);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001579
Steve Naroff6231f182009-10-27 14:35:18 +00001580 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenekc560b682010-02-17 00:41:20 +00001581 return createCXString(FEnt->getName());
Steve Naroff6231f182009-10-27 14:35:18 +00001582}
1583
1584time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor66a58812010-01-18 22:46:11 +00001585 if (!SFile)
1586 return 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001587
Steve Naroff6231f182009-10-27 14:35:18 +00001588 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
1589 return FEnt->getModificationTime();
Steve Naroff26760892009-09-25 21:45:39 +00001590}
Ted Kremenekf441baf2010-02-17 00:41:40 +00001591
Douglas Gregor816fd362010-01-22 21:44:22 +00001592CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
1593 if (!tu)
1594 return 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001595
Douglas Gregor816fd362010-01-22 21:44:22 +00001596 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf441baf2010-02-17 00:41:40 +00001597
Douglas Gregor816fd362010-01-22 21:44:22 +00001598 FileManager &FMgr = CXXUnit->getFileManager();
1599 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name));
1600 return const_cast<FileEntry *>(File);
1601}
Ted Kremenekf441baf2010-02-17 00:41:40 +00001602
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001603} // end: extern "C"
Steve Naroff26760892009-09-25 21:45:39 +00001604
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001605//===----------------------------------------------------------------------===//
1606// CXCursor Operations.
1607//===----------------------------------------------------------------------===//
1608
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001609static Decl *getDeclFromExpr(Stmt *E) {
1610 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
1611 return RefExpr->getDecl();
1612 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1613 return ME->getMemberDecl();
1614 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
1615 return RE->getDecl();
Ted Kremenekf441baf2010-02-17 00:41:40 +00001616
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001617 if (CallExpr *CE = dyn_cast<CallExpr>(E))
1618 return getDeclFromExpr(CE->getCallee());
1619 if (CastExpr *CE = dyn_cast<CastExpr>(E))
1620 return getDeclFromExpr(CE->getSubExpr());
1621 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
1622 return OME->getMethodDecl();
Ted Kremenekf441baf2010-02-17 00:41:40 +00001623
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001624 return 0;
1625}
1626
Daniel Dunbara4a2e5d2010-02-02 05:00:22 +00001627static SourceLocation getLocationFromExpr(Expr *E) {
1628 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
1629 return /*FIXME:*/Msg->getLeftLoc();
1630 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1631 return DRE->getLocation();
1632 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
1633 return Member->getMemberLoc();
1634 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
1635 return Ivar->getLocation();
1636 return E->getLocStart();
1637}
1638
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00001639extern "C" {
Ted Kremenekf441baf2010-02-17 00:41:40 +00001640
1641unsigned clang_visitChildren(CXCursor parent,
Douglas Gregor71f3d942010-01-20 20:59:29 +00001642 CXCursorVisitor visitor,
1643 CXClientData client_data) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00001644 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregor71f3d942010-01-20 20:59:29 +00001645
Douglas Gregore9db88f2010-08-03 19:06:41 +00001646 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
1647 CXXUnit->getMaxPCHLevel());
Douglas Gregor71f3d942010-01-20 20:59:29 +00001648 return CursorVis.VisitChildren(parent);
1649}
1650
Douglas Gregordd969c82010-01-20 21:45:58 +00001651static CXString getDeclSpelling(Decl *D) {
1652 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
1653 if (!ND)
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001654 return createCXString("");
Ted Kremenekf441baf2010-02-17 00:41:40 +00001655
Douglas Gregordd969c82010-01-20 21:45:58 +00001656 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001657 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf441baf2010-02-17 00:41:40 +00001658
Douglas Gregordd969c82010-01-20 21:45:58 +00001659 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
1660 // No, this isn't the same as the code below. getIdentifier() is non-virtual
1661 // and returns different names. NamedDecl returns the class name and
1662 // ObjCCategoryImplDecl returns the category name.
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001663 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf441baf2010-02-17 00:41:40 +00001664
Ted Kremenek08de5c12010-05-19 21:51:10 +00001665 llvm::SmallString<1024> S;
1666 llvm::raw_svector_ostream os(S);
1667 ND->printName(os);
1668
1669 return createCXString(os.str());
Douglas Gregordd969c82010-01-20 21:45:58 +00001670}
Ted Kremenekf441baf2010-02-17 00:41:40 +00001671
Daniel Dunbar079203f2009-12-01 03:14:51 +00001672CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregord2fc7272010-01-20 00:23:15 +00001673 if (clang_isTranslationUnit(C.kind))
Douglas Gregorfed36b12010-01-20 23:57:43 +00001674 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregord2fc7272010-01-20 00:23:15 +00001675
Steve Naroff80a766b2009-09-02 18:26:48 +00001676 if (clang_isReference(C.kind)) {
1677 switch (C.kind) {
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001678 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor6c8959b2010-01-16 14:00:32 +00001679 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001680 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001681 }
1682 case CXCursor_ObjCClassRef: {
Douglas Gregor46d66142010-01-16 17:14:40 +00001683 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001684 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001685 }
1686 case CXCursor_ObjCProtocolRef: {
Douglas Gregoref6eb842010-01-16 15:44:18 +00001687 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001688 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001689 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001690 }
Douglas Gregor93f89952010-01-21 16:28:34 +00001691 case CXCursor_TypeRef: {
1692 TypeDecl *Type = getCursorTypeRef(C).first;
1693 assert(Type && "Missing type decl");
1694
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001695 return createCXString(getCursorContext(C).getTypeDeclType(Type).
1696 getAsString());
Douglas Gregor93f89952010-01-21 16:28:34 +00001697 }
1698
Daniel Dunbar5b2f5ca2009-11-30 20:42:49 +00001699 default:
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001700 return createCXString("<not implemented>");
Steve Naroff80a766b2009-09-02 18:26:48 +00001701 }
1702 }
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001703
1704 if (clang_isExpression(C.kind)) {
1705 Decl *D = getDeclFromExpr(getCursorExpr(C));
1706 if (D)
Douglas Gregordd969c82010-01-20 21:45:58 +00001707 return getDeclSpelling(D);
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001708 return createCXString("");
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001709 }
1710
Douglas Gregor065f8d12010-03-18 17:52:52 +00001711 if (C.kind == CXCursor_MacroInstantiation)
1712 return createCXString(getCursorMacroInstantiation(C)->getName()
1713 ->getNameStart());
1714
Douglas Gregor06d6d322010-03-18 18:04:21 +00001715 if (C.kind == CXCursor_MacroDefinition)
1716 return createCXString(getCursorMacroDefinition(C)->getName()
1717 ->getNameStart());
1718
Douglas Gregor5bce76c2010-01-25 16:56:17 +00001719 if (clang_isDeclaration(C.kind))
1720 return getDeclSpelling(getCursorDecl(C));
Ted Kremenek29004672010-02-17 00:41:32 +00001721
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00001722 return createCXString("");
Steve Naroff80a766b2009-09-02 18:26:48 +00001723}
1724
Ted Kremenek29004672010-02-17 00:41:32 +00001725CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff1054e602009-08-31 00:59:03 +00001726 switch (Kind) {
Ted Kremenek29004672010-02-17 00:41:32 +00001727 case CXCursor_FunctionDecl:
1728 return createCXString("FunctionDecl");
1729 case CXCursor_TypedefDecl:
1730 return createCXString("TypedefDecl");
1731 case CXCursor_EnumDecl:
1732 return createCXString("EnumDecl");
1733 case CXCursor_EnumConstantDecl:
1734 return createCXString("EnumConstantDecl");
1735 case CXCursor_StructDecl:
1736 return createCXString("StructDecl");
1737 case CXCursor_UnionDecl:
1738 return createCXString("UnionDecl");
1739 case CXCursor_ClassDecl:
1740 return createCXString("ClassDecl");
1741 case CXCursor_FieldDecl:
1742 return createCXString("FieldDecl");
1743 case CXCursor_VarDecl:
1744 return createCXString("VarDecl");
1745 case CXCursor_ParmDecl:
1746 return createCXString("ParmDecl");
1747 case CXCursor_ObjCInterfaceDecl:
1748 return createCXString("ObjCInterfaceDecl");
1749 case CXCursor_ObjCCategoryDecl:
1750 return createCXString("ObjCCategoryDecl");
1751 case CXCursor_ObjCProtocolDecl:
1752 return createCXString("ObjCProtocolDecl");
1753 case CXCursor_ObjCPropertyDecl:
1754 return createCXString("ObjCPropertyDecl");
1755 case CXCursor_ObjCIvarDecl:
1756 return createCXString("ObjCIvarDecl");
1757 case CXCursor_ObjCInstanceMethodDecl:
1758 return createCXString("ObjCInstanceMethodDecl");
1759 case CXCursor_ObjCClassMethodDecl:
1760 return createCXString("ObjCClassMethodDecl");
1761 case CXCursor_ObjCImplementationDecl:
1762 return createCXString("ObjCImplementationDecl");
1763 case CXCursor_ObjCCategoryImplDecl:
1764 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek225b8e32010-04-13 23:39:06 +00001765 case CXCursor_CXXMethod:
1766 return createCXString("CXXMethod");
Ted Kremenek29004672010-02-17 00:41:32 +00001767 case CXCursor_UnexposedDecl:
1768 return createCXString("UnexposedDecl");
1769 case CXCursor_ObjCSuperClassRef:
1770 return createCXString("ObjCSuperClassRef");
1771 case CXCursor_ObjCProtocolRef:
1772 return createCXString("ObjCProtocolRef");
1773 case CXCursor_ObjCClassRef:
1774 return createCXString("ObjCClassRef");
1775 case CXCursor_TypeRef:
1776 return createCXString("TypeRef");
1777 case CXCursor_UnexposedExpr:
1778 return createCXString("UnexposedExpr");
Ted Kremenek33b9a422010-04-11 21:47:37 +00001779 case CXCursor_BlockExpr:
1780 return createCXString("BlockExpr");
Ted Kremenek29004672010-02-17 00:41:32 +00001781 case CXCursor_DeclRefExpr:
1782 return createCXString("DeclRefExpr");
1783 case CXCursor_MemberRefExpr:
1784 return createCXString("MemberRefExpr");
1785 case CXCursor_CallExpr:
1786 return createCXString("CallExpr");
1787 case CXCursor_ObjCMessageExpr:
1788 return createCXString("ObjCMessageExpr");
1789 case CXCursor_UnexposedStmt:
1790 return createCXString("UnexposedStmt");
1791 case CXCursor_InvalidFile:
1792 return createCXString("InvalidFile");
Ted Kremenek00da3b92010-03-19 20:39:05 +00001793 case CXCursor_InvalidCode:
1794 return createCXString("InvalidCode");
Ted Kremenek29004672010-02-17 00:41:32 +00001795 case CXCursor_NoDeclFound:
1796 return createCXString("NoDeclFound");
1797 case CXCursor_NotImplemented:
1798 return createCXString("NotImplemented");
1799 case CXCursor_TranslationUnit:
1800 return createCXString("TranslationUnit");
Ted Kremenekbff31432010-02-18 03:09:07 +00001801 case CXCursor_UnexposedAttr:
1802 return createCXString("UnexposedAttr");
1803 case CXCursor_IBActionAttr:
1804 return createCXString("attribute(ibaction)");
Douglas Gregor92a524f2010-03-18 00:42:48 +00001805 case CXCursor_IBOutletAttr:
1806 return createCXString("attribute(iboutlet)");
Ted Kremenek26bde772010-05-19 17:38:06 +00001807 case CXCursor_IBOutletCollectionAttr:
1808 return createCXString("attribute(iboutletcollection)");
Douglas Gregor92a524f2010-03-18 00:42:48 +00001809 case CXCursor_PreprocessingDirective:
1810 return createCXString("preprocessing directive");
Douglas Gregor06d6d322010-03-18 18:04:21 +00001811 case CXCursor_MacroDefinition:
1812 return createCXString("macro definition");
Douglas Gregor02ded2a2010-03-18 15:23:44 +00001813 case CXCursor_MacroInstantiation:
1814 return createCXString("macro instantiation");
Ted Kremenekbd67fb22010-05-06 23:38:21 +00001815 case CXCursor_Namespace:
1816 return createCXString("Namespace");
Ted Kremenekb80cba52010-05-07 01:04:29 +00001817 case CXCursor_LinkageSpec:
1818 return createCXString("LinkageSpec");
Steve Naroff1054e602009-08-31 00:59:03 +00001819 }
Ted Kremenek29004672010-02-17 00:41:32 +00001820
Ted Kremenek4ba52632010-01-16 02:02:09 +00001821 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremenek29004672010-02-17 00:41:32 +00001822 return createCXString(NULL);
Steve Naroffd5e8e862009-08-27 19:51:58 +00001823}
Steve Naroff1054e602009-08-31 00:59:03 +00001824
Ted Kremenek29004672010-02-17 00:41:32 +00001825enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
1826 CXCursor parent,
Douglas Gregor562c1f92010-01-22 19:49:59 +00001827 CXClientData client_data) {
1828 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
1829 *BestCursor = cursor;
1830 return CXChildVisit_Recurse;
1831}
Ted Kremenek29004672010-02-17 00:41:32 +00001832
Douglas Gregor816fd362010-01-22 21:44:22 +00001833CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
1834 if (!TU)
Ted Kremeneke34cbde2010-01-14 01:51:23 +00001835 return clang_getNullCursor();
Ted Kremenek29004672010-02-17 00:41:32 +00001836
Douglas Gregor816fd362010-01-22 21:44:22 +00001837 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor0c7c2f82010-03-05 21:16:25 +00001838 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
1839
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00001840 // Translate the given source location to make it point at the beginning of
1841 // the token under the cursor.
Ted Kremenek97a45372010-01-25 22:34:44 +00001842 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremenek1e589f22010-07-29 00:52:07 +00001843
1844 // Guard against an invalid SourceLocation, or we may assert in one
1845 // of the following calls.
1846 if (SLoc.isInvalid())
1847 return clang_getNullCursor();
1848
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00001849 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
1850 CXXUnit->getASTContext().getLangOptions());
1851
Douglas Gregor562c1f92010-01-22 19:49:59 +00001852 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
1853 if (SLoc.isValid()) {
Douglas Gregor562c1f92010-01-22 19:49:59 +00001854 // FIXME: Would be great to have a "hint" cursor, then walk from that
1855 // hint cursor upward until we find a cursor whose source range encloses
1856 // the region of interest, rather than starting from the translation unit.
1857 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremenek29004672010-02-17 00:41:32 +00001858 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00001859 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor562c1f92010-01-22 19:49:59 +00001860 CursorVis.VisitChildren(Parent);
Steve Naroff54f22fb2009-09-15 20:25:34 +00001861 }
Ted Kremenek29004672010-02-17 00:41:32 +00001862 return Result;
Steve Naroffd5e8e862009-08-27 19:51:58 +00001863}
1864
Ted Kremeneke05d7802009-11-17 19:28:59 +00001865CXCursor clang_getNullCursor(void) {
Douglas Gregor58552bc2010-01-20 23:34:41 +00001866 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremeneke05d7802009-11-17 19:28:59 +00001867}
1868
1869unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregorc58d05b2010-01-15 21:56:13 +00001870 return X == Y;
Ted Kremeneke05d7802009-11-17 19:28:59 +00001871}
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00001872
Daniel Dunbar079203f2009-12-01 03:14:51 +00001873unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff54f22fb2009-09-15 20:25:34 +00001874 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
1875}
1876
Daniel Dunbar079203f2009-12-01 03:14:51 +00001877unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff1054e602009-08-31 00:59:03 +00001878 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
1879}
Steve Naroff772c1a42009-08-31 14:26:51 +00001880
Daniel Dunbar079203f2009-12-01 03:14:51 +00001881unsigned clang_isReference(enum CXCursorKind K) {
Steve Naroff80a766b2009-09-02 18:26:48 +00001882 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
1883}
1884
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001885unsigned clang_isExpression(enum CXCursorKind K) {
1886 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
1887}
1888
1889unsigned clang_isStatement(enum CXCursorKind K) {
1890 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
1891}
1892
Douglas Gregord2fc7272010-01-20 00:23:15 +00001893unsigned clang_isTranslationUnit(enum CXCursorKind K) {
1894 return K == CXCursor_TranslationUnit;
1895}
1896
Douglas Gregor92a524f2010-03-18 00:42:48 +00001897unsigned clang_isPreprocessing(enum CXCursorKind K) {
1898 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
1899}
1900
Ted Kremenekff9021b2010-03-08 21:17:29 +00001901unsigned clang_isUnexposed(enum CXCursorKind K) {
1902 switch (K) {
1903 case CXCursor_UnexposedDecl:
1904 case CXCursor_UnexposedExpr:
1905 case CXCursor_UnexposedStmt:
1906 case CXCursor_UnexposedAttr:
1907 return true;
1908 default:
1909 return false;
1910 }
1911}
1912
Daniel Dunbar079203f2009-12-01 03:14:51 +00001913CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroffef9618b2009-09-04 15:44:05 +00001914 return C.kind;
1915}
1916
Douglas Gregor66a58812010-01-18 22:46:11 +00001917CXSourceLocation clang_getCursorLocation(CXCursor C) {
1918 if (clang_isReference(C.kind)) {
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001919 switch (C.kind) {
Ted Kremenekf441baf2010-02-17 00:41:40 +00001920 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001921 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1922 = getCursorObjCSuperClassRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001923 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001924 }
1925
Ted Kremenekf441baf2010-02-17 00:41:40 +00001926 case CXCursor_ObjCProtocolRef: {
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001927 std::pair<ObjCProtocolDecl *, SourceLocation> P
1928 = getCursorObjCProtocolRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001929 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001930 }
1931
Ted Kremenekf441baf2010-02-17 00:41:40 +00001932 case CXCursor_ObjCClassRef: {
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001933 std::pair<ObjCInterfaceDecl *, SourceLocation> P
1934 = getCursorObjCClassRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001935 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001936 }
Douglas Gregor93f89952010-01-21 16:28:34 +00001937
Ted Kremenekf441baf2010-02-17 00:41:40 +00001938 case CXCursor_TypeRef: {
Douglas Gregor93f89952010-01-21 16:28:34 +00001939 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremenek97a45372010-01-25 22:34:44 +00001940 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor93f89952010-01-21 16:28:34 +00001941 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00001942
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001943 default:
1944 // FIXME: Need a way to enumerate all non-reference cases.
1945 llvm_unreachable("Missed a reference kind");
1946 }
Douglas Gregor66a58812010-01-18 22:46:11 +00001947 }
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001948
1949 if (clang_isExpression(C.kind))
Ted Kremenekf441baf2010-02-17 00:41:40 +00001950 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00001951 getLocationFromExpr(getCursorExpr(C)));
1952
Douglas Gregor92a524f2010-03-18 00:42:48 +00001953 if (C.kind == CXCursor_PreprocessingDirective) {
1954 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
1955 return cxloc::translateSourceLocation(getCursorContext(C), L);
1956 }
Douglas Gregor02ded2a2010-03-18 15:23:44 +00001957
1958 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor065f8d12010-03-18 17:52:52 +00001959 SourceLocation L
1960 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor02ded2a2010-03-18 15:23:44 +00001961 return cxloc::translateSourceLocation(getCursorContext(C), L);
1962 }
Douglas Gregor06d6d322010-03-18 18:04:21 +00001963
1964 if (C.kind == CXCursor_MacroDefinition) {
1965 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
1966 return cxloc::translateSourceLocation(getCursorContext(C), L);
1967 }
Douglas Gregor92a524f2010-03-18 00:42:48 +00001968
Ted Kremenek8278a322010-05-12 06:16:13 +00001969 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor4f9c3762010-01-28 00:27:43 +00001970 return clang_getNullLocation();
Douglas Gregor66a58812010-01-18 22:46:11 +00001971
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001972 Decl *D = getCursorDecl(C);
Douglas Gregor7ecd0202010-01-18 23:41:10 +00001973 SourceLocation Loc = D->getLocation();
1974 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
1975 Loc = Class->getClassLoc();
Douglas Gregor7bf6b8a2010-03-22 15:53:50 +00001976 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor66a58812010-01-18 22:46:11 +00001977}
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001978
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00001979} // end extern "C"
1980
1981static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001982 if (clang_isReference(C.kind)) {
1983 switch (C.kind) {
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00001984 case CXCursor_ObjCSuperClassRef:
1985 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001986
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00001987 case CXCursor_ObjCProtocolRef:
1988 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001989
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00001990 case CXCursor_ObjCClassRef:
1991 return getCursorObjCClassRef(C).second;
Ted Kremenekf441baf2010-02-17 00:41:40 +00001992
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00001993 case CXCursor_TypeRef:
1994 return getCursorTypeRef(C).second;
Douglas Gregor93f89952010-01-21 16:28:34 +00001995
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00001996 default:
1997 // FIXME: Need a way to enumerate all non-reference cases.
1998 llvm_unreachable("Missed a reference kind");
Douglas Gregor33c34ac2010-01-19 00:34:46 +00001999 }
2000 }
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00002001
2002 if (clang_isExpression(C.kind))
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002003 return getCursorExpr(C)->getSourceRange();
Douglas Gregor562c1f92010-01-22 19:49:59 +00002004
2005 if (clang_isStatement(C.kind))
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002006 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002007
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002008 if (C.kind == CXCursor_PreprocessingDirective)
2009 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor02ded2a2010-03-18 15:23:44 +00002010
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002011 if (C.kind == CXCursor_MacroInstantiation)
2012 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor06d6d322010-03-18 18:04:21 +00002013
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002014 if (C.kind == CXCursor_MacroDefinition)
2015 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregor92a524f2010-03-18 00:42:48 +00002016
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002017 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl)
2018 return getCursorDecl(C)->getSourceRange();
2019
2020 return SourceRange();
2021}
2022
2023extern "C" {
2024
2025CXSourceRange clang_getCursorExtent(CXCursor C) {
2026 SourceRange R = getRawCursorExtent(C);
2027 if (R.isInvalid())
Douglas Gregor4f9c3762010-01-28 00:27:43 +00002028 return clang_getNullRange();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002029
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002030 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregor33c34ac2010-01-19 00:34:46 +00002031}
Douglas Gregorad27e8b2010-01-19 01:20:04 +00002032
2033CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00002034 if (clang_isInvalid(C.kind))
2035 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002036
Douglas Gregorfed36b12010-01-20 23:57:43 +00002037 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002038 if (clang_isDeclaration(C.kind))
Douglas Gregorad27e8b2010-01-19 01:20:04 +00002039 return C;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002040
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00002041 if (clang_isExpression(C.kind)) {
2042 Decl *D = getDeclFromExpr(getCursorExpr(C));
2043 if (D)
Douglas Gregorfed36b12010-01-20 23:57:43 +00002044 return MakeCXCursor(D, CXXUnit);
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00002045 return clang_getNullCursor();
2046 }
2047
Douglas Gregor78ae2482010-03-18 18:23:03 +00002048 if (C.kind == CXCursor_MacroInstantiation) {
2049 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
2050 return MakeMacroDefinitionCursor(Def, CXXUnit);
2051 }
2052
Douglas Gregorad27e8b2010-01-19 01:20:04 +00002053 if (!clang_isReference(C.kind))
2054 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002055
Douglas Gregorad27e8b2010-01-19 01:20:04 +00002056 switch (C.kind) {
2057 case CXCursor_ObjCSuperClassRef:
Douglas Gregorfed36b12010-01-20 23:57:43 +00002058 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002059
2060 case CXCursor_ObjCProtocolRef: {
Douglas Gregorfed36b12010-01-20 23:57:43 +00002061 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002062
2063 case CXCursor_ObjCClassRef:
Douglas Gregorfed36b12010-01-20 23:57:43 +00002064 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor93f89952010-01-21 16:28:34 +00002065
Ted Kremenekf441baf2010-02-17 00:41:40 +00002066 case CXCursor_TypeRef:
Douglas Gregor93f89952010-01-21 16:28:34 +00002067 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002068
Douglas Gregorad27e8b2010-01-19 01:20:04 +00002069 default:
2070 // We would prefer to enumerate all non-reference cursor kinds here.
2071 llvm_unreachable("Unhandled reference cursor kind");
2072 break;
2073 }
2074 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00002075
Douglas Gregorad27e8b2010-01-19 01:20:04 +00002076 return clang_getNullCursor();
2077}
2078
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002079CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorfed36b12010-01-20 23:57:43 +00002080 if (clang_isInvalid(C.kind))
2081 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002082
Douglas Gregorfed36b12010-01-20 23:57:43 +00002083 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002084
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002085 bool WasReference = false;
Douglas Gregor8f40bbee2010-01-19 23:20:36 +00002086 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002087 C = clang_getCursorReferenced(C);
2088 WasReference = true;
2089 }
2090
Douglas Gregor78ae2482010-03-18 18:23:03 +00002091 if (C.kind == CXCursor_MacroInstantiation)
2092 return clang_getCursorReferenced(C);
2093
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002094 if (!clang_isDeclaration(C.kind))
2095 return clang_getNullCursor();
2096
2097 Decl *D = getCursorDecl(C);
2098 if (!D)
2099 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002100
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002101 switch (D->getKind()) {
2102 // Declaration kinds that don't really separate the notions of
2103 // declaration and definition.
2104 case Decl::Namespace:
2105 case Decl::Typedef:
2106 case Decl::TemplateTypeParm:
2107 case Decl::EnumConstant:
2108 case Decl::Field:
2109 case Decl::ObjCIvar:
2110 case Decl::ObjCAtDefsField:
2111 case Decl::ImplicitParam:
2112 case Decl::ParmVar:
2113 case Decl::NonTypeTemplateParm:
2114 case Decl::TemplateTemplateParm:
2115 case Decl::ObjCCategoryImpl:
2116 case Decl::ObjCImplementation:
Abramo Bagnarad7340582010-06-05 05:09:32 +00002117 case Decl::AccessSpec:
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002118 case Decl::LinkageSpec:
2119 case Decl::ObjCPropertyImpl:
2120 case Decl::FileScopeAsm:
2121 case Decl::StaticAssert:
2122 case Decl::Block:
2123 return C;
2124
2125 // Declaration kinds that don't make any sense here, but are
2126 // nonetheless harmless.
2127 case Decl::TranslationUnit:
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002128 break;
2129
2130 // Declaration kinds for which the definition is not resolvable.
2131 case Decl::UnresolvedUsingTypename:
2132 case Decl::UnresolvedUsingValue:
2133 break;
2134
2135 case Decl::UsingDirective:
Douglas Gregorfed36b12010-01-20 23:57:43 +00002136 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
2137 CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002138
2139 case Decl::NamespaceAlias:
Douglas Gregorfed36b12010-01-20 23:57:43 +00002140 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002141
2142 case Decl::Enum:
2143 case Decl::Record:
2144 case Decl::CXXRecord:
2145 case Decl::ClassTemplateSpecialization:
2146 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002147 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002148 return MakeCXCursor(Def, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002149 return clang_getNullCursor();
2150
2151 case Decl::Function:
2152 case Decl::CXXMethod:
2153 case Decl::CXXConstructor:
2154 case Decl::CXXDestructor:
2155 case Decl::CXXConversion: {
2156 const FunctionDecl *Def = 0;
2157 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorfed36b12010-01-20 23:57:43 +00002158 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002159 return clang_getNullCursor();
2160 }
2161
2162 case Decl::Var: {
Sebastian Redl5ca79842010-02-01 20:16:42 +00002163 // Ask the variable if it has a definition.
2164 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
2165 return MakeCXCursor(Def, CXXUnit);
2166 return clang_getNullCursor();
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002167 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00002168
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002169 case Decl::FunctionTemplate: {
2170 const FunctionDecl *Def = 0;
2171 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorfed36b12010-01-20 23:57:43 +00002172 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002173 return clang_getNullCursor();
2174 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00002175
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002176 case Decl::ClassTemplate: {
2177 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor0a5a2212010-02-11 01:04:33 +00002178 ->getDefinition())
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002179 return MakeCXCursor(
Ted Kremenekf441baf2010-02-17 00:41:40 +00002180 cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorfed36b12010-01-20 23:57:43 +00002181 CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002182 return clang_getNullCursor();
2183 }
2184
2185 case Decl::Using: {
2186 UsingDecl *Using = cast<UsingDecl>(D);
2187 CXCursor Def = clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002188 for (UsingDecl::shadow_iterator S = Using->shadow_begin(),
2189 SEnd = Using->shadow_end();
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002190 S != SEnd; ++S) {
2191 if (Def != clang_getNullCursor()) {
2192 // FIXME: We have no way to return multiple results.
2193 return clang_getNullCursor();
2194 }
2195
Ted Kremenekf441baf2010-02-17 00:41:40 +00002196 Def = clang_getCursorDefinition(MakeCXCursor((*S)->getTargetDecl(),
Douglas Gregorfed36b12010-01-20 23:57:43 +00002197 CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002198 }
2199
2200 return Def;
2201 }
2202
2203 case Decl::UsingShadow:
2204 return clang_getCursorDefinition(
Ted Kremenekf441baf2010-02-17 00:41:40 +00002205 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorfed36b12010-01-20 23:57:43 +00002206 CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002207
2208 case Decl::ObjCMethod: {
2209 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
2210 if (Method->isThisDeclarationADefinition())
2211 return C;
2212
2213 // Dig out the method definition in the associated
2214 // @implementation, if we have it.
2215 // FIXME: The ASTs should make finding the definition easier.
2216 if (ObjCInterfaceDecl *Class
2217 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
2218 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
2219 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
2220 Method->isInstanceMethod()))
2221 if (Def->isThisDeclarationADefinition())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002222 return MakeCXCursor(Def, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002223
2224 return clang_getNullCursor();
2225 }
2226
2227 case Decl::ObjCCategory:
2228 if (ObjCCategoryImplDecl *Impl
2229 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002230 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002231 return clang_getNullCursor();
2232
2233 case Decl::ObjCProtocol:
2234 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
2235 return C;
2236 return clang_getNullCursor();
2237
2238 case Decl::ObjCInterface:
2239 // There are two notions of a "definition" for an Objective-C
2240 // class: the interface and its implementation. When we resolved a
2241 // reference to an Objective-C class, produce the @interface as
2242 // the definition; when we were provided with the interface,
2243 // produce the @implementation as the definition.
2244 if (WasReference) {
2245 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
2246 return C;
2247 } else if (ObjCImplementationDecl *Impl
2248 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002249 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002250 return clang_getNullCursor();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002251
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002252 case Decl::ObjCProperty:
2253 // FIXME: We don't really know where to find the
2254 // ObjCPropertyImplDecls that implement this property.
2255 return clang_getNullCursor();
2256
2257 case Decl::ObjCCompatibleAlias:
2258 if (ObjCInterfaceDecl *Class
2259 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
2260 if (!Class->isForwardDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002261 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002262
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002263 return clang_getNullCursor();
2264
2265 case Decl::ObjCForwardProtocol: {
2266 ObjCForwardProtocolDecl *Forward = cast<ObjCForwardProtocolDecl>(D);
2267 if (Forward->protocol_size() == 1)
2268 return clang_getCursorDefinition(
Ted Kremenekf441baf2010-02-17 00:41:40 +00002269 MakeCXCursor(*Forward->protocol_begin(),
Douglas Gregorfed36b12010-01-20 23:57:43 +00002270 CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002271
2272 // FIXME: Cannot return multiple definitions.
2273 return clang_getNullCursor();
2274 }
2275
2276 case Decl::ObjCClass: {
2277 ObjCClassDecl *Class = cast<ObjCClassDecl>(D);
2278 if (Class->size() == 1) {
2279 ObjCInterfaceDecl *IFace = Class->begin()->getInterface();
2280 if (!IFace->isForwardDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002281 return MakeCXCursor(IFace, CXXUnit);
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002282 return clang_getNullCursor();
2283 }
2284
2285 // FIXME: Cannot return multiple definitions.
2286 return clang_getNullCursor();
2287 }
2288
2289 case Decl::Friend:
2290 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002291 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002292 return clang_getNullCursor();
2293
2294 case Decl::FriendTemplate:
2295 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorfed36b12010-01-20 23:57:43 +00002296 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregor6b8232f2010-01-19 19:34:47 +00002297 return clang_getNullCursor();
2298 }
2299
2300 return clang_getNullCursor();
2301}
2302
2303unsigned clang_isCursorDefinition(CXCursor C) {
2304 if (!clang_isDeclaration(C.kind))
2305 return 0;
2306
2307 return clang_getCursorDefinition(C) == C;
2308}
2309
Daniel Dunbarbbc569c2009-11-30 20:42:43 +00002310void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff76b8f132009-09-23 17:52:52 +00002311 const char **startBuf,
2312 const char **endBuf,
2313 unsigned *startLine,
2314 unsigned *startColumn,
2315 unsigned *endLine,
Daniel Dunbar079203f2009-12-01 03:14:51 +00002316 unsigned *endColumn) {
Douglas Gregorc58d05b2010-01-15 21:56:13 +00002317 assert(getCursorDecl(C) && "CXCursor has null decl");
2318 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff76b8f132009-09-23 17:52:52 +00002319 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
2320 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf441baf2010-02-17 00:41:40 +00002321
Steve Naroff76b8f132009-09-23 17:52:52 +00002322 SourceManager &SM = FD->getASTContext().getSourceManager();
2323 *startBuf = SM.getCharacterData(Body->getLBracLoc());
2324 *endBuf = SM.getCharacterData(Body->getRBracLoc());
2325 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
2326 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
2327 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
2328 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
2329}
Ted Kremenekf441baf2010-02-17 00:41:40 +00002330
Douglas Gregor1e21cc72010-02-18 23:07:20 +00002331void clang_enableStackTraces(void) {
2332 llvm::sys::PrintStackTraceOnErrorSignal();
2333}
2334
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002335} // end: extern "C"
Steve Naroff76b8f132009-09-23 17:52:52 +00002336
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002337//===----------------------------------------------------------------------===//
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002338// Token-based Operations.
2339//===----------------------------------------------------------------------===//
2340
2341/* CXToken layout:
2342 * int_data[0]: a CXTokenKind
2343 * int_data[1]: starting token location
2344 * int_data[2]: token length
2345 * int_data[3]: reserved
Ted Kremenekf441baf2010-02-17 00:41:40 +00002346 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002347 * otherwise unused.
2348 */
2349extern "C" {
2350
2351CXTokenKind clang_getTokenKind(CXToken CXTok) {
2352 return static_cast<CXTokenKind>(CXTok.int_data[0]);
2353}
2354
2355CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
2356 switch (clang_getTokenKind(CXTok)) {
2357 case CXToken_Identifier:
2358 case CXToken_Keyword:
2359 // We know we have an IdentifierInfo*, so use that.
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002360 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
2361 ->getNameStart());
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002362
2363 case CXToken_Literal: {
2364 // We have stashed the starting pointer in the ptr_data field. Use it.
2365 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002366 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002367 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00002368
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002369 case CXToken_Punctuation:
2370 case CXToken_Comment:
2371 break;
2372 }
Ted Kremenekf441baf2010-02-17 00:41:40 +00002373
2374 // We have to find the starting buffer pointer the hard way, by
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002375 // deconstructing the source location.
2376 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2377 if (!CXXUnit)
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002378 return createCXString("");
Ted Kremenekf441baf2010-02-17 00:41:40 +00002379
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002380 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
2381 std::pair<FileID, unsigned> LocInfo
2382 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregore0fbb832010-03-16 00:06:06 +00002383 bool Invalid = false;
Benjamin Kramereb92dc02010-03-16 14:14:31 +00002384 llvm::StringRef Buffer
Douglas Gregore0fbb832010-03-16 00:06:06 +00002385 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2386 if (Invalid)
Douglas Gregor802b7762010-03-15 22:54:52 +00002387 return createCXString("");
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002388
Benjamin Kramereb92dc02010-03-16 14:14:31 +00002389 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002390}
Ted Kremenekf441baf2010-02-17 00:41:40 +00002391
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002392CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
2393 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2394 if (!CXXUnit)
2395 return clang_getNullLocation();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002396
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002397 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
2398 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2399}
2400
2401CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
2402 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4f9c3762010-01-28 00:27:43 +00002403 if (!CXXUnit)
2404 return clang_getNullRange();
Ted Kremenekf441baf2010-02-17 00:41:40 +00002405
2406 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002407 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
2408}
Ted Kremenekf441baf2010-02-17 00:41:40 +00002409
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002410void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
2411 CXToken **Tokens, unsigned *NumTokens) {
2412 if (Tokens)
2413 *Tokens = 0;
2414 if (NumTokens)
2415 *NumTokens = 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002416
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002417 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2418 if (!CXXUnit || !Tokens || !NumTokens)
2419 return;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002420
Douglas Gregor0c7c2f82010-03-05 21:16:25 +00002421 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2422
Daniel Dunbar80daf532010-02-14 08:31:57 +00002423 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002424 if (R.isInvalid())
2425 return;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002426
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002427 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2428 std::pair<FileID, unsigned> BeginLocInfo
2429 = SourceMgr.getDecomposedLoc(R.getBegin());
2430 std::pair<FileID, unsigned> EndLocInfo
2431 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf441baf2010-02-17 00:41:40 +00002432
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002433 // Cannot tokenize across files.
2434 if (BeginLocInfo.first != EndLocInfo.first)
2435 return;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002436
2437 // Create a lexer
Douglas Gregore0fbb832010-03-16 00:06:06 +00002438 bool Invalid = false;
Benjamin Kramereb92dc02010-03-16 14:14:31 +00002439 llvm::StringRef Buffer
Douglas Gregore0fbb832010-03-16 00:06:06 +00002440 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor554e0b12010-03-16 20:26:15 +00002441 if (Invalid)
2442 return;
Douglas Gregor802b7762010-03-15 22:54:52 +00002443
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002444 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2445 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramereb92dc02010-03-16 14:14:31 +00002446 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002447 Lex.SetCommentRetentionState(true);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002448
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002449 // Lex tokens until we hit the end of the range.
Benjamin Kramereb92dc02010-03-16 14:14:31 +00002450 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002451 llvm::SmallVector<CXToken, 32> CXTokens;
2452 Token Tok;
2453 do {
2454 // Lex the next token
2455 Lex.LexFromRawLexer(Tok);
2456 if (Tok.is(tok::eof))
2457 break;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002458
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002459 // Initialize the CXToken.
2460 CXToken CXTok;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002461
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002462 // - Common fields
2463 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
2464 CXTok.int_data[2] = Tok.getLength();
2465 CXTok.int_data[3] = 0;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002466
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002467 // - Kind-specific fields
2468 if (Tok.isLiteral()) {
2469 CXTok.int_data[0] = CXToken_Literal;
2470 CXTok.ptr_data = (void *)Tok.getLiteralData();
2471 } else if (Tok.is(tok::identifier)) {
Douglas Gregor802b7762010-03-15 22:54:52 +00002472 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002473 std::pair<FileID, unsigned> LocInfo
2474 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregore0fbb832010-03-16 00:06:06 +00002475 bool Invalid = false;
Benjamin Kramereb92dc02010-03-16 14:14:31 +00002476 llvm::StringRef Buf
Douglas Gregore0fbb832010-03-16 00:06:06 +00002477 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
2478 if (Invalid)
Douglas Gregor802b7762010-03-15 22:54:52 +00002479 return;
2480
Benjamin Kramereb92dc02010-03-16 14:14:31 +00002481 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002482 IdentifierInfo *II
2483 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenek15cbc3a2010-05-05 00:55:20 +00002484
2485 if (II->getObjCKeywordID() != tok::objc_not_keyword) {
2486 CXTok.int_data[0] = CXToken_Keyword;
2487 }
2488 else {
2489 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
2490 CXToken_Identifier
2491 : CXToken_Keyword;
2492 }
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002493 CXTok.ptr_data = II;
2494 } else if (Tok.is(tok::comment)) {
2495 CXTok.int_data[0] = CXToken_Comment;
2496 CXTok.ptr_data = 0;
2497 } else {
2498 CXTok.int_data[0] = CXToken_Punctuation;
2499 CXTok.ptr_data = 0;
2500 }
2501 CXTokens.push_back(CXTok);
2502 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf441baf2010-02-17 00:41:40 +00002503
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002504 if (CXTokens.empty())
2505 return;
Ted Kremenekf441baf2010-02-17 00:41:40 +00002506
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002507 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
2508 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
2509 *NumTokens = CXTokens.size();
2510}
Douglas Gregor61656112010-01-26 18:31:56 +00002511
Ted Kremenek63ac5992010-05-05 00:55:15 +00002512void clang_disposeTokens(CXTranslationUnit TU,
2513 CXToken *Tokens, unsigned NumTokens) {
2514 free(Tokens);
2515}
2516
2517} // end: extern "C"
2518
2519//===----------------------------------------------------------------------===//
2520// Token annotation APIs.
2521//===----------------------------------------------------------------------===//
2522
Douglas Gregor61656112010-01-26 18:31:56 +00002523typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenek680fe512010-05-05 00:55:23 +00002524static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2525 CXCursor parent,
2526 CXClientData client_data);
Ted Kremenek63ac5992010-05-05 00:55:15 +00002527namespace {
2528class AnnotateTokensWorker {
2529 AnnotateTokensData &Annotated;
Ted Kremenek458c2f12010-05-05 00:55:17 +00002530 CXToken *Tokens;
2531 CXCursor *Cursors;
2532 unsigned NumTokens;
Ted Kremenek680fe512010-05-05 00:55:23 +00002533 unsigned TokIdx;
2534 CursorVisitor AnnotateVis;
2535 SourceManager &SrcMgr;
2536
2537 bool MoreTokens() const { return TokIdx < NumTokens; }
2538 unsigned NextToken() const { return TokIdx; }
2539 void AdvanceToken() { ++TokIdx; }
2540 SourceLocation GetTokenLoc(unsigned tokI) {
2541 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
2542 }
2543
Ted Kremenek63ac5992010-05-05 00:55:15 +00002544public:
Ted Kremenek458c2f12010-05-05 00:55:17 +00002545 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenek680fe512010-05-05 00:55:23 +00002546 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
2547 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek458c2f12010-05-05 00:55:17 +00002548 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Ted Kremenek680fe512010-05-05 00:55:23 +00002549 NumTokens(numTokens), TokIdx(0),
2550 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
2551 Decl::MaxPCHLevel, RegionOfInterest),
2552 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek458c2f12010-05-05 00:55:17 +00002553
Ted Kremenek680fe512010-05-05 00:55:23 +00002554 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek63ac5992010-05-05 00:55:15 +00002555 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenek680fe512010-05-05 00:55:23 +00002556 void AnnotateTokens(CXCursor parent);
Ted Kremenek63ac5992010-05-05 00:55:15 +00002557};
2558}
Douglas Gregor61656112010-01-26 18:31:56 +00002559
Ted Kremenek680fe512010-05-05 00:55:23 +00002560void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
2561 // Walk the AST within the region of interest, annotating tokens
2562 // along the way.
2563 VisitChildren(parent);
Ted Kremenek458c2f12010-05-05 00:55:17 +00002564
Ted Kremenek680fe512010-05-05 00:55:23 +00002565 for (unsigned I = 0 ; I < TokIdx ; ++I) {
2566 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2567 if (Pos != Annotated.end())
2568 Cursors[I] = Pos->second;
2569 }
2570
2571 // Finish up annotating any tokens left.
2572 if (!MoreTokens())
2573 return;
2574
2575 const CXCursor &C = clang_getNullCursor();
2576 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
2577 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
2578 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek458c2f12010-05-05 00:55:17 +00002579 }
2580}
2581
Ted Kremenek63ac5992010-05-05 00:55:15 +00002582enum CXChildVisitResult
2583AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenek680fe512010-05-05 00:55:23 +00002584 CXSourceLocation Loc = clang_getCursorLocation(cursor);
2585 // We can always annotate a preprocessing directive/macro instantiation.
2586 if (clang_isPreprocessing(cursor.kind)) {
2587 Annotated[Loc.int_data] = cursor;
Douglas Gregor61656112010-01-26 18:31:56 +00002588 return CXChildVisit_Recurse;
2589 }
Ted Kremenek680fe512010-05-05 00:55:23 +00002590
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002591 SourceRange cursorRange = getRawCursorExtent(cursor);
Ted Kremenek5d616142010-05-12 05:29:33 +00002592
Ted Kremenek680fe512010-05-05 00:55:23 +00002593 if (cursorRange.isInvalid())
2594 return CXChildVisit_Continue;
Ted Kremenek5d616142010-05-12 05:29:33 +00002595
Ted Kremenek680fe512010-05-05 00:55:23 +00002596 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
2597
Ted Kremenek5d616142010-05-12 05:29:33 +00002598 // Adjust the annotated range based specific declarations.
2599 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
2600 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek49be9e02010-05-18 21:09:07 +00002601 Decl *D = cxcursor::getCursorDecl(cursor);
2602 // Don't visit synthesized ObjC methods, since they have no syntatic
2603 // representation in the source.
2604 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
2605 if (MD->isSynthesized())
2606 return CXChildVisit_Continue;
2607 }
2608 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremenek5d616142010-05-12 05:29:33 +00002609 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
2610 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00002611 SourceLocation TLoc = TL.getSourceRange().getBegin();
Ted Kremenekd3214132010-05-13 15:38:38 +00002612 if (TLoc.isValid() &&
2613 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremenek5d616142010-05-12 05:29:33 +00002614 cursorRange.setBegin(TLoc);
Ted Kremenek5d616142010-05-12 05:29:33 +00002615 }
2616 }
2617 }
2618
Ted Kremenek680fe512010-05-05 00:55:23 +00002619 const enum CXCursorKind K = clang_getCursorKind(parent);
2620 const CXCursor updateC =
2621 (clang_isInvalid(K) || K == CXCursor_TranslationUnit ||
2622 L.isMacroID())
2623 ? clang_getNullCursor() : parent;
2624
2625 while (MoreTokens()) {
2626 const unsigned I = NextToken();
2627 SourceLocation TokLoc = GetTokenLoc(I);
2628 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2629 case RangeBefore:
2630 Cursors[I] = updateC;
2631 AdvanceToken();
2632 continue;
2633 case RangeAfter:
2634 return CXChildVisit_Continue;
2635 case RangeOverlap:
2636 break;
2637 }
2638 break;
2639 }
2640
2641 // Visit children to get their cursor information.
2642 const unsigned BeforeChildren = NextToken();
2643 VisitChildren(cursor);
2644 const unsigned AfterChildren = NextToken();
2645
2646 // Adjust 'Last' to the last token within the extent of the cursor.
2647 while (MoreTokens()) {
2648 const unsigned I = NextToken();
2649 SourceLocation TokLoc = GetTokenLoc(I);
2650 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
2651 case RangeBefore:
2652 assert(0 && "Infeasible");
2653 case RangeAfter:
2654 break;
2655 case RangeOverlap:
2656 Cursors[I] = updateC;
2657 AdvanceToken();
2658 continue;
2659 }
2660 break;
2661 }
2662 const unsigned Last = NextToken();
Ted Kremenek63ac5992010-05-05 00:55:15 +00002663
Ted Kremenek680fe512010-05-05 00:55:23 +00002664 // Scan the tokens that are at the beginning of the cursor, but are not
2665 // capture by the child cursors.
2666
2667 // For AST elements within macros, rely on a post-annotate pass to
2668 // to correctly annotate the tokens with cursors. Otherwise we can
2669 // get confusing results of having tokens that map to cursors that really
2670 // are expanded by an instantiation.
2671 if (L.isMacroID())
2672 cursor = clang_getNullCursor();
2673
2674 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
2675 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
2676 break;
2677 Cursors[I] = cursor;
2678 }
2679 // Scan the tokens that are at the end of the cursor, but are not captured
2680 // but the child cursors.
2681 for (unsigned I = AfterChildren; I != Last; ++I)
2682 Cursors[I] = cursor;
2683
2684 TokIdx = Last;
2685 return CXChildVisit_Continue;
Douglas Gregor61656112010-01-26 18:31:56 +00002686}
2687
Ted Kremenek63ac5992010-05-05 00:55:15 +00002688static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
2689 CXCursor parent,
2690 CXClientData client_data) {
2691 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
2692}
2693
2694extern "C" {
2695
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002696void clang_annotateTokens(CXTranslationUnit TU,
2697 CXToken *Tokens, unsigned NumTokens,
2698 CXCursor *Cursors) {
Ted Kremenek680fe512010-05-05 00:55:23 +00002699
2700 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor61656112010-01-26 18:31:56 +00002701 return;
Ted Kremenek680fe512010-05-05 00:55:23 +00002702
Douglas Gregor61656112010-01-26 18:31:56 +00002703 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Ted Kremenek680fe512010-05-05 00:55:23 +00002704 if (!CXXUnit) {
2705 // Any token we don't specifically annotate will have a NULL cursor.
2706 const CXCursor &C = clang_getNullCursor();
2707 for (unsigned I = 0; I != NumTokens; ++I)
2708 Cursors[I] = C;
Douglas Gregor61656112010-01-26 18:31:56 +00002709 return;
Ted Kremenek680fe512010-05-05 00:55:23 +00002710 }
2711
Douglas Gregor0c7c2f82010-03-05 21:16:25 +00002712 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenek680fe512010-05-05 00:55:23 +00002713
Douglas Gregor5272e802010-03-19 05:22:59 +00002714 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor61656112010-01-26 18:31:56 +00002715 SourceRange RegionOfInterest;
Ted Kremenek680fe512010-05-05 00:55:23 +00002716 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
2717 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregorcd8bdd02010-07-22 20:22:31 +00002718 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
2719 clang_getTokenLocation(TU,
2720 Tokens[NumTokens - 1])));
Ted Kremenek680fe512010-05-05 00:55:23 +00002721
Douglas Gregor5272e802010-03-19 05:22:59 +00002722 // A mapping from the source locations found when re-lexing or traversing the
2723 // region of interest to the corresponding cursors.
2724 AnnotateTokensData Annotated;
Ted Kremenek680fe512010-05-05 00:55:23 +00002725
2726 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor5272e802010-03-19 05:22:59 +00002727 // directives.
Douglas Gregor92a524f2010-03-18 00:42:48 +00002728 SourceManager &SourceMgr = CXXUnit->getSourceManager();
2729 std::pair<FileID, unsigned> BeginLocInfo
2730 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
2731 std::pair<FileID, unsigned> EndLocInfo
2732 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenek680fe512010-05-05 00:55:23 +00002733
Douglas Gregor92a524f2010-03-18 00:42:48 +00002734 llvm::StringRef Buffer;
Douglas Gregor5272e802010-03-19 05:22:59 +00002735 bool Invalid = false;
2736 if (BeginLocInfo.first == EndLocInfo.first &&
2737 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
2738 !Invalid) {
Douglas Gregor92a524f2010-03-18 00:42:48 +00002739 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
2740 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenek680fe512010-05-05 00:55:23 +00002741 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor065f8d12010-03-18 17:52:52 +00002742 Buffer.end());
Douglas Gregor92a524f2010-03-18 00:42:48 +00002743 Lex.SetCommentRetentionState(true);
Ted Kremenek680fe512010-05-05 00:55:23 +00002744
2745 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor92a524f2010-03-18 00:42:48 +00002746 // entering #includes or expanding macros.
Douglas Gregor02ded2a2010-03-18 15:23:44 +00002747 while (true) {
Douglas Gregor92a524f2010-03-18 00:42:48 +00002748 Token Tok;
2749 Lex.LexFromRawLexer(Tok);
Ted Kremenek680fe512010-05-05 00:55:23 +00002750
Douglas Gregor92a524f2010-03-18 00:42:48 +00002751 reprocess:
2752 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
2753 // We have found a preprocessing directive. Gobble it up so that we
2754 // don't see it while preprocessing these tokens later, but keep track of
2755 // all of the token locations inside this preprocessing directive so that
2756 // we can annotate them appropriately.
2757 //
2758 // FIXME: Some simple tests here could identify macro definitions and
2759 // #undefs, to provide specific cursor kinds for those.
2760 std::vector<SourceLocation> Locations;
2761 do {
2762 Locations.push_back(Tok.getLocation());
Ted Kremenek680fe512010-05-05 00:55:23 +00002763 Lex.LexFromRawLexer(Tok);
Douglas Gregor92a524f2010-03-18 00:42:48 +00002764 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenek680fe512010-05-05 00:55:23 +00002765
Douglas Gregor92a524f2010-03-18 00:42:48 +00002766 using namespace cxcursor;
2767 CXCursor Cursor
Ted Kremenek680fe512010-05-05 00:55:23 +00002768 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
2769 Locations.back()),
Ted Kremenek63ac5992010-05-05 00:55:15 +00002770 CXXUnit);
Douglas Gregor92a524f2010-03-18 00:42:48 +00002771 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
2772 Annotated[Locations[I].getRawEncoding()] = Cursor;
2773 }
Ted Kremenek680fe512010-05-05 00:55:23 +00002774
Douglas Gregor92a524f2010-03-18 00:42:48 +00002775 if (Tok.isAtStartOfLine())
2776 goto reprocess;
Ted Kremenek680fe512010-05-05 00:55:23 +00002777
Douglas Gregor92a524f2010-03-18 00:42:48 +00002778 continue;
2779 }
Ted Kremenek680fe512010-05-05 00:55:23 +00002780
Douglas Gregor02ded2a2010-03-18 15:23:44 +00002781 if (Tok.is(tok::eof))
Douglas Gregor92a524f2010-03-18 00:42:48 +00002782 break;
2783 }
Douglas Gregor065f8d12010-03-18 17:52:52 +00002784 }
Ted Kremenek680fe512010-05-05 00:55:23 +00002785
Douglas Gregor5272e802010-03-19 05:22:59 +00002786 // Annotate all of the source locations in the region of interest that map to
Ted Kremenek680fe512010-05-05 00:55:23 +00002787 // a specific cursor.
2788 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
2789 CXXUnit, RegionOfInterest);
2790 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002791}
Douglas Gregor27b4fa92010-01-26 17:06:03 +00002792} // end: extern "C"
2793
2794//===----------------------------------------------------------------------===//
Ted Kremenekfb4961d2010-03-03 06:36:57 +00002795// Operations for querying linkage of a cursor.
2796//===----------------------------------------------------------------------===//
2797
2798extern "C" {
2799CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor5272e802010-03-19 05:22:59 +00002800 if (!clang_isDeclaration(cursor.kind))
2801 return CXLinkage_Invalid;
2802
Ted Kremenekfb4961d2010-03-03 06:36:57 +00002803 Decl *D = cxcursor::getCursorDecl(cursor);
2804 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
2805 switch (ND->getLinkage()) {
2806 case NoLinkage: return CXLinkage_NoLinkage;
2807 case InternalLinkage: return CXLinkage_Internal;
2808 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
2809 case ExternalLinkage: return CXLinkage_External;
2810 };
2811
2812 return CXLinkage_Invalid;
2813}
2814} // end: extern "C"
2815
2816//===----------------------------------------------------------------------===//
Ted Kremenek4ed29252010-04-12 21:22:16 +00002817// Operations for querying language of a cursor.
2818//===----------------------------------------------------------------------===//
2819
2820static CXLanguageKind getDeclLanguage(const Decl *D) {
2821 switch (D->getKind()) {
2822 default:
2823 break;
2824 case Decl::ImplicitParam:
2825 case Decl::ObjCAtDefsField:
2826 case Decl::ObjCCategory:
2827 case Decl::ObjCCategoryImpl:
2828 case Decl::ObjCClass:
2829 case Decl::ObjCCompatibleAlias:
Ted Kremenek4ed29252010-04-12 21:22:16 +00002830 case Decl::ObjCForwardProtocol:
2831 case Decl::ObjCImplementation:
2832 case Decl::ObjCInterface:
2833 case Decl::ObjCIvar:
2834 case Decl::ObjCMethod:
2835 case Decl::ObjCProperty:
2836 case Decl::ObjCPropertyImpl:
2837 case Decl::ObjCProtocol:
2838 return CXLanguage_ObjC;
2839 case Decl::CXXConstructor:
2840 case Decl::CXXConversion:
2841 case Decl::CXXDestructor:
2842 case Decl::CXXMethod:
2843 case Decl::CXXRecord:
2844 case Decl::ClassTemplate:
2845 case Decl::ClassTemplatePartialSpecialization:
2846 case Decl::ClassTemplateSpecialization:
2847 case Decl::Friend:
2848 case Decl::FriendTemplate:
2849 case Decl::FunctionTemplate:
2850 case Decl::LinkageSpec:
2851 case Decl::Namespace:
2852 case Decl::NamespaceAlias:
2853 case Decl::NonTypeTemplateParm:
2854 case Decl::StaticAssert:
Ted Kremenek4ed29252010-04-12 21:22:16 +00002855 case Decl::TemplateTemplateParm:
2856 case Decl::TemplateTypeParm:
2857 case Decl::UnresolvedUsingTypename:
2858 case Decl::UnresolvedUsingValue:
2859 case Decl::Using:
2860 case Decl::UsingDirective:
2861 case Decl::UsingShadow:
2862 return CXLanguage_CPlusPlus;
2863 }
2864
2865 return CXLanguage_C;
2866}
2867
2868extern "C" {
2869CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
2870 if (clang_isDeclaration(cursor.kind))
2871 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
2872
2873 return CXLanguage_Invalid;
2874}
2875} // end: extern "C"
2876
Ted Kremenek9cfe9e62010-05-17 20:06:56 +00002877
2878//===----------------------------------------------------------------------===//
2879// C++ AST instrospection.
2880//===----------------------------------------------------------------------===//
2881
2882extern "C" {
2883unsigned clang_CXXMethod_isStatic(CXCursor C) {
2884 if (!clang_isDeclaration(C.kind))
2885 return 0;
2886 CXXMethodDecl *D = dyn_cast<CXXMethodDecl>(cxcursor::getCursorDecl(C));
2887 return (D && D->isStatic()) ? 1 : 0;
Ted Kremenek0ed75492010-05-17 20:12:45 +00002888}
Ted Kremeneka10f1282010-05-18 22:32:15 +00002889
Ted Kremenek9cfe9e62010-05-17 20:06:56 +00002890} // end: extern "C"
2891
Ted Kremenek4ed29252010-04-12 21:22:16 +00002892//===----------------------------------------------------------------------===//
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002893// CXString Operations.
2894//===----------------------------------------------------------------------===//
2895
2896extern "C" {
2897const char *clang_getCString(CXString string) {
2898 return string.Spelling;
2899}
2900
2901void clang_disposeString(CXString string) {
2902 if (string.MustFreeString && string.Spelling)
2903 free((void*)string.Spelling);
2904}
Ted Kremenekc0f3f722010-01-22 22:44:15 +00002905
Ted Kremenekd5c6eaf2010-01-13 21:46:36 +00002906} // end: extern "C"
Ted Kremenekc0f3f722010-01-22 22:44:15 +00002907
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002908namespace clang { namespace cxstring {
2909CXString createCXString(const char *String, bool DupString){
2910 CXString Str;
2911 if (DupString) {
2912 Str.Spelling = strdup(String);
2913 Str.MustFreeString = 1;
2914 } else {
2915 Str.Spelling = String;
2916 Str.MustFreeString = 0;
2917 }
2918 return Str;
2919}
2920
2921CXString createCXString(llvm::StringRef String, bool DupString) {
2922 CXString Result;
2923 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
2924 char *Spelling = (char *)malloc(String.size() + 1);
2925 memmove(Spelling, String.data(), String.size());
2926 Spelling[String.size()] = 0;
2927 Result.Spelling = Spelling;
2928 Result.MustFreeString = 1;
2929 } else {
2930 Result.Spelling = String.data();
2931 Result.MustFreeString = 0;
2932 }
2933 return Result;
2934}
2935}}
2936
Ted Kremenekc0f3f722010-01-22 22:44:15 +00002937//===----------------------------------------------------------------------===//
2938// Misc. utility functions.
2939//===----------------------------------------------------------------------===//
Ted Kremenekf441baf2010-02-17 00:41:40 +00002940
Ted Kremenekc0f3f722010-01-22 22:44:15 +00002941extern "C" {
2942
Ted Kremeneka3e65702010-02-12 22:54:40 +00002943CXString clang_getClangVersion() {
Ted Kremenek5cca6eb2010-02-17 00:41:08 +00002944 return createCXString(getClangFullVersion());
Ted Kremenekc0f3f722010-01-22 22:44:15 +00002945}
2946
2947} // end: extern "C"