blob: f3aa99ba2f11445f23e06276c3f4e1a02a924bc9 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000033#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000034#include "llvm/ADT/Optional.h"
35#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000036#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000037#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000038#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000040#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000041#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000042#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000043#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000044#include "llvm/System/Threading.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000045
Benjamin Kramerc2a98162010-03-13 21:22:49 +000046// Needed to define L_TMPNAM on some systems.
47#include <cstdio>
48
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Douglas Gregor33e9abd2010-01-22 19:49:59 +000053/// \brief The result of comparing two source ranges.
54enum RangeComparisonResult {
55 /// \brief Either the ranges overlap or one of the ranges is invalid.
56 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Douglas Gregor33e9abd2010-01-22 19:49:59 +000058 /// \brief The first range ends before the second range starts.
59 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Douglas Gregor33e9abd2010-01-22 19:49:59 +000061 /// \brief The first range starts after the second range ends.
62 RangeAfter
63};
64
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000066/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000067static RangeComparisonResult RangeCompare(SourceManager &SM,
68 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 SourceRange R2) {
70 assert(R1.isValid() && "First range is invalid?");
71 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000072 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000073 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000075 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000076 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077 return RangeAfter;
78 return RangeOverlap;
79}
80
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000081/// \brief Determine if a source location falls within, before, or after a
82/// a given source range.
83static RangeComparisonResult LocationCompare(SourceManager &SM,
84 SourceLocation L, SourceRange R) {
85 assert(R.isValid() && "First range is invalid?");
86 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000087 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000088 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000089 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
90 return RangeBefore;
91 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
92 return RangeAfter;
93 return RangeOverlap;
94}
95
Daniel Dunbar76dd3c22010-02-14 01:47:29 +000096/// \brief Translate a Clang source range into a CIndex source range.
97///
98/// Clang internally represents ranges where the end location points to the
99/// start of the token at the end. However, for external clients it is more
100/// useful to have a CXSourceRange be a proper half-open interval. This routine
101/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000102CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000103 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000104 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000106 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000108 if (EndLoc.isValid() && EndLoc.isMacroID())
109 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000110 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 EndLoc = EndLoc.getFileLocWithOffset(Length);
113 }
114
115 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
116 R.getBegin().getRawEncoding(),
117 EndLoc.getRawEncoding() };
118 return Result;
119}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000120
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000122// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123//===----------------------------------------------------------------------===//
124
Steve Naroff89922f82009-08-31 00:59:03 +0000125namespace {
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000126
127class VisitorJob {
128public:
129 enum Kind { StmtVisitKind, MemberExprPartsKind };
130protected:
131 void *data;
132 CXCursor parent;
133 Kind K;
134 VisitorJob(void *d, CXCursor C, Kind k) : data(d), parent(C), K(k) {}
135public:
136 Kind getKind() const { return K; }
137 const CXCursor &getParent() const { return parent; }
138 static bool classof(VisitorJob *VJ) { return true; }
139};
140
141typedef llvm::SmallVector<VisitorJob, 10> VisitorWorkList;
142
143#define DEF_JOB(NAME, DATA, KIND)\
144class NAME : public VisitorJob {\
145public:\
146 NAME(DATA *d, CXCursor parent) : VisitorJob(d, parent, VisitorJob::KIND) {}\
147 static bool classof(const VisitorJob *VJ) { return VJ->getKind() == KIND; }\
148 DATA *get() const { return static_cast<DATA*>(data); }\
149};
150
151DEF_JOB(StmtVisit, Stmt, StmtVisitKind)
152DEF_JOB(MemberExprParts, MemberExpr, MemberExprPartsKind)
153
154#undef DEF_JOB
155
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000156
Douglas Gregorb1373d02010-01-20 20:59:29 +0000157// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000158class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000159 public TypeLocVisitor<CursorVisitor, bool>,
160 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000161{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000162 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000163 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000164
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000165 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000166 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000167
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000168 /// \brief The declaration that serves at the parent of any statement or
169 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000170 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000171
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000172 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000173 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000174
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000175 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000176 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000177
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000178 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
179 // to the visitor. Declarations with a PCH level greater than this value will
180 // be suppressed.
181 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000182
183 /// \brief When valid, a source range to which the cursor should restrict
184 /// its search.
185 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000186
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000187 // FIXME: Eventually remove. This part of a hack to support proper
188 // iteration over all Decls contained lexically within an ObjC container.
189 DeclContext::decl_iterator *DI_current;
190 DeclContext::decl_iterator DE_current;
191
Douglas Gregorb1373d02010-01-20 20:59:29 +0000192 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000193 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000194 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000195
196 /// \brief Determine whether this particular source range comes before, comes
197 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000198 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000199 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000200 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
201
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000202 class SetParentRAII {
203 CXCursor &Parent;
204 Decl *&StmtParent;
205 CXCursor OldParent;
206
207 public:
208 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
209 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
210 {
211 Parent = NewParent;
212 if (clang_isDeclaration(Parent.kind))
213 StmtParent = getCursorDecl(Parent);
214 }
215
216 ~SetParentRAII() {
217 Parent = OldParent;
218 if (clang_isDeclaration(Parent.kind))
219 StmtParent = getCursorDecl(Parent);
220 }
221 };
222
Steve Naroff89922f82009-08-31 00:59:03 +0000223public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000224 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
225 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000226 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000227 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000228 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
229 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000230 {
231 Parent.kind = CXCursor_NoDeclFound;
232 Parent.data[0] = 0;
233 Parent.data[1] = 0;
234 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000235 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000236 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000237
Ted Kremenekab979612010-11-11 08:05:23 +0000238 ASTUnit *getASTUnit() const { return TU; }
239
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000240 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000241
242 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
243 getPreprocessedEntities();
244
Douglas Gregorb1373d02010-01-20 20:59:29 +0000245 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000246
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000247 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000248 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000249 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000250 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000251 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000252 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000253 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
254 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000255 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000256 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000257 bool VisitClassTemplatePartialSpecializationDecl(
258 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000259 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000260 bool VisitEnumConstantDecl(EnumConstantDecl *D);
261 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
262 bool VisitFunctionDecl(FunctionDecl *ND);
263 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000264 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000265 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000266 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000267 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000268 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000269 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
270 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
271 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
272 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000273 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000274 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
275 bool VisitObjCImplDecl(ObjCImplDecl *D);
276 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
277 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000278 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
279 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
280 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000281 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000282 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000283 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000284 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000285 bool VisitUsingDecl(UsingDecl *D);
286 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
287 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000288
Douglas Gregor01829d32010-08-31 14:41:23 +0000289 // Name visitor
290 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000291 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000292
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000293 // Template visitors
294 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000295 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000296 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
297
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000298 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000299 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000300 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000301 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000302 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
303 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000304 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000305 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000306 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000307 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
308 bool VisitPointerTypeLoc(PointerTypeLoc TL);
309 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
310 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
311 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
312 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000313 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000314 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000315 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000316 // FIXME: Implement visitors here when the unimplemented TypeLocs get
317 // implemented
318 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
319 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000320
Douglas Gregora59e3902010-01-21 23:27:09 +0000321 // Statement visitors
322 bool VisitStmt(Stmt *S);
323 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000324 bool VisitGotoStmt(GotoStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000325 bool VisitIfStmt(IfStmt *S);
326 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000327 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000328 bool VisitWhileStmt(WhileStmt *S);
329 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000330
Douglas Gregor336fd812010-01-23 00:40:08 +0000331 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000332 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000333 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000334 bool VisitBlockExpr(BlockExpr *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000335 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000336 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000337 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000338 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000339 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000340 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000341 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000342 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
343 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000344 bool VisitInitListExpr(InitListExpr *E);
345 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000346 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000347 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000348 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000349 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
350 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000351 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000352 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000353 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000354 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000355 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000356 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000357 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000358 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Ted Kremenekc0e1d922010-11-11 08:05:18 +0000359
360#define DATA_RECURSIVE_VISIT(NAME)\
361bool Visit##NAME(NAME *S) { return VisitDataRecursive(S); }
362 DATA_RECURSIVE_VISIT(BinaryOperator)
363 DATA_RECURSIVE_VISIT(MemberExpr)
364 DATA_RECURSIVE_VISIT(CXXMemberCallExpr)
365
366 // Data-recursive visitor functions.
367 bool IsInRegionOfInterest(CXCursor C);
368 bool RunVisitorWorkList(VisitorWorkList &WL);
369 void EnqueueWorkList(VisitorWorkList &WL, Stmt *S);
370 bool VisitDataRecursive(Stmt *S);
Steve Naroff89922f82009-08-31 00:59:03 +0000371};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000372
Ted Kremenekab188932010-01-05 19:32:54 +0000373} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000374
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000375static SourceRange getRawCursorExtent(CXCursor C);
376
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000377RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000378 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
379}
380
Douglas Gregorb1373d02010-01-20 20:59:29 +0000381/// \brief Visit the given cursor and, if requested by the visitor,
382/// its children.
383///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000384/// \param Cursor the cursor to visit.
385///
386/// \param CheckRegionOfInterest if true, then the caller already checked that
387/// this cursor is within the region of interest.
388///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000389/// \returns true if the visitation should be aborted, false if it
390/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000391bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000392 if (clang_isInvalid(Cursor.kind))
393 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000394
Douglas Gregorb1373d02010-01-20 20:59:29 +0000395 if (clang_isDeclaration(Cursor.kind)) {
396 Decl *D = getCursorDecl(Cursor);
397 assert(D && "Invalid declaration cursor");
398 if (D->getPCHLevel() > MaxPCHLevel)
399 return false;
400
401 if (D->isImplicit())
402 return false;
403 }
404
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000405 // If we have a range of interest, and this cursor doesn't intersect with it,
406 // we're done.
407 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000408 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000409 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000410 return false;
411 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000412
Douglas Gregorb1373d02010-01-20 20:59:29 +0000413 switch (Visitor(Cursor, Parent, ClientData)) {
414 case CXChildVisit_Break:
415 return true;
416
417 case CXChildVisit_Continue:
418 return false;
419
420 case CXChildVisit_Recurse:
421 return VisitChildren(Cursor);
422 }
423
Douglas Gregorfd643772010-01-25 16:45:46 +0000424 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000425}
426
Douglas Gregor788f5a12010-03-20 00:41:21 +0000427std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
428CursorVisitor::getPreprocessedEntities() {
429 PreprocessingRecord &PPRec
430 = *TU->getPreprocessor().getPreprocessingRecord();
431
432 bool OnlyLocalDecls
433 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
434
435 // There is no region of interest; we have to walk everything.
436 if (RegionOfInterest.isInvalid())
437 return std::make_pair(PPRec.begin(OnlyLocalDecls),
438 PPRec.end(OnlyLocalDecls));
439
440 // Find the file in which the region of interest lands.
441 SourceManager &SM = TU->getSourceManager();
442 std::pair<FileID, unsigned> Begin
443 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
444 std::pair<FileID, unsigned> End
445 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
446
447 // The region of interest spans files; we have to walk everything.
448 if (Begin.first != End.first)
449 return std::make_pair(PPRec.begin(OnlyLocalDecls),
450 PPRec.end(OnlyLocalDecls));
451
452 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
453 = TU->getPreprocessedEntitiesByFile();
454 if (ByFileMap.empty()) {
455 // Build the mapping from files to sets of preprocessed entities.
456 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
457 EEnd = PPRec.end(OnlyLocalDecls);
458 E != EEnd; ++E) {
459 std::pair<FileID, unsigned> P
460 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
461 ByFileMap[P.first].push_back(*E);
462 }
463 }
464
465 return std::make_pair(ByFileMap[Begin.first].begin(),
466 ByFileMap[Begin.first].end());
467}
468
Douglas Gregorb1373d02010-01-20 20:59:29 +0000469/// \brief Visit the children of the given cursor.
470///
471/// \returns true if the visitation should be aborted, false if it
472/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000473bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000474 if (clang_isReference(Cursor.kind)) {
475 // By definition, references have no children.
476 return false;
477 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000478
479 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000480 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000481 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000482
Douglas Gregorb1373d02010-01-20 20:59:29 +0000483 if (clang_isDeclaration(Cursor.kind)) {
484 Decl *D = getCursorDecl(Cursor);
485 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000486 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000487 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000488
Douglas Gregora59e3902010-01-21 23:27:09 +0000489 if (clang_isStatement(Cursor.kind))
490 return Visit(getCursorStmt(Cursor));
491 if (clang_isExpression(Cursor.kind))
492 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000493
Douglas Gregorb1373d02010-01-20 20:59:29 +0000494 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000495 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000496 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
497 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000498 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
499 TLEnd = CXXUnit->top_level_end();
500 TL != TLEnd; ++TL) {
501 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000502 return true;
503 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000504 } else if (VisitDeclContext(
505 CXXUnit->getASTContext().getTranslationUnitDecl()))
506 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000507
Douglas Gregor0396f462010-03-19 05:22:59 +0000508 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000509 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000510 // FIXME: Once we have the ability to deserialize a preprocessing record,
511 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000512 PreprocessingRecord::iterator E, EEnd;
513 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000514 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
515 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
516 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000517
Douglas Gregor0396f462010-03-19 05:22:59 +0000518 continue;
519 }
520
521 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
522 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
523 return true;
524
525 continue;
526 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000527
528 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
529 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
530 return true;
531
532 continue;
533 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000534 }
535 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000536 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000537 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000538
Douglas Gregorb1373d02010-01-20 20:59:29 +0000539 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000540 return false;
541}
542
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000543bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000544 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
545 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000546
Ted Kremenek664cffd2010-07-22 11:30:19 +0000547 if (Stmt *Body = B->getBody())
548 return Visit(MakeCXCursor(Body, StmtParent, TU));
549
550 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000551}
552
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000553llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
554 if (RegionOfInterest.isValid()) {
555 SourceRange Range = getRawCursorExtent(Cursor);
556 if (Range.isInvalid())
557 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000558
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000559 switch (CompareRegionOfInterest(Range)) {
560 case RangeBefore:
561 // This declaration comes before the region of interest; skip it.
562 return llvm::Optional<bool>();
563
564 case RangeAfter:
565 // This declaration comes after the region of interest; we're done.
566 return false;
567
568 case RangeOverlap:
569 // This declaration overlaps the region of interest; visit it.
570 break;
571 }
572 }
573 return true;
574}
575
576bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
577 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
578
579 // FIXME: Eventually remove. This part of a hack to support proper
580 // iteration over all Decls contained lexically within an ObjC container.
581 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
582 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
583
584 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000585 Decl *D = *I;
586 if (D->getLexicalDeclContext() != DC)
587 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000588 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000589 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
590 if (!V.hasValue())
591 continue;
592 if (!V.getValue())
593 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000594 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000595 return true;
596 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000597 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000598}
599
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000600bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
601 llvm_unreachable("Translation units are visited directly by Visit()");
602 return false;
603}
604
605bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
606 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
607 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000608
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000609 return false;
610}
611
612bool CursorVisitor::VisitTagDecl(TagDecl *D) {
613 return VisitDeclContext(D);
614}
615
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000616bool CursorVisitor::VisitClassTemplateSpecializationDecl(
617 ClassTemplateSpecializationDecl *D) {
618 bool ShouldVisitBody = false;
619 switch (D->getSpecializationKind()) {
620 case TSK_Undeclared:
621 case TSK_ImplicitInstantiation:
622 // Nothing to visit
623 return false;
624
625 case TSK_ExplicitInstantiationDeclaration:
626 case TSK_ExplicitInstantiationDefinition:
627 break;
628
629 case TSK_ExplicitSpecialization:
630 ShouldVisitBody = true;
631 break;
632 }
633
634 // Visit the template arguments used in the specialization.
635 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
636 TypeLoc TL = SpecType->getTypeLoc();
637 if (TemplateSpecializationTypeLoc *TSTLoc
638 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
639 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
640 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
641 return true;
642 }
643 }
644
645 if (ShouldVisitBody && VisitCXXRecordDecl(D))
646 return true;
647
648 return false;
649}
650
Douglas Gregor74dbe642010-08-31 19:31:58 +0000651bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
652 ClassTemplatePartialSpecializationDecl *D) {
653 // FIXME: Visit the "outer" template parameter lists on the TagDecl
654 // before visiting these template parameters.
655 if (VisitTemplateParameters(D->getTemplateParameters()))
656 return true;
657
658 // Visit the partial specialization arguments.
659 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
660 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
661 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
662 return true;
663
664 return VisitCXXRecordDecl(D);
665}
666
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000667bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000668 // Visit the default argument.
669 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
670 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
671 if (Visit(DefArg->getTypeLoc()))
672 return true;
673
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000674 return false;
675}
676
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000677bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
678 if (Expr *Init = D->getInitExpr())
679 return Visit(MakeCXCursor(Init, StmtParent, TU));
680 return false;
681}
682
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000683bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
684 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
685 if (Visit(TSInfo->getTypeLoc()))
686 return true;
687
688 return false;
689}
690
Douglas Gregora67e03f2010-09-09 21:42:20 +0000691/// \brief Compare two base or member initializers based on their source order.
692static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
693 CXXBaseOrMemberInitializer const * const *X
694 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
695 CXXBaseOrMemberInitializer const * const *Y
696 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
697
698 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
699 return -1;
700 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
701 return 1;
702 else
703 return 0;
704}
705
Douglas Gregorb1373d02010-01-20 20:59:29 +0000706bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000707 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
708 // Visit the function declaration's syntactic components in the order
709 // written. This requires a bit of work.
710 TypeLoc TL = TSInfo->getTypeLoc();
711 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
712
713 // If we have a function declared directly (without the use of a typedef),
714 // visit just the return type. Otherwise, just visit the function's type
715 // now.
716 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
717 (!FTL && Visit(TL)))
718 return true;
719
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000720 // Visit the nested-name-specifier, if present.
721 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
722 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
723 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000724
725 // Visit the declaration name.
726 if (VisitDeclarationNameInfo(ND->getNameInfo()))
727 return true;
728
729 // FIXME: Visit explicitly-specified template arguments!
730
731 // Visit the function parameters, if we have a function type.
732 if (FTL && VisitFunctionTypeLoc(*FTL, true))
733 return true;
734
735 // FIXME: Attributes?
736 }
737
Douglas Gregora67e03f2010-09-09 21:42:20 +0000738 if (ND->isThisDeclarationADefinition()) {
739 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
740 // Find the initializers that were written in the source.
741 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
742 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
743 IEnd = Constructor->init_end();
744 I != IEnd; ++I) {
745 if (!(*I)->isWritten())
746 continue;
747
748 WrittenInits.push_back(*I);
749 }
750
751 // Sort the initializers in source order
752 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
753 &CompareCXXBaseOrMemberInitializers);
754
755 // Visit the initializers in source order
756 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
757 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
758 if (Init->isMemberInitializer()) {
759 if (Visit(MakeCursorMemberRef(Init->getMember(),
760 Init->getMemberLocation(), TU)))
761 return true;
762 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
763 if (Visit(BaseInfo->getTypeLoc()))
764 return true;
765 }
766
767 // Visit the initializer value.
768 if (Expr *Initializer = Init->getInit())
769 if (Visit(MakeCXCursor(Initializer, ND, TU)))
770 return true;
771 }
772 }
773
774 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
775 return true;
776 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000777
Douglas Gregorb1373d02010-01-20 20:59:29 +0000778 return false;
779}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000780
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000781bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
782 if (VisitDeclaratorDecl(D))
783 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000784
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000785 if (Expr *BitWidth = D->getBitWidth())
786 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000787
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000788 return false;
789}
790
791bool CursorVisitor::VisitVarDecl(VarDecl *D) {
792 if (VisitDeclaratorDecl(D))
793 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000794
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000795 if (Expr *Init = D->getInit())
796 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000797
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000798 return false;
799}
800
Douglas Gregor84b51d72010-09-01 20:16:53 +0000801bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
802 if (VisitDeclaratorDecl(D))
803 return true;
804
805 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
806 if (Expr *DefArg = D->getDefaultArgument())
807 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
808
809 return false;
810}
811
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000812bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
813 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
814 // before visiting these template parameters.
815 if (VisitTemplateParameters(D->getTemplateParameters()))
816 return true;
817
818 return VisitFunctionDecl(D->getTemplatedDecl());
819}
820
Douglas Gregor39d6f072010-08-31 19:02:00 +0000821bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
822 // FIXME: Visit the "outer" template parameter lists on the TagDecl
823 // before visiting these template parameters.
824 if (VisitTemplateParameters(D->getTemplateParameters()))
825 return true;
826
827 return VisitCXXRecordDecl(D->getTemplatedDecl());
828}
829
Douglas Gregor84b51d72010-09-01 20:16:53 +0000830bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
831 if (VisitTemplateParameters(D->getTemplateParameters()))
832 return true;
833
834 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
835 VisitTemplateArgumentLoc(D->getDefaultArgument()))
836 return true;
837
838 return false;
839}
840
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000841bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000842 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
843 if (Visit(TSInfo->getTypeLoc()))
844 return true;
845
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000846 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000847 PEnd = ND->param_end();
848 P != PEnd; ++P) {
849 if (Visit(MakeCXCursor(*P, TU)))
850 return true;
851 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000852
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000853 if (ND->isThisDeclarationADefinition() &&
854 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
855 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000856
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000857 return false;
858}
859
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000860namespace {
861 struct ContainerDeclsSort {
862 SourceManager &SM;
863 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
864 bool operator()(Decl *A, Decl *B) {
865 SourceLocation L_A = A->getLocStart();
866 SourceLocation L_B = B->getLocStart();
867 assert(L_A.isValid() && L_B.isValid());
868 return SM.isBeforeInTranslationUnit(L_A, L_B);
869 }
870 };
871}
872
Douglas Gregora59e3902010-01-21 23:27:09 +0000873bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000874 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
875 // an @implementation can lexically contain Decls that are not properly
876 // nested in the AST. When we identify such cases, we need to retrofit
877 // this nesting here.
878 if (!DI_current)
879 return VisitDeclContext(D);
880
881 // Scan the Decls that immediately come after the container
882 // in the current DeclContext. If any fall within the
883 // container's lexical region, stash them into a vector
884 // for later processing.
885 llvm::SmallVector<Decl *, 24> DeclsInContainer;
886 SourceLocation EndLoc = D->getSourceRange().getEnd();
887 SourceManager &SM = TU->getSourceManager();
888 if (EndLoc.isValid()) {
889 DeclContext::decl_iterator next = *DI_current;
890 while (++next != DE_current) {
891 Decl *D_next = *next;
892 if (!D_next)
893 break;
894 SourceLocation L = D_next->getLocStart();
895 if (!L.isValid())
896 break;
897 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
898 *DI_current = next;
899 DeclsInContainer.push_back(D_next);
900 continue;
901 }
902 break;
903 }
904 }
905
906 // The common case.
907 if (DeclsInContainer.empty())
908 return VisitDeclContext(D);
909
910 // Get all the Decls in the DeclContext, and sort them with the
911 // additional ones we've collected. Then visit them.
912 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
913 I!=E; ++I) {
914 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000915 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
916 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000917 continue;
918 DeclsInContainer.push_back(subDecl);
919 }
920
921 // Now sort the Decls so that they appear in lexical order.
922 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
923 ContainerDeclsSort(SM));
924
925 // Now visit the decls.
926 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
927 E = DeclsInContainer.end(); I != E; ++I) {
928 CXCursor Cursor = MakeCXCursor(*I, TU);
929 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
930 if (!V.hasValue())
931 continue;
932 if (!V.getValue())
933 return false;
934 if (Visit(Cursor, true))
935 return true;
936 }
937 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000938}
939
Douglas Gregorb1373d02010-01-20 20:59:29 +0000940bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000941 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
942 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000943 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000944
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000945 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
946 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
947 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000948 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000949 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000950
Douglas Gregora59e3902010-01-21 23:27:09 +0000951 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000952}
953
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000954bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
955 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
956 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
957 E = PID->protocol_end(); I != E; ++I, ++PL)
958 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
959 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000960
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000961 return VisitObjCContainerDecl(PID);
962}
963
Ted Kremenek23173d72010-05-18 21:09:07 +0000964bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000965 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000966 return true;
967
Ted Kremenek23173d72010-05-18 21:09:07 +0000968 // FIXME: This implements a workaround with @property declarations also being
969 // installed in the DeclContext for the @interface. Eventually this code
970 // should be removed.
971 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
972 if (!CDecl || !CDecl->IsClassExtension())
973 return false;
974
975 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
976 if (!ID)
977 return false;
978
979 IdentifierInfo *PropertyId = PD->getIdentifier();
980 ObjCPropertyDecl *prevDecl =
981 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
982
983 if (!prevDecl)
984 return false;
985
986 // Visit synthesized methods since they will be skipped when visiting
987 // the @interface.
988 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000989 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000990 if (Visit(MakeCXCursor(MD, TU)))
991 return true;
992
993 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000994 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000995 if (Visit(MakeCXCursor(MD, TU)))
996 return true;
997
998 return false;
999}
1000
Douglas Gregorb1373d02010-01-20 20:59:29 +00001001bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001002 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +00001003 if (D->getSuperClass() &&
1004 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001005 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001006 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001007 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001008
Douglas Gregor78db0cd2010-01-16 15:44:18 +00001009 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1010 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
1011 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001012 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001013 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001014
Douglas Gregora59e3902010-01-21 23:27:09 +00001015 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001016}
1017
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001018bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
1019 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001020}
1021
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001022bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +00001023 // 'ID' could be null when dealing with invalid code.
1024 if (ObjCInterfaceDecl *ID = D->getClassInterface())
1025 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
1026 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001027
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001028 return VisitObjCImplDecl(D);
1029}
1030
1031bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1032#if 0
1033 // Issue callbacks for super class.
1034 // FIXME: No source location information!
1035 if (D->getSuperClass() &&
1036 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001037 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001038 TU)))
1039 return true;
1040#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001041
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001042 return VisitObjCImplDecl(D);
1043}
1044
1045bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1046 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1047 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1048 E = D->protocol_end();
1049 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001050 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001051 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001052
1053 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001054}
1055
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001056bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1057 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1058 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1059 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001060
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001061 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001062}
1063
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001064bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1065 return VisitDeclContext(D);
1066}
1067
Douglas Gregor69319002010-08-31 23:48:11 +00001068bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001069 // Visit nested-name-specifier.
1070 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1071 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1072 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001073
1074 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1075 D->getTargetNameLoc(), TU));
1076}
1077
Douglas Gregor7e242562010-09-01 19:52:22 +00001078bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001079 // Visit nested-name-specifier.
1080 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1081 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1082 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001083
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001084 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1085 return true;
1086
Douglas Gregor7e242562010-09-01 19:52:22 +00001087 return VisitDeclarationNameInfo(D->getNameInfo());
1088}
1089
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001090bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001091 // Visit nested-name-specifier.
1092 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1093 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1094 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001095
1096 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1097 D->getIdentLocation(), TU));
1098}
1099
Douglas Gregor7e242562010-09-01 19:52:22 +00001100bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001101 // Visit nested-name-specifier.
1102 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1103 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1104 return true;
1105
Douglas Gregor7e242562010-09-01 19:52:22 +00001106 return VisitDeclarationNameInfo(D->getNameInfo());
1107}
1108
1109bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1110 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001111 // Visit nested-name-specifier.
1112 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1113 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1114 return true;
1115
Douglas Gregor7e242562010-09-01 19:52:22 +00001116 return false;
1117}
1118
Douglas Gregor01829d32010-08-31 14:41:23 +00001119bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1120 switch (Name.getName().getNameKind()) {
1121 case clang::DeclarationName::Identifier:
1122 case clang::DeclarationName::CXXLiteralOperatorName:
1123 case clang::DeclarationName::CXXOperatorName:
1124 case clang::DeclarationName::CXXUsingDirective:
1125 return false;
1126
1127 case clang::DeclarationName::CXXConstructorName:
1128 case clang::DeclarationName::CXXDestructorName:
1129 case clang::DeclarationName::CXXConversionFunctionName:
1130 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1131 return Visit(TSInfo->getTypeLoc());
1132 return false;
1133
1134 case clang::DeclarationName::ObjCZeroArgSelector:
1135 case clang::DeclarationName::ObjCOneArgSelector:
1136 case clang::DeclarationName::ObjCMultiArgSelector:
1137 // FIXME: Per-identifier location info?
1138 return false;
1139 }
1140
1141 return false;
1142}
1143
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001144bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1145 SourceRange Range) {
1146 // FIXME: This whole routine is a hack to work around the lack of proper
1147 // source information in nested-name-specifiers (PR5791). Since we do have
1148 // a beginning source location, we can visit the first component of the
1149 // nested-name-specifier, if it's a single-token component.
1150 if (!NNS)
1151 return false;
1152
1153 // Get the first component in the nested-name-specifier.
1154 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1155 NNS = Prefix;
1156
1157 switch (NNS->getKind()) {
1158 case NestedNameSpecifier::Namespace:
1159 // FIXME: The token at this source location might actually have been a
1160 // namespace alias, but we don't model that. Lame!
1161 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1162 TU));
1163
1164 case NestedNameSpecifier::TypeSpec: {
1165 // If the type has a form where we know that the beginning of the source
1166 // range matches up with a reference cursor. Visit the appropriate reference
1167 // cursor.
1168 Type *T = NNS->getAsType();
1169 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1170 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1171 if (const TagType *Tag = dyn_cast<TagType>(T))
1172 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1173 if (const TemplateSpecializationType *TST
1174 = dyn_cast<TemplateSpecializationType>(T))
1175 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1176 break;
1177 }
1178
1179 case NestedNameSpecifier::TypeSpecWithTemplate:
1180 case NestedNameSpecifier::Global:
1181 case NestedNameSpecifier::Identifier:
1182 break;
1183 }
1184
1185 return false;
1186}
1187
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001188bool CursorVisitor::VisitTemplateParameters(
1189 const TemplateParameterList *Params) {
1190 if (!Params)
1191 return false;
1192
1193 for (TemplateParameterList::const_iterator P = Params->begin(),
1194 PEnd = Params->end();
1195 P != PEnd; ++P) {
1196 if (Visit(MakeCXCursor(*P, TU)))
1197 return true;
1198 }
1199
1200 return false;
1201}
1202
Douglas Gregor0b36e612010-08-31 20:37:03 +00001203bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1204 switch (Name.getKind()) {
1205 case TemplateName::Template:
1206 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1207
1208 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001209 // Visit the overloaded template set.
1210 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1211 return true;
1212
Douglas Gregor0b36e612010-08-31 20:37:03 +00001213 return false;
1214
1215 case TemplateName::DependentTemplate:
1216 // FIXME: Visit nested-name-specifier.
1217 return false;
1218
1219 case TemplateName::QualifiedTemplate:
1220 // FIXME: Visit nested-name-specifier.
1221 return Visit(MakeCursorTemplateRef(
1222 Name.getAsQualifiedTemplateName()->getDecl(),
1223 Loc, TU));
1224 }
1225
1226 return false;
1227}
1228
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001229bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1230 switch (TAL.getArgument().getKind()) {
1231 case TemplateArgument::Null:
1232 case TemplateArgument::Integral:
1233 return false;
1234
1235 case TemplateArgument::Pack:
1236 // FIXME: Implement when variadic templates come along.
1237 return false;
1238
1239 case TemplateArgument::Type:
1240 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1241 return Visit(TSInfo->getTypeLoc());
1242 return false;
1243
1244 case TemplateArgument::Declaration:
1245 if (Expr *E = TAL.getSourceDeclExpression())
1246 return Visit(MakeCXCursor(E, StmtParent, TU));
1247 return false;
1248
1249 case TemplateArgument::Expression:
1250 if (Expr *E = TAL.getSourceExpression())
1251 return Visit(MakeCXCursor(E, StmtParent, TU));
1252 return false;
1253
1254 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001255 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1256 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001257 }
1258
1259 return false;
1260}
1261
Ted Kremeneka0536d82010-05-07 01:04:29 +00001262bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1263 return VisitDeclContext(D);
1264}
1265
Douglas Gregor01829d32010-08-31 14:41:23 +00001266bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1267 return Visit(TL.getUnqualifiedLoc());
1268}
1269
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001270bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1271 ASTContext &Context = TU->getASTContext();
1272
1273 // Some builtin types (such as Objective-C's "id", "sel", and
1274 // "Class") have associated declarations. Create cursors for those.
1275 QualType VisitType;
1276 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001277 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001278 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001279 case BuiltinType::Char_U:
1280 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001281 case BuiltinType::Char16:
1282 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001283 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001284 case BuiltinType::UInt:
1285 case BuiltinType::ULong:
1286 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001287 case BuiltinType::UInt128:
1288 case BuiltinType::Char_S:
1289 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001290 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001291 case BuiltinType::Short:
1292 case BuiltinType::Int:
1293 case BuiltinType::Long:
1294 case BuiltinType::LongLong:
1295 case BuiltinType::Int128:
1296 case BuiltinType::Float:
1297 case BuiltinType::Double:
1298 case BuiltinType::LongDouble:
1299 case BuiltinType::NullPtr:
1300 case BuiltinType::Overload:
1301 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001302 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001303
1304 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001305 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001306
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001307 case BuiltinType::ObjCId:
1308 VisitType = Context.getObjCIdType();
1309 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001310
1311 case BuiltinType::ObjCClass:
1312 VisitType = Context.getObjCClassType();
1313 break;
1314
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001315 case BuiltinType::ObjCSel:
1316 VisitType = Context.getObjCSelType();
1317 break;
1318 }
1319
1320 if (!VisitType.isNull()) {
1321 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001322 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001323 TU));
1324 }
1325
1326 return false;
1327}
1328
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001329bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1330 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1331}
1332
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001333bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1334 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1335}
1336
1337bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1338 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1339}
1340
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001341bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001342 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001343 // no context information with which we can match up the depth/index in the
1344 // type to the appropriate
1345 return false;
1346}
1347
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001348bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1349 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1350 return true;
1351
John McCallc12c5bb2010-05-15 11:32:37 +00001352 return false;
1353}
1354
1355bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1356 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1357 return true;
1358
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001359 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1360 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1361 TU)))
1362 return true;
1363 }
1364
1365 return false;
1366}
1367
1368bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001369 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001370}
1371
1372bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1373 return Visit(TL.getPointeeLoc());
1374}
1375
1376bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1377 return Visit(TL.getPointeeLoc());
1378}
1379
1380bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1381 return Visit(TL.getPointeeLoc());
1382}
1383
1384bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001385 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001386}
1387
1388bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001389 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001390}
1391
Douglas Gregor01829d32010-08-31 14:41:23 +00001392bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1393 bool SkipResultType) {
1394 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001395 return true;
1396
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001397 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001398 if (Decl *D = TL.getArg(I))
1399 if (Visit(MakeCXCursor(D, TU)))
1400 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001401
1402 return false;
1403}
1404
1405bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1406 if (Visit(TL.getElementLoc()))
1407 return true;
1408
1409 if (Expr *Size = TL.getSizeExpr())
1410 return Visit(MakeCXCursor(Size, StmtParent, TU));
1411
1412 return false;
1413}
1414
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001415bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1416 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001417 // Visit the template name.
1418 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1419 TL.getTemplateNameLoc()))
1420 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001421
1422 // Visit the template arguments.
1423 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1424 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1425 return true;
1426
1427 return false;
1428}
1429
Douglas Gregor2332c112010-01-21 20:48:56 +00001430bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1431 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1432}
1433
1434bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1435 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1436 return Visit(TSInfo->getTypeLoc());
1437
1438 return false;
1439}
1440
Douglas Gregora59e3902010-01-21 23:27:09 +00001441bool CursorVisitor::VisitStmt(Stmt *S) {
1442 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1443 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001444 if (Stmt *C = *Child)
1445 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1446 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001447 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001448
Douglas Gregora59e3902010-01-21 23:27:09 +00001449 return false;
1450}
1451
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001452bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1453 // Specially handle CaseStmts because they can be nested, e.g.:
1454 //
1455 // case 1:
1456 // case 2:
1457 //
1458 // In this case the second CaseStmt is the child of the first. Walking
1459 // these recursively can blow out the stack.
1460 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1461 while (true) {
1462 // Set the Parent field to Cursor, then back to its old value once we're
1463 // done.
1464 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1465
1466 if (Stmt *LHS = S->getLHS())
1467 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1468 return true;
1469 if (Stmt *RHS = S->getRHS())
1470 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1471 return true;
1472 if (Stmt *SubStmt = S->getSubStmt()) {
1473 if (!isa<CaseStmt>(SubStmt))
1474 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1475
1476 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1477 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1478 Cursor = MakeCXCursor(CS, StmtParent, TU);
1479 if (RegionOfInterest.isValid()) {
1480 SourceRange Range = CS->getSourceRange();
1481 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1482 return false;
1483 }
1484
1485 switch (Visitor(Cursor, Parent, ClientData)) {
1486 case CXChildVisit_Break: return true;
1487 case CXChildVisit_Continue: return false;
1488 case CXChildVisit_Recurse:
1489 // Perform tail-recursion manually.
1490 S = CS;
1491 continue;
1492 }
1493 }
1494 return false;
1495 }
1496}
1497
Douglas Gregora59e3902010-01-21 23:27:09 +00001498bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001499 bool isFirst = true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001500 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1501 D != DEnd; ++D) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001502 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001503 return true;
Ted Kremenek007a7c92010-11-01 23:26:51 +00001504 isFirst = false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001505 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001506
Douglas Gregora59e3902010-01-21 23:27:09 +00001507 return false;
1508}
1509
Douglas Gregor36897b02010-09-10 00:22:18 +00001510bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1511 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1512}
1513
Douglas Gregorf5bab412010-01-22 01:00:11 +00001514bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1515 if (VarDecl *Var = S->getConditionVariable()) {
1516 if (Visit(MakeCXCursor(Var, TU)))
1517 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001518 }
1519
Douglas Gregor263b47b2010-01-25 16:12:32 +00001520 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1521 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001522 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1523 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001524 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1525 return true;
1526
1527 return false;
1528}
1529
1530bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1531 if (VarDecl *Var = S->getConditionVariable()) {
1532 if (Visit(MakeCXCursor(Var, TU)))
1533 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001534 }
1535
Douglas Gregor263b47b2010-01-25 16:12:32 +00001536 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1537 return true;
1538 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1539 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001540
Douglas Gregor263b47b2010-01-25 16:12:32 +00001541 return false;
1542}
1543
1544bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1545 if (VarDecl *Var = S->getConditionVariable()) {
1546 if (Visit(MakeCXCursor(Var, TU)))
1547 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001548 }
1549
Douglas Gregor263b47b2010-01-25 16:12:32 +00001550 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1551 return true;
1552 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001553 return true;
1554
Douglas Gregor263b47b2010-01-25 16:12:32 +00001555 return false;
1556}
1557
1558bool CursorVisitor::VisitForStmt(ForStmt *S) {
1559 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1560 return true;
1561 if (VarDecl *Var = S->getConditionVariable()) {
1562 if (Visit(MakeCXCursor(Var, TU)))
1563 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001564 }
1565
Douglas Gregor263b47b2010-01-25 16:12:32 +00001566 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1567 return true;
1568 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1569 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001570 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1571 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001572
Douglas Gregorf5bab412010-01-22 01:00:11 +00001573 return false;
1574}
1575
Douglas Gregor8947a752010-09-02 20:35:02 +00001576bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1577 // Visit nested-name-specifier, if present.
1578 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1579 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1580 return true;
1581
1582 // Visit declaration name.
1583 if (VisitDeclarationNameInfo(E->getNameInfo()))
1584 return true;
1585
1586 // Visit explicitly-specified template arguments.
1587 if (E->hasExplicitTemplateArgs()) {
1588 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1589 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1590 *ArgEnd = Arg + Args.NumTemplateArgs;
1591 Arg != ArgEnd; ++Arg)
1592 if (VisitTemplateArgumentLoc(*Arg))
1593 return true;
1594 }
1595
1596 return false;
1597}
1598
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001599bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1600 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1601 return true;
1602
1603 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1604 return true;
1605
1606 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1607 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1608 return true;
1609
1610 return false;
1611}
1612
Ted Kremenek3064ef92010-08-27 21:34:58 +00001613bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1614 if (D->isDefinition()) {
1615 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1616 E = D->bases_end(); I != E; ++I) {
1617 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1618 return true;
1619 }
1620 }
1621
1622 return VisitTagDecl(D);
1623}
1624
1625
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001626bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1627 return Visit(B->getBlockDecl());
1628}
1629
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001630bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001631 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001632 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1633 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001634
1635 // Visit the components of the offsetof expression.
1636 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1637 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1638 const OffsetOfNode &Node = E->getComponent(I);
1639 switch (Node.getKind()) {
1640 case OffsetOfNode::Array:
1641 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1642 StmtParent, TU)))
1643 return true;
1644 break;
1645
1646 case OffsetOfNode::Field:
1647 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1648 TU)))
1649 return true;
1650 break;
1651
1652 case OffsetOfNode::Identifier:
1653 case OffsetOfNode::Base:
1654 continue;
1655 }
1656 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001657
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001658 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001659}
1660
Douglas Gregor336fd812010-01-23 00:40:08 +00001661bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1662 if (E->isArgumentType()) {
1663 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1664 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001665
Douglas Gregor336fd812010-01-23 00:40:08 +00001666 return false;
1667 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001668
Douglas Gregor336fd812010-01-23 00:40:08 +00001669 return VisitExpr(E);
1670}
1671
1672bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1673 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1674 if (Visit(TSInfo->getTypeLoc()))
1675 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001676
Douglas Gregor336fd812010-01-23 00:40:08 +00001677 return VisitCastExpr(E);
1678}
1679
1680bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1681 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1682 if (Visit(TSInfo->getTypeLoc()))
1683 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001684
Douglas Gregor336fd812010-01-23 00:40:08 +00001685 return VisitExpr(E);
1686}
1687
Douglas Gregor36897b02010-09-10 00:22:18 +00001688bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1689 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1690}
1691
Douglas Gregor648220e2010-08-10 15:02:34 +00001692bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1693 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1694 Visit(E->getArgTInfo2()->getTypeLoc());
1695}
1696
1697bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1698 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1699 return true;
1700
1701 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1702}
1703
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001704bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1705 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001706 if (InitListExpr *Syntactic = E->getSyntacticForm())
1707 return VisitExpr(Syntactic);
1708
1709 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001710}
1711
1712bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1713 // Visit the designators.
1714 typedef DesignatedInitExpr::Designator Designator;
1715 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1716 DEnd = E->designators_end();
1717 D != DEnd; ++D) {
1718 if (D->isFieldDesignator()) {
1719 if (FieldDecl *Field = D->getField())
1720 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1721 return true;
1722
1723 continue;
1724 }
1725
1726 if (D->isArrayDesignator()) {
1727 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1728 return true;
1729
1730 continue;
1731 }
1732
1733 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1734 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1735 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1736 return true;
1737 }
1738
1739 // Visit the initializer value itself.
1740 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1741}
1742
Douglas Gregor94802292010-09-02 21:20:16 +00001743bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1744 if (E->isTypeOperand()) {
1745 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1746 return Visit(TSInfo->getTypeLoc());
1747
1748 return false;
1749 }
1750
1751 return VisitExpr(E);
1752}
1753
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001754bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1755 if (E->isTypeOperand()) {
1756 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1757 return Visit(TSInfo->getTypeLoc());
1758
1759 return false;
1760 }
1761
1762 return VisitExpr(E);
1763}
1764
Douglas Gregorab6677e2010-09-08 00:15:04 +00001765bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1766 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
Douglas Gregor40749ee2010-11-03 00:35:38 +00001767 if (Visit(TSInfo->getTypeLoc()))
1768 return true;
Douglas Gregorab6677e2010-09-08 00:15:04 +00001769
1770 return VisitExpr(E);
1771}
1772
1773bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1774 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1775 return Visit(TSInfo->getTypeLoc());
1776
1777 return false;
1778}
1779
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001780bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1781 // Visit placement arguments.
1782 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1783 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1784 return true;
1785
1786 // Visit the allocated type.
1787 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1788 if (Visit(TSInfo->getTypeLoc()))
1789 return true;
1790
1791 // Visit the array size, if any.
1792 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1793 return true;
1794
1795 // Visit the initializer or constructor arguments.
1796 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1797 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1798 return true;
1799
1800 return false;
1801}
1802
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001803bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1804 // Visit base expression.
1805 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1806 return true;
1807
1808 // Visit the nested-name-specifier.
1809 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1810 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1811 return true;
1812
1813 // Visit the scope type that looks disturbingly like the nested-name-specifier
1814 // but isn't.
1815 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1816 if (Visit(TSInfo->getTypeLoc()))
1817 return true;
1818
1819 // Visit the name of the type being destroyed.
1820 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1821 if (Visit(TSInfo->getTypeLoc()))
1822 return true;
1823
1824 return false;
1825}
1826
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001827bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1828 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1829}
1830
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001831bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001832 // Visit the nested-name-specifier.
1833 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1834 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1835 return true;
1836
1837 // Visit the declaration name.
1838 if (VisitDeclarationNameInfo(E->getNameInfo()))
1839 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001840
1841 // Visit the overloaded declaration reference.
1842 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1843 return true;
1844
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001845 // Visit the explicitly-specified template arguments.
1846 if (const ExplicitTemplateArgumentList *ArgList
1847 = E->getOptionalExplicitTemplateArgs()) {
1848 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1849 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1850 Arg != ArgEnd; ++Arg) {
1851 if (VisitTemplateArgumentLoc(*Arg))
1852 return true;
1853 }
1854 }
1855
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001856 return false;
1857}
1858
Douglas Gregorbfebed22010-09-03 17:24:10 +00001859bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1860 DependentScopeDeclRefExpr *E) {
1861 // Visit the nested-name-specifier.
1862 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1863 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1864 return true;
1865
1866 // Visit the declaration name.
1867 if (VisitDeclarationNameInfo(E->getNameInfo()))
1868 return true;
1869
1870 // Visit the explicitly-specified template arguments.
1871 if (const ExplicitTemplateArgumentList *ArgList
1872 = E->getOptionalExplicitTemplateArgs()) {
1873 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1874 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1875 Arg != ArgEnd; ++Arg) {
1876 if (VisitTemplateArgumentLoc(*Arg))
1877 return true;
1878 }
1879 }
1880
1881 return false;
1882}
1883
Douglas Gregorab6677e2010-09-08 00:15:04 +00001884bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1885 CXXUnresolvedConstructExpr *E) {
1886 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1887 if (Visit(TSInfo->getTypeLoc()))
1888 return true;
1889
1890 return VisitExpr(E);
1891}
1892
Douglas Gregor25d63622010-09-03 17:35:34 +00001893bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1894 CXXDependentScopeMemberExpr *E) {
1895 // Visit the base expression, if there is one.
1896 if (!E->isImplicitAccess() &&
1897 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1898 return true;
1899
1900 // Visit the nested-name-specifier.
1901 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1902 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1903 return true;
1904
1905 // Visit the declaration name.
1906 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1907 return true;
1908
1909 // Visit the explicitly-specified template arguments.
1910 if (const ExplicitTemplateArgumentList *ArgList
1911 = E->getOptionalExplicitTemplateArgs()) {
1912 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1913 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1914 Arg != ArgEnd; ++Arg) {
1915 if (VisitTemplateArgumentLoc(*Arg))
1916 return true;
1917 }
1918 }
1919
1920 return false;
1921}
1922
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001923bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1924 // Visit the base expression, if there is one.
1925 if (!E->isImplicitAccess() &&
1926 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1927 return true;
1928
1929 return VisitOverloadExpr(E);
1930}
Douglas Gregor25d63622010-09-03 17:35:34 +00001931
Douglas Gregorc2350e52010-03-08 16:40:19 +00001932bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00001933 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
1934 if (Visit(TSInfo->getTypeLoc()))
1935 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00001936
1937 return VisitExpr(E);
1938}
1939
Douglas Gregor81d34662010-04-20 15:39:42 +00001940bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
1941 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
1942}
1943
1944
Ted Kremenek09dfa372010-02-18 05:46:33 +00001945bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00001946 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
1947 i != e; ++i)
1948 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00001949 return true;
1950
1951 return false;
1952}
1953
Ted Kremenekc0e1d922010-11-11 08:05:18 +00001954//===----------------------------------------------------------------------===//
1955// Data-recursive visitor methods.
1956//===----------------------------------------------------------------------===//
1957
1958void CursorVisitor::EnqueueWorkList(VisitorWorkList &WL, Stmt *S) {
1959 CXCursor C = MakeCXCursor(S, StmtParent, TU);
1960 switch (S->getStmtClass()) {
1961 default: {
1962 unsigned size = WL.size();
1963 for (Stmt::child_iterator Child = S->child_begin(),
1964 ChildEnd = S->child_end(); Child != ChildEnd; ++Child) {
1965 if (Stmt *child = *Child) {
1966 WL.push_back(StmtVisit(child, C));
1967 }
1968 }
1969
1970 if (size == WL.size())
1971 return;
1972
1973 // Now reverse the entries we just added. This will match the DFS
1974 // ordering performed by the worklist.
1975 VisitorWorkList::iterator I = WL.begin() + size, E = WL.end();
1976 std::reverse(I, E);
1977 break;
1978 }
1979 case Stmt::ParenExprClass: {
1980 WL.push_back(StmtVisit(cast<ParenExpr>(S)->getSubExpr(), C));
1981 break;
1982 }
1983 case Stmt::BinaryOperatorClass: {
1984 BinaryOperator *B = cast<BinaryOperator>(S);
1985 WL.push_back(StmtVisit(B->getRHS(), C));
1986 WL.push_back(StmtVisit(B->getLHS(), C));
1987 break;
1988 }
1989 case Stmt::MemberExprClass: {
1990 MemberExpr *M = cast<MemberExpr>(S);
1991 WL.push_back(MemberExprParts(M, C));
1992 WL.push_back(StmtVisit(M->getBase(), C));
1993 break;
1994 }
1995 }
1996}
1997
1998bool CursorVisitor::IsInRegionOfInterest(CXCursor C) {
1999 if (RegionOfInterest.isValid()) {
2000 SourceRange Range = getRawCursorExtent(C);
2001 if (Range.isInvalid() || CompareRegionOfInterest(Range))
2002 return false;
2003 }
2004 return true;
2005}
2006
2007bool CursorVisitor::RunVisitorWorkList(VisitorWorkList &WL) {
2008 while (!WL.empty()) {
2009 // Dequeue the worklist item.
2010 VisitorJob LI = WL.back(); WL.pop_back();
2011
2012 // Set the Parent field, then back to its old value once we're done.
2013 SetParentRAII SetParent(Parent, StmtParent, LI.getParent());
2014
2015 switch (LI.getKind()) {
2016 case VisitorJob::StmtVisitKind: {
2017 // Update the current cursor.
2018 Stmt *S = cast<StmtVisit>(LI).get();
2019 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
2020
2021 switch (S->getStmtClass()) {
2022 default: {
2023 // Perform default visitation for other cases.
2024 if (Visit(Cursor))
2025 return true;
2026 continue;
2027 }
2028 case Stmt::CallExprClass:
2029 case Stmt::CXXMemberCallExprClass:
2030 case Stmt::ParenExprClass:
2031 case Stmt::MemberExprClass:
2032 case Stmt::BinaryOperatorClass: {
2033 if (!IsInRegionOfInterest(Cursor))
2034 continue;
2035 switch (Visitor(Cursor, Parent, ClientData)) {
2036 case CXChildVisit_Break:
2037 return true;
2038 case CXChildVisit_Continue:
2039 break;
2040 case CXChildVisit_Recurse:
2041 EnqueueWorkList(WL, S);
2042 break;
2043 }
2044 }
2045 }
2046 continue;
2047 }
2048 case VisitorJob::MemberExprPartsKind: {
2049 // Handle the other pieces in the MemberExpr besides the base.
2050 MemberExpr *M = cast<MemberExprParts>(LI).get();
2051
2052 // Visit the nested-name-specifier
2053 if (NestedNameSpecifier *Qualifier = M->getQualifier())
2054 if (VisitNestedNameSpecifier(Qualifier, M->getQualifierRange()))
2055 return true;
2056
2057 // Visit the declaration name.
2058 if (VisitDeclarationNameInfo(M->getMemberNameInfo()))
2059 return true;
2060
2061 // Visit the explicitly-specified template arguments, if any.
2062 if (M->hasExplicitTemplateArgs()) {
2063 for (const TemplateArgumentLoc *Arg = M->getTemplateArgs(),
2064 *ArgEnd = Arg + M->getNumTemplateArgs();
2065 Arg != ArgEnd; ++Arg) {
2066 if (VisitTemplateArgumentLoc(*Arg))
2067 return true;
2068 }
2069 }
2070 continue;
2071 }
2072 }
2073 }
2074 return false;
2075}
2076
2077bool CursorVisitor::VisitDataRecursive(Stmt *S) {
2078 VisitorWorkList WL;
2079 EnqueueWorkList(WL, S);
2080 return RunVisitorWorkList(WL);
2081}
2082
2083//===----------------------------------------------------------------------===//
2084// Misc. API hooks.
2085//===----------------------------------------------------------------------===//
2086
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002087static llvm::sys::Mutex EnableMultithreadingMutex;
2088static bool EnabledMultithreading;
2089
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002090extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002091CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2092 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002093 // Disable pretty stack trace functionality, which will otherwise be a very
2094 // poor citizen of the world and set up all sorts of signal handlers.
2095 llvm::DisablePrettyStackTrace = true;
2096
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002097 // We use crash recovery to make some of our APIs more reliable, implicitly
2098 // enable it.
2099 llvm::CrashRecoveryContext::Enable();
2100
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002101 // Enable support for multithreading in LLVM.
2102 {
2103 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2104 if (!EnabledMultithreading) {
2105 llvm::llvm_start_multithreaded();
2106 EnabledMultithreading = true;
2107 }
2108 }
2109
Douglas Gregora030b7c2010-01-22 20:35:53 +00002110 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002111 if (excludeDeclarationsFromPCH)
2112 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002113 if (displayDiagnostics)
2114 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002115 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002116}
2117
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002118void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002119 if (CIdx)
2120 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002121}
2122
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002123CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002124 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002125 if (!CIdx)
2126 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002127
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002128 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002129 FileSystemOptions FileSystemOpts;
2130 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002131
Douglas Gregor28019772010-04-05 23:52:57 +00002132 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002133 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002134 CXXIdx->getOnlyLocalDecls(),
2135 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002136}
2137
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002138unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002139 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002140 CXTranslationUnit_CacheCompletionResults |
2141 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002142}
2143
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002144CXTranslationUnit
2145clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2146 const char *source_filename,
2147 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002148 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002149 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002150 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002151 return clang_parseTranslationUnit(CIdx, source_filename,
2152 command_line_args, num_command_line_args,
2153 unsaved_files, num_unsaved_files,
2154 CXTranslationUnit_DetailedPreprocessingRecord);
2155}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002156
2157struct ParseTranslationUnitInfo {
2158 CXIndex CIdx;
2159 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002160 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002161 int num_command_line_args;
2162 struct CXUnsavedFile *unsaved_files;
2163 unsigned num_unsaved_files;
2164 unsigned options;
2165 CXTranslationUnit result;
2166};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002167static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002168 ParseTranslationUnitInfo *PTUI =
2169 static_cast<ParseTranslationUnitInfo*>(UserData);
2170 CXIndex CIdx = PTUI->CIdx;
2171 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002172 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002173 int num_command_line_args = PTUI->num_command_line_args;
2174 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2175 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2176 unsigned options = PTUI->options;
2177 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002178
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002179 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002180 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002181
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002182 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2183
Douglas Gregor44c181a2010-07-23 00:33:23 +00002184 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002185 bool CompleteTranslationUnit
2186 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002187 bool CacheCodeCompetionResults
2188 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002189 bool CXXPrecompilePreamble
2190 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2191 bool CXXChainedPCH
2192 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002193
Douglas Gregor5352ac02010-01-28 00:27:43 +00002194 // Configure the diagnostics.
2195 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002196 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2197 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002198
Douglas Gregor4db64a42010-01-23 00:14:00 +00002199 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2200 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002201 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002202 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002203 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002204 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2205 Buffer));
2206 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002207
Douglas Gregorb10daed2010-10-11 16:52:23 +00002208 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002209
Ted Kremenek139ba862009-10-22 00:03:57 +00002210 // The 'source_filename' argument is optional. If the caller does not
2211 // specify it then it is assumed that the source file is specified
2212 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002213 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002214 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002215
2216 // Since the Clang C library is primarily used by batch tools dealing with
2217 // (often very broken) source code, where spell-checking can have a
2218 // significant negative impact on performance (particularly when
2219 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002220 // Only do this if we haven't found a spell-checking-related argument.
2221 bool FoundSpellCheckingArgument = false;
2222 for (int I = 0; I != num_command_line_args; ++I) {
2223 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2224 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2225 FoundSpellCheckingArgument = true;
2226 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002227 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002228 }
2229 if (!FoundSpellCheckingArgument)
2230 Args.push_back("-fno-spell-checking");
2231
2232 Args.insert(Args.end(), command_line_args,
2233 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002234
Douglas Gregor44c181a2010-07-23 00:33:23 +00002235 // Do we need the detailed preprocessing record?
2236 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002237 Args.push_back("-Xclang");
2238 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002239 }
2240
Douglas Gregorb10daed2010-10-11 16:52:23 +00002241 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002242 llvm::OwningPtr<ASTUnit> Unit(
2243 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2244 Diags,
2245 CXXIdx->getClangResourcesPath(),
2246 CXXIdx->getOnlyLocalDecls(),
Douglas Gregore47be3e2010-11-11 00:39:14 +00002247 /*CaptureDiagnostics=*/true,
Douglas Gregorb10daed2010-10-11 16:52:23 +00002248 RemappedFiles.data(),
2249 RemappedFiles.size(),
Douglas Gregorb10daed2010-10-11 16:52:23 +00002250 PrecompilePreamble,
2251 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002252 CacheCodeCompetionResults,
2253 CXXPrecompilePreamble,
2254 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002255
Douglas Gregorb10daed2010-10-11 16:52:23 +00002256 if (NumErrors != Diags->getNumErrors()) {
2257 // Make sure to check that 'Unit' is non-NULL.
2258 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2259 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2260 DEnd = Unit->stored_diag_end();
2261 D != DEnd; ++D) {
2262 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2263 CXString Msg = clang_formatDiagnostic(&Diag,
2264 clang_defaultDiagnosticDisplayOptions());
2265 fprintf(stderr, "%s\n", clang_getCString(Msg));
2266 clang_disposeString(Msg);
2267 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002268#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002269 // On Windows, force a flush, since there may be multiple copies of
2270 // stderr and stdout in the file system, all with different buffers
2271 // but writing to the same device.
2272 fflush(stderr);
2273#endif
2274 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002275 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002276
Douglas Gregorb10daed2010-10-11 16:52:23 +00002277 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002278}
2279CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2280 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002281 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002282 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002283 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002284 unsigned num_unsaved_files,
2285 unsigned options) {
2286 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002287 num_command_line_args, unsaved_files,
2288 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002289 llvm::CrashRecoveryContext CRC;
2290
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002291 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002292 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2293 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2294 fprintf(stderr, " 'command_line_args' : [");
2295 for (int i = 0; i != num_command_line_args; ++i) {
2296 if (i)
2297 fprintf(stderr, ", ");
2298 fprintf(stderr, "'%s'", command_line_args[i]);
2299 }
2300 fprintf(stderr, "],\n");
2301 fprintf(stderr, " 'unsaved_files' : [");
2302 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2303 if (i)
2304 fprintf(stderr, ", ");
2305 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2306 unsaved_files[i].Length);
2307 }
2308 fprintf(stderr, "],\n");
2309 fprintf(stderr, " 'options' : %d,\n", options);
2310 fprintf(stderr, "}\n");
2311
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002312 return 0;
2313 }
2314
2315 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002316}
2317
Douglas Gregor19998442010-08-13 15:35:05 +00002318unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2319 return CXSaveTranslationUnit_None;
2320}
2321
2322int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2323 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002324 if (!TU)
2325 return 1;
2326
2327 return static_cast<ASTUnit *>(TU)->Save(FileName);
2328}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002329
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002330void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002331 if (CTUnit) {
2332 // If the translation unit has been marked as unsafe to free, just discard
2333 // it.
2334 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2335 return;
2336
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002337 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002338 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002339}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002340
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002341unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2342 return CXReparse_None;
2343}
2344
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002345struct ReparseTranslationUnitInfo {
2346 CXTranslationUnit TU;
2347 unsigned num_unsaved_files;
2348 struct CXUnsavedFile *unsaved_files;
2349 unsigned options;
2350 int result;
2351};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002352
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002353static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002354 ReparseTranslationUnitInfo *RTUI =
2355 static_cast<ReparseTranslationUnitInfo*>(UserData);
2356 CXTranslationUnit TU = RTUI->TU;
2357 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2358 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2359 unsigned options = RTUI->options;
2360 (void) options;
2361 RTUI->result = 1;
2362
Douglas Gregorabc563f2010-07-19 21:46:24 +00002363 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002364 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002365
2366 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2367 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002368
2369 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2370 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2371 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2372 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002373 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002374 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2375 Buffer));
2376 }
2377
Douglas Gregor593b0c12010-09-23 18:47:53 +00002378 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2379 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002380}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002381
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002382int clang_reparseTranslationUnit(CXTranslationUnit TU,
2383 unsigned num_unsaved_files,
2384 struct CXUnsavedFile *unsaved_files,
2385 unsigned options) {
2386 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2387 options, 0 };
2388 llvm::CrashRecoveryContext CRC;
2389
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002390 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002391 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002392 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2393 return 1;
2394 }
2395
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002396
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002397 return RTUI.result;
2398}
2399
Douglas Gregordf95a132010-08-09 20:45:32 +00002400
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002401CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002402 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002403 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002404
Steve Naroff77accc12009-09-03 18:19:54 +00002405 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002406 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002407}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002408
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002409CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002410 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002411 return Result;
2412}
2413
Ted Kremenekfb480492010-01-13 21:46:36 +00002414} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002415
Ted Kremenekfb480492010-01-13 21:46:36 +00002416//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002417// CXSourceLocation and CXSourceRange Operations.
2418//===----------------------------------------------------------------------===//
2419
Douglas Gregorb9790342010-01-22 21:44:22 +00002420extern "C" {
2421CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002422 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002423 return Result;
2424}
2425
2426unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002427 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2428 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2429 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002430}
2431
2432CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2433 CXFile file,
2434 unsigned line,
2435 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002436 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002437 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002438
Douglas Gregorb9790342010-01-22 21:44:22 +00002439 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2440 SourceLocation SLoc
2441 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002442 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002443 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002444 if (SLoc.isInvalid()) return clang_getNullLocation();
2445
2446 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2447}
2448
2449CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2450 CXFile file,
2451 unsigned offset) {
2452 if (!tu || !file)
2453 return clang_getNullLocation();
2454
2455 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2456 SourceLocation Start
2457 = CXXUnit->getSourceManager().getLocation(
2458 static_cast<const FileEntry *>(file),
2459 1, 1);
2460 if (Start.isInvalid()) return clang_getNullLocation();
2461
2462 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2463
2464 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002465
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002466 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002467}
2468
Douglas Gregor5352ac02010-01-28 00:27:43 +00002469CXSourceRange clang_getNullRange() {
2470 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2471 return Result;
2472}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002473
Douglas Gregor5352ac02010-01-28 00:27:43 +00002474CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2475 if (begin.ptr_data[0] != end.ptr_data[0] ||
2476 begin.ptr_data[1] != end.ptr_data[1])
2477 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002478
2479 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002480 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002481 return Result;
2482}
2483
Douglas Gregor46766dc2010-01-26 19:19:08 +00002484void clang_getInstantiationLocation(CXSourceLocation location,
2485 CXFile *file,
2486 unsigned *line,
2487 unsigned *column,
2488 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002489 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2490
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002491 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002492 if (file)
2493 *file = 0;
2494 if (line)
2495 *line = 0;
2496 if (column)
2497 *column = 0;
2498 if (offset)
2499 *offset = 0;
2500 return;
2501 }
2502
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002503 const SourceManager &SM =
2504 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002505 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002506
2507 if (file)
2508 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2509 if (line)
2510 *line = SM.getInstantiationLineNumber(InstLoc);
2511 if (column)
2512 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002513 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002514 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002515}
2516
Douglas Gregora9b06d42010-11-09 06:24:54 +00002517void clang_getSpellingLocation(CXSourceLocation location,
2518 CXFile *file,
2519 unsigned *line,
2520 unsigned *column,
2521 unsigned *offset) {
2522 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2523
2524 if (!location.ptr_data[0] || Loc.isInvalid()) {
2525 if (file)
2526 *file = 0;
2527 if (line)
2528 *line = 0;
2529 if (column)
2530 *column = 0;
2531 if (offset)
2532 *offset = 0;
2533 return;
2534 }
2535
2536 const SourceManager &SM =
2537 *static_cast<const SourceManager*>(location.ptr_data[0]);
2538 SourceLocation SpellLoc = Loc;
2539 if (SpellLoc.isMacroID()) {
2540 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2541 if (SimpleSpellingLoc.isFileID() &&
2542 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2543 SpellLoc = SimpleSpellingLoc;
2544 else
2545 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2546 }
2547
2548 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2549 FileID FID = LocInfo.first;
2550 unsigned FileOffset = LocInfo.second;
2551
2552 if (file)
2553 *file = (void *)SM.getFileEntryForID(FID);
2554 if (line)
2555 *line = SM.getLineNumber(FID, FileOffset);
2556 if (column)
2557 *column = SM.getColumnNumber(FID, FileOffset);
2558 if (offset)
2559 *offset = FileOffset;
2560}
2561
Douglas Gregor1db19de2010-01-19 21:36:55 +00002562CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002563 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002564 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002565 return Result;
2566}
2567
2568CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002569 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002570 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002571 return Result;
2572}
2573
Douglas Gregorb9790342010-01-22 21:44:22 +00002574} // end: extern "C"
2575
Douglas Gregor1db19de2010-01-19 21:36:55 +00002576//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002577// CXFile Operations.
2578//===----------------------------------------------------------------------===//
2579
2580extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002581CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002582 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002583 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002584
Steve Naroff88145032009-10-27 14:35:18 +00002585 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002586 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002587}
2588
2589time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002590 if (!SFile)
2591 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002592
Steve Naroff88145032009-10-27 14:35:18 +00002593 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2594 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002595}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002596
Douglas Gregorb9790342010-01-22 21:44:22 +00002597CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2598 if (!tu)
2599 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002600
Douglas Gregorb9790342010-01-22 21:44:22 +00002601 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002602
Douglas Gregorb9790342010-01-22 21:44:22 +00002603 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002604 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2605 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002606 return const_cast<FileEntry *>(File);
2607}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002608
Ted Kremenekfb480492010-01-13 21:46:36 +00002609} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002610
Ted Kremenekfb480492010-01-13 21:46:36 +00002611//===----------------------------------------------------------------------===//
2612// CXCursor Operations.
2613//===----------------------------------------------------------------------===//
2614
Ted Kremenekfb480492010-01-13 21:46:36 +00002615static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002616 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2617 return getDeclFromExpr(CE->getSubExpr());
2618
Ted Kremenekfb480492010-01-13 21:46:36 +00002619 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2620 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002621 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2622 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002623 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2624 return ME->getMemberDecl();
2625 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2626 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002627 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2628 return PRE->getProperty();
2629
Ted Kremenekfb480492010-01-13 21:46:36 +00002630 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2631 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002632 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2633 if (!CE->isElidable())
2634 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002635 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2636 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002637
Douglas Gregordb1314e2010-10-01 21:11:22 +00002638 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2639 return PE->getProtocol();
2640
Ted Kremenekfb480492010-01-13 21:46:36 +00002641 return 0;
2642}
2643
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002644static SourceLocation getLocationFromExpr(Expr *E) {
2645 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2646 return /*FIXME:*/Msg->getLeftLoc();
2647 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2648 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002649 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2650 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002651 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2652 return Member->getMemberLoc();
2653 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2654 return Ivar->getLocation();
2655 return E->getLocStart();
2656}
2657
Ted Kremenekfb480492010-01-13 21:46:36 +00002658extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002659
2660unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002661 CXCursorVisitor visitor,
2662 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002663 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002664
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002665 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2666 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002667 return CursorVis.VisitChildren(parent);
2668}
2669
David Chisnall3387c652010-11-03 14:12:26 +00002670#ifndef __has_feature
2671#define __has_feature(x) 0
2672#endif
2673#if __has_feature(blocks)
2674typedef enum CXChildVisitResult
2675 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2676
2677static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2678 CXClientData client_data) {
2679 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2680 return block(cursor, parent);
2681}
2682#else
2683// If we are compiled with a compiler that doesn't have native blocks support,
2684// define and call the block manually, so the
2685typedef struct _CXChildVisitResult
2686{
2687 void *isa;
2688 int flags;
2689 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002690 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2691 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002692} *CXCursorVisitorBlock;
2693
2694static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2695 CXClientData client_data) {
2696 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2697 return block->invoke(block, cursor, parent);
2698}
2699#endif
2700
2701
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002702unsigned clang_visitChildrenWithBlock(CXCursor parent,
2703 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002704 return clang_visitChildren(parent, visitWithBlock, block);
2705}
2706
Douglas Gregor78205d42010-01-20 21:45:58 +00002707static CXString getDeclSpelling(Decl *D) {
2708 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2709 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002710 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002711
Douglas Gregor78205d42010-01-20 21:45:58 +00002712 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002713 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002714
Douglas Gregor78205d42010-01-20 21:45:58 +00002715 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2716 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2717 // and returns different names. NamedDecl returns the class name and
2718 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002719 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002720
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002721 if (isa<UsingDirectiveDecl>(D))
2722 return createCXString("");
2723
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002724 llvm::SmallString<1024> S;
2725 llvm::raw_svector_ostream os(S);
2726 ND->printName(os);
2727
2728 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002729}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002730
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002731CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002732 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002733 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002734
Steve Narofff334b4e2009-09-02 18:26:48 +00002735 if (clang_isReference(C.kind)) {
2736 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002737 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002738 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002739 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002740 }
2741 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002742 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002743 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002744 }
2745 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002746 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002747 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002748 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002749 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002750 case CXCursor_CXXBaseSpecifier: {
2751 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2752 return createCXString(B->getType().getAsString());
2753 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002754 case CXCursor_TypeRef: {
2755 TypeDecl *Type = getCursorTypeRef(C).first;
2756 assert(Type && "Missing type decl");
2757
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002758 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2759 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002760 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002761 case CXCursor_TemplateRef: {
2762 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002763 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002764
2765 return createCXString(Template->getNameAsString());
2766 }
Douglas Gregor69319002010-08-31 23:48:11 +00002767
2768 case CXCursor_NamespaceRef: {
2769 NamedDecl *NS = getCursorNamespaceRef(C).first;
2770 assert(NS && "Missing namespace decl");
2771
2772 return createCXString(NS->getNameAsString());
2773 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002774
Douglas Gregora67e03f2010-09-09 21:42:20 +00002775 case CXCursor_MemberRef: {
2776 FieldDecl *Field = getCursorMemberRef(C).first;
2777 assert(Field && "Missing member decl");
2778
2779 return createCXString(Field->getNameAsString());
2780 }
2781
Douglas Gregor36897b02010-09-10 00:22:18 +00002782 case CXCursor_LabelRef: {
2783 LabelStmt *Label = getCursorLabelRef(C).first;
2784 assert(Label && "Missing label");
2785
2786 return createCXString(Label->getID()->getName());
2787 }
2788
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002789 case CXCursor_OverloadedDeclRef: {
2790 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2791 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2792 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2793 return createCXString(ND->getNameAsString());
2794 return createCXString("");
2795 }
2796 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2797 return createCXString(E->getName().getAsString());
2798 OverloadedTemplateStorage *Ovl
2799 = Storage.get<OverloadedTemplateStorage*>();
2800 if (Ovl->size() == 0)
2801 return createCXString("");
2802 return createCXString((*Ovl->begin())->getNameAsString());
2803 }
2804
Daniel Dunbaracca7252009-11-30 20:42:49 +00002805 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002806 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002807 }
2808 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002809
2810 if (clang_isExpression(C.kind)) {
2811 Decl *D = getDeclFromExpr(getCursorExpr(C));
2812 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002813 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002814 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002815 }
2816
Douglas Gregor36897b02010-09-10 00:22:18 +00002817 if (clang_isStatement(C.kind)) {
2818 Stmt *S = getCursorStmt(C);
2819 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2820 return createCXString(Label->getID()->getName());
2821
2822 return createCXString("");
2823 }
2824
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002825 if (C.kind == CXCursor_MacroInstantiation)
2826 return createCXString(getCursorMacroInstantiation(C)->getName()
2827 ->getNameStart());
2828
Douglas Gregor572feb22010-03-18 18:04:21 +00002829 if (C.kind == CXCursor_MacroDefinition)
2830 return createCXString(getCursorMacroDefinition(C)->getName()
2831 ->getNameStart());
2832
Douglas Gregorecdcb882010-10-20 22:00:55 +00002833 if (C.kind == CXCursor_InclusionDirective)
2834 return createCXString(getCursorInclusionDirective(C)->getFileName());
2835
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002836 if (clang_isDeclaration(C.kind))
2837 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002838
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002839 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002840}
2841
Douglas Gregor358559d2010-10-02 22:49:11 +00002842CXString clang_getCursorDisplayName(CXCursor C) {
2843 if (!clang_isDeclaration(C.kind))
2844 return clang_getCursorSpelling(C);
2845
2846 Decl *D = getCursorDecl(C);
2847 if (!D)
2848 return createCXString("");
2849
2850 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2851 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2852 D = FunTmpl->getTemplatedDecl();
2853
2854 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2855 llvm::SmallString<64> Str;
2856 llvm::raw_svector_ostream OS(Str);
2857 OS << Function->getNameAsString();
2858 if (Function->getPrimaryTemplate())
2859 OS << "<>";
2860 OS << "(";
2861 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2862 if (I)
2863 OS << ", ";
2864 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2865 }
2866
2867 if (Function->isVariadic()) {
2868 if (Function->getNumParams())
2869 OS << ", ";
2870 OS << "...";
2871 }
2872 OS << ")";
2873 return createCXString(OS.str());
2874 }
2875
2876 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2877 llvm::SmallString<64> Str;
2878 llvm::raw_svector_ostream OS(Str);
2879 OS << ClassTemplate->getNameAsString();
2880 OS << "<";
2881 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2882 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2883 if (I)
2884 OS << ", ";
2885
2886 NamedDecl *Param = Params->getParam(I);
2887 if (Param->getIdentifier()) {
2888 OS << Param->getIdentifier()->getName();
2889 continue;
2890 }
2891
2892 // There is no parameter name, which makes this tricky. Try to come up
2893 // with something useful that isn't too long.
2894 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2895 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2896 else if (NonTypeTemplateParmDecl *NTTP
2897 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2898 OS << NTTP->getType().getAsString(Policy);
2899 else
2900 OS << "template<...> class";
2901 }
2902
2903 OS << ">";
2904 return createCXString(OS.str());
2905 }
2906
2907 if (ClassTemplateSpecializationDecl *ClassSpec
2908 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2909 // If the type was explicitly written, use that.
2910 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2911 return createCXString(TSInfo->getType().getAsString(Policy));
2912
2913 llvm::SmallString<64> Str;
2914 llvm::raw_svector_ostream OS(Str);
2915 OS << ClassSpec->getNameAsString();
2916 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002917 ClassSpec->getTemplateArgs().data(),
2918 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002919 Policy);
2920 return createCXString(OS.str());
2921 }
2922
2923 return clang_getCursorSpelling(C);
2924}
2925
Ted Kremeneke68fff62010-02-17 00:41:32 +00002926CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002927 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002928 case CXCursor_FunctionDecl:
2929 return createCXString("FunctionDecl");
2930 case CXCursor_TypedefDecl:
2931 return createCXString("TypedefDecl");
2932 case CXCursor_EnumDecl:
2933 return createCXString("EnumDecl");
2934 case CXCursor_EnumConstantDecl:
2935 return createCXString("EnumConstantDecl");
2936 case CXCursor_StructDecl:
2937 return createCXString("StructDecl");
2938 case CXCursor_UnionDecl:
2939 return createCXString("UnionDecl");
2940 case CXCursor_ClassDecl:
2941 return createCXString("ClassDecl");
2942 case CXCursor_FieldDecl:
2943 return createCXString("FieldDecl");
2944 case CXCursor_VarDecl:
2945 return createCXString("VarDecl");
2946 case CXCursor_ParmDecl:
2947 return createCXString("ParmDecl");
2948 case CXCursor_ObjCInterfaceDecl:
2949 return createCXString("ObjCInterfaceDecl");
2950 case CXCursor_ObjCCategoryDecl:
2951 return createCXString("ObjCCategoryDecl");
2952 case CXCursor_ObjCProtocolDecl:
2953 return createCXString("ObjCProtocolDecl");
2954 case CXCursor_ObjCPropertyDecl:
2955 return createCXString("ObjCPropertyDecl");
2956 case CXCursor_ObjCIvarDecl:
2957 return createCXString("ObjCIvarDecl");
2958 case CXCursor_ObjCInstanceMethodDecl:
2959 return createCXString("ObjCInstanceMethodDecl");
2960 case CXCursor_ObjCClassMethodDecl:
2961 return createCXString("ObjCClassMethodDecl");
2962 case CXCursor_ObjCImplementationDecl:
2963 return createCXString("ObjCImplementationDecl");
2964 case CXCursor_ObjCCategoryImplDecl:
2965 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002966 case CXCursor_CXXMethod:
2967 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002968 case CXCursor_UnexposedDecl:
2969 return createCXString("UnexposedDecl");
2970 case CXCursor_ObjCSuperClassRef:
2971 return createCXString("ObjCSuperClassRef");
2972 case CXCursor_ObjCProtocolRef:
2973 return createCXString("ObjCProtocolRef");
2974 case CXCursor_ObjCClassRef:
2975 return createCXString("ObjCClassRef");
2976 case CXCursor_TypeRef:
2977 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002978 case CXCursor_TemplateRef:
2979 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002980 case CXCursor_NamespaceRef:
2981 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002982 case CXCursor_MemberRef:
2983 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002984 case CXCursor_LabelRef:
2985 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002986 case CXCursor_OverloadedDeclRef:
2987 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002988 case CXCursor_UnexposedExpr:
2989 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002990 case CXCursor_BlockExpr:
2991 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002992 case CXCursor_DeclRefExpr:
2993 return createCXString("DeclRefExpr");
2994 case CXCursor_MemberRefExpr:
2995 return createCXString("MemberRefExpr");
2996 case CXCursor_CallExpr:
2997 return createCXString("CallExpr");
2998 case CXCursor_ObjCMessageExpr:
2999 return createCXString("ObjCMessageExpr");
3000 case CXCursor_UnexposedStmt:
3001 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00003002 case CXCursor_LabelStmt:
3003 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003004 case CXCursor_InvalidFile:
3005 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00003006 case CXCursor_InvalidCode:
3007 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003008 case CXCursor_NoDeclFound:
3009 return createCXString("NoDeclFound");
3010 case CXCursor_NotImplemented:
3011 return createCXString("NotImplemented");
3012 case CXCursor_TranslationUnit:
3013 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00003014 case CXCursor_UnexposedAttr:
3015 return createCXString("UnexposedAttr");
3016 case CXCursor_IBActionAttr:
3017 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003018 case CXCursor_IBOutletAttr:
3019 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00003020 case CXCursor_IBOutletCollectionAttr:
3021 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003022 case CXCursor_PreprocessingDirective:
3023 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00003024 case CXCursor_MacroDefinition:
3025 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00003026 case CXCursor_MacroInstantiation:
3027 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00003028 case CXCursor_InclusionDirective:
3029 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00003030 case CXCursor_Namespace:
3031 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00003032 case CXCursor_LinkageSpec:
3033 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00003034 case CXCursor_CXXBaseSpecifier:
3035 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00003036 case CXCursor_Constructor:
3037 return createCXString("CXXConstructor");
3038 case CXCursor_Destructor:
3039 return createCXString("CXXDestructor");
3040 case CXCursor_ConversionFunction:
3041 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00003042 case CXCursor_TemplateTypeParameter:
3043 return createCXString("TemplateTypeParameter");
3044 case CXCursor_NonTypeTemplateParameter:
3045 return createCXString("NonTypeTemplateParameter");
3046 case CXCursor_TemplateTemplateParameter:
3047 return createCXString("TemplateTemplateParameter");
3048 case CXCursor_FunctionTemplate:
3049 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00003050 case CXCursor_ClassTemplate:
3051 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00003052 case CXCursor_ClassTemplatePartialSpecialization:
3053 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00003054 case CXCursor_NamespaceAlias:
3055 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00003056 case CXCursor_UsingDirective:
3057 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003058 case CXCursor_UsingDeclaration:
3059 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003060 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003061
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003062 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003063 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003064}
Steve Naroff89922f82009-08-31 00:59:03 +00003065
Ted Kremeneke68fff62010-02-17 00:41:32 +00003066enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3067 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003068 CXClientData client_data) {
3069 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003070
3071 // If our current best cursor is the construction of a temporary object,
3072 // don't replace that cursor with a type reference, because we want
3073 // clang_getCursor() to point at the constructor.
3074 if (clang_isExpression(BestCursor->kind) &&
3075 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3076 cursor.kind == CXCursor_TypeRef)
3077 return CXChildVisit_Recurse;
3078
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003079 *BestCursor = cursor;
3080 return CXChildVisit_Recurse;
3081}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003082
Douglas Gregorb9790342010-01-22 21:44:22 +00003083CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3084 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003085 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003086
Douglas Gregorb9790342010-01-22 21:44:22 +00003087 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003088 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3089
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003090 // Translate the given source location to make it point at the beginning of
3091 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003092 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003093
3094 // Guard against an invalid SourceLocation, or we may assert in one
3095 // of the following calls.
3096 if (SLoc.isInvalid())
3097 return clang_getNullCursor();
3098
Douglas Gregor40749ee2010-11-03 00:35:38 +00003099 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003100 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3101 CXXUnit->getASTContext().getLangOptions());
3102
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003103 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3104 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003105 // FIXME: Would be great to have a "hint" cursor, then walk from that
3106 // hint cursor upward until we find a cursor whose source range encloses
3107 // the region of interest, rather than starting from the translation unit.
3108 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003109 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003110 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003111 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003112 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003113
3114 if (Logging) {
3115 CXFile SearchFile;
3116 unsigned SearchLine, SearchColumn;
3117 CXFile ResultFile;
3118 unsigned ResultLine, ResultColumn;
3119 CXString SearchFileName, ResultFileName, KindSpelling;
3120 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3121
3122 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3123 0);
3124 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3125 &ResultColumn, 0);
3126 SearchFileName = clang_getFileName(SearchFile);
3127 ResultFileName = clang_getFileName(ResultFile);
3128 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3129 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3130 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3131 clang_getCString(KindSpelling),
3132 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3133 clang_disposeString(SearchFileName);
3134 clang_disposeString(ResultFileName);
3135 clang_disposeString(KindSpelling);
3136 }
3137
Ted Kremeneke68fff62010-02-17 00:41:32 +00003138 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003139}
3140
Ted Kremenek73885552009-11-17 19:28:59 +00003141CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003142 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003143}
3144
3145unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003146 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003147}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003148
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003149unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003150 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3151}
3152
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003153unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003154 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3155}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003156
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003157unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003158 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3159}
3160
Douglas Gregor97b98722010-01-19 23:20:36 +00003161unsigned clang_isExpression(enum CXCursorKind K) {
3162 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3163}
3164
3165unsigned clang_isStatement(enum CXCursorKind K) {
3166 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3167}
3168
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003169unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3170 return K == CXCursor_TranslationUnit;
3171}
3172
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003173unsigned clang_isPreprocessing(enum CXCursorKind K) {
3174 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3175}
3176
Ted Kremenekad6eff62010-03-08 21:17:29 +00003177unsigned clang_isUnexposed(enum CXCursorKind K) {
3178 switch (K) {
3179 case CXCursor_UnexposedDecl:
3180 case CXCursor_UnexposedExpr:
3181 case CXCursor_UnexposedStmt:
3182 case CXCursor_UnexposedAttr:
3183 return true;
3184 default:
3185 return false;
3186 }
3187}
3188
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003189CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003190 return C.kind;
3191}
3192
Douglas Gregor98258af2010-01-18 22:46:11 +00003193CXSourceLocation clang_getCursorLocation(CXCursor C) {
3194 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003195 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003196 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003197 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3198 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003199 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003200 }
3201
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003202 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003203 std::pair<ObjCProtocolDecl *, SourceLocation> P
3204 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003205 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003206 }
3207
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003208 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003209 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3210 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003211 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003212 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003213
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003214 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003215 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003216 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003217 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003218
3219 case CXCursor_TemplateRef: {
3220 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3221 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3222 }
3223
Douglas Gregor69319002010-08-31 23:48:11 +00003224 case CXCursor_NamespaceRef: {
3225 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3226 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3227 }
3228
Douglas Gregora67e03f2010-09-09 21:42:20 +00003229 case CXCursor_MemberRef: {
3230 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3231 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3232 }
3233
Ted Kremenek3064ef92010-08-27 21:34:58 +00003234 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003235 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3236 if (!BaseSpec)
3237 return clang_getNullLocation();
3238
3239 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3240 return cxloc::translateSourceLocation(getCursorContext(C),
3241 TSInfo->getTypeLoc().getBeginLoc());
3242
3243 return cxloc::translateSourceLocation(getCursorContext(C),
3244 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003245 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003246
Douglas Gregor36897b02010-09-10 00:22:18 +00003247 case CXCursor_LabelRef: {
3248 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3249 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3250 }
3251
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003252 case CXCursor_OverloadedDeclRef:
3253 return cxloc::translateSourceLocation(getCursorContext(C),
3254 getCursorOverloadedDeclRef(C).second);
3255
Douglas Gregorf46034a2010-01-18 23:41:10 +00003256 default:
3257 // FIXME: Need a way to enumerate all non-reference cases.
3258 llvm_unreachable("Missed a reference kind");
3259 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003260 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003261
3262 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003263 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003264 getLocationFromExpr(getCursorExpr(C)));
3265
Douglas Gregor36897b02010-09-10 00:22:18 +00003266 if (clang_isStatement(C.kind))
3267 return cxloc::translateSourceLocation(getCursorContext(C),
3268 getCursorStmt(C)->getLocStart());
3269
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003270 if (C.kind == CXCursor_PreprocessingDirective) {
3271 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3272 return cxloc::translateSourceLocation(getCursorContext(C), L);
3273 }
Douglas Gregor48072312010-03-18 15:23:44 +00003274
3275 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003276 SourceLocation L
3277 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003278 return cxloc::translateSourceLocation(getCursorContext(C), L);
3279 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003280
3281 if (C.kind == CXCursor_MacroDefinition) {
3282 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3283 return cxloc::translateSourceLocation(getCursorContext(C), L);
3284 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003285
3286 if (C.kind == CXCursor_InclusionDirective) {
3287 SourceLocation L
3288 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3289 return cxloc::translateSourceLocation(getCursorContext(C), L);
3290 }
3291
Ted Kremenek9a700d22010-05-12 06:16:13 +00003292 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003293 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003294
Douglas Gregorf46034a2010-01-18 23:41:10 +00003295 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003296 SourceLocation Loc = D->getLocation();
3297 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3298 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003299 // FIXME: Multiple variables declared in a single declaration
3300 // currently lack the information needed to correctly determine their
3301 // ranges when accounting for the type-specifier. We use context
3302 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3303 // and if so, whether it is the first decl.
3304 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3305 if (!cxcursor::isFirstInDeclGroup(C))
3306 Loc = VD->getLocation();
3307 }
3308
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003309 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003310}
Douglas Gregora7bde202010-01-19 00:34:46 +00003311
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003312} // end extern "C"
3313
3314static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003315 if (clang_isReference(C.kind)) {
3316 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003317 case CXCursor_ObjCSuperClassRef:
3318 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003319
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003320 case CXCursor_ObjCProtocolRef:
3321 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003322
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003323 case CXCursor_ObjCClassRef:
3324 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003325
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003326 case CXCursor_TypeRef:
3327 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003328
3329 case CXCursor_TemplateRef:
3330 return getCursorTemplateRef(C).second;
3331
Douglas Gregor69319002010-08-31 23:48:11 +00003332 case CXCursor_NamespaceRef:
3333 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003334
3335 case CXCursor_MemberRef:
3336 return getCursorMemberRef(C).second;
3337
Ted Kremenek3064ef92010-08-27 21:34:58 +00003338 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003339 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003340
Douglas Gregor36897b02010-09-10 00:22:18 +00003341 case CXCursor_LabelRef:
3342 return getCursorLabelRef(C).second;
3343
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003344 case CXCursor_OverloadedDeclRef:
3345 return getCursorOverloadedDeclRef(C).second;
3346
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003347 default:
3348 // FIXME: Need a way to enumerate all non-reference cases.
3349 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003350 }
3351 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003352
3353 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003354 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003355
3356 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003357 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003358
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003359 if (C.kind == CXCursor_PreprocessingDirective)
3360 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003361
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003362 if (C.kind == CXCursor_MacroInstantiation)
3363 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003364
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003365 if (C.kind == CXCursor_MacroDefinition)
3366 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003367
3368 if (C.kind == CXCursor_InclusionDirective)
3369 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3370
Ted Kremenek007a7c92010-11-01 23:26:51 +00003371 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3372 Decl *D = cxcursor::getCursorDecl(C);
3373 SourceRange R = D->getSourceRange();
3374 // FIXME: Multiple variables declared in a single declaration
3375 // currently lack the information needed to correctly determine their
3376 // ranges when accounting for the type-specifier. We use context
3377 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3378 // and if so, whether it is the first decl.
3379 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3380 if (!cxcursor::isFirstInDeclGroup(C))
3381 R.setBegin(VD->getLocation());
3382 }
3383 return R;
3384 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003385 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003386
3387extern "C" {
3388
3389CXSourceRange clang_getCursorExtent(CXCursor C) {
3390 SourceRange R = getRawCursorExtent(C);
3391 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003392 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003393
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003394 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003395}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003396
3397CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003398 if (clang_isInvalid(C.kind))
3399 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003400
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003401 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003402 if (clang_isDeclaration(C.kind)) {
3403 Decl *D = getCursorDecl(C);
3404 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3405 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3406 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3407 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3408 if (ObjCForwardProtocolDecl *Protocols
3409 = dyn_cast<ObjCForwardProtocolDecl>(D))
3410 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3411
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003412 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003413 }
3414
Douglas Gregor97b98722010-01-19 23:20:36 +00003415 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003416 Expr *E = getCursorExpr(C);
3417 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003418 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003419 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003420
3421 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3422 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3423
Douglas Gregor97b98722010-01-19 23:20:36 +00003424 return clang_getNullCursor();
3425 }
3426
Douglas Gregor36897b02010-09-10 00:22:18 +00003427 if (clang_isStatement(C.kind)) {
3428 Stmt *S = getCursorStmt(C);
3429 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3430 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3431 getCursorASTUnit(C));
3432
3433 return clang_getNullCursor();
3434 }
3435
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003436 if (C.kind == CXCursor_MacroInstantiation) {
3437 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3438 return MakeMacroDefinitionCursor(Def, CXXUnit);
3439 }
3440
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003441 if (!clang_isReference(C.kind))
3442 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003443
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003444 switch (C.kind) {
3445 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003446 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003447
3448 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003449 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003450
3451 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003452 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003453
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003454 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003455 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003456
3457 case CXCursor_TemplateRef:
3458 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3459
Douglas Gregor69319002010-08-31 23:48:11 +00003460 case CXCursor_NamespaceRef:
3461 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3462
Douglas Gregora67e03f2010-09-09 21:42:20 +00003463 case CXCursor_MemberRef:
3464 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3465
Ted Kremenek3064ef92010-08-27 21:34:58 +00003466 case CXCursor_CXXBaseSpecifier: {
3467 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3468 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3469 CXXUnit));
3470 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003471
Douglas Gregor36897b02010-09-10 00:22:18 +00003472 case CXCursor_LabelRef:
3473 // FIXME: We end up faking the "parent" declaration here because we
3474 // don't want to make CXCursor larger.
3475 return MakeCXCursor(getCursorLabelRef(C).first,
3476 CXXUnit->getASTContext().getTranslationUnitDecl(),
3477 CXXUnit);
3478
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003479 case CXCursor_OverloadedDeclRef:
3480 return C;
3481
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003482 default:
3483 // We would prefer to enumerate all non-reference cursor kinds here.
3484 llvm_unreachable("Unhandled reference cursor kind");
3485 break;
3486 }
3487 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003488
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003489 return clang_getNullCursor();
3490}
3491
Douglas Gregorb6998662010-01-19 19:34:47 +00003492CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003493 if (clang_isInvalid(C.kind))
3494 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003495
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003496 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003497
Douglas Gregorb6998662010-01-19 19:34:47 +00003498 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003499 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003500 C = clang_getCursorReferenced(C);
3501 WasReference = true;
3502 }
3503
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003504 if (C.kind == CXCursor_MacroInstantiation)
3505 return clang_getCursorReferenced(C);
3506
Douglas Gregorb6998662010-01-19 19:34:47 +00003507 if (!clang_isDeclaration(C.kind))
3508 return clang_getNullCursor();
3509
3510 Decl *D = getCursorDecl(C);
3511 if (!D)
3512 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003513
Douglas Gregorb6998662010-01-19 19:34:47 +00003514 switch (D->getKind()) {
3515 // Declaration kinds that don't really separate the notions of
3516 // declaration and definition.
3517 case Decl::Namespace:
3518 case Decl::Typedef:
3519 case Decl::TemplateTypeParm:
3520 case Decl::EnumConstant:
3521 case Decl::Field:
3522 case Decl::ObjCIvar:
3523 case Decl::ObjCAtDefsField:
3524 case Decl::ImplicitParam:
3525 case Decl::ParmVar:
3526 case Decl::NonTypeTemplateParm:
3527 case Decl::TemplateTemplateParm:
3528 case Decl::ObjCCategoryImpl:
3529 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003530 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003531 case Decl::LinkageSpec:
3532 case Decl::ObjCPropertyImpl:
3533 case Decl::FileScopeAsm:
3534 case Decl::StaticAssert:
3535 case Decl::Block:
3536 return C;
3537
3538 // Declaration kinds that don't make any sense here, but are
3539 // nonetheless harmless.
3540 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003541 break;
3542
3543 // Declaration kinds for which the definition is not resolvable.
3544 case Decl::UnresolvedUsingTypename:
3545 case Decl::UnresolvedUsingValue:
3546 break;
3547
3548 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003549 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3550 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003551
3552 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003553 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003554
3555 case Decl::Enum:
3556 case Decl::Record:
3557 case Decl::CXXRecord:
3558 case Decl::ClassTemplateSpecialization:
3559 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003560 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003561 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003562 return clang_getNullCursor();
3563
3564 case Decl::Function:
3565 case Decl::CXXMethod:
3566 case Decl::CXXConstructor:
3567 case Decl::CXXDestructor:
3568 case Decl::CXXConversion: {
3569 const FunctionDecl *Def = 0;
3570 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003571 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003572 return clang_getNullCursor();
3573 }
3574
3575 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003576 // Ask the variable if it has a definition.
3577 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3578 return MakeCXCursor(Def, CXXUnit);
3579 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003580 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003581
Douglas Gregorb6998662010-01-19 19:34:47 +00003582 case Decl::FunctionTemplate: {
3583 const FunctionDecl *Def = 0;
3584 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003585 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003586 return clang_getNullCursor();
3587 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003588
Douglas Gregorb6998662010-01-19 19:34:47 +00003589 case Decl::ClassTemplate: {
3590 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003591 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003592 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003593 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003594 return clang_getNullCursor();
3595 }
3596
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003597 case Decl::Using:
3598 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3599 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003600
3601 case Decl::UsingShadow:
3602 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003603 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003604 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003605
3606 case Decl::ObjCMethod: {
3607 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3608 if (Method->isThisDeclarationADefinition())
3609 return C;
3610
3611 // Dig out the method definition in the associated
3612 // @implementation, if we have it.
3613 // FIXME: The ASTs should make finding the definition easier.
3614 if (ObjCInterfaceDecl *Class
3615 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3616 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3617 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3618 Method->isInstanceMethod()))
3619 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003620 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003621
3622 return clang_getNullCursor();
3623 }
3624
3625 case Decl::ObjCCategory:
3626 if (ObjCCategoryImplDecl *Impl
3627 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003628 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003629 return clang_getNullCursor();
3630
3631 case Decl::ObjCProtocol:
3632 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3633 return C;
3634 return clang_getNullCursor();
3635
3636 case Decl::ObjCInterface:
3637 // There are two notions of a "definition" for an Objective-C
3638 // class: the interface and its implementation. When we resolved a
3639 // reference to an Objective-C class, produce the @interface as
3640 // the definition; when we were provided with the interface,
3641 // produce the @implementation as the definition.
3642 if (WasReference) {
3643 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3644 return C;
3645 } else if (ObjCImplementationDecl *Impl
3646 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003647 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003648 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003649
Douglas Gregorb6998662010-01-19 19:34:47 +00003650 case Decl::ObjCProperty:
3651 // FIXME: We don't really know where to find the
3652 // ObjCPropertyImplDecls that implement this property.
3653 return clang_getNullCursor();
3654
3655 case Decl::ObjCCompatibleAlias:
3656 if (ObjCInterfaceDecl *Class
3657 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3658 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003659 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003660
Douglas Gregorb6998662010-01-19 19:34:47 +00003661 return clang_getNullCursor();
3662
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003663 case Decl::ObjCForwardProtocol:
3664 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3665 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003666
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003667 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003668 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003669 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003670
3671 case Decl::Friend:
3672 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003673 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003674 return clang_getNullCursor();
3675
3676 case Decl::FriendTemplate:
3677 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003678 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003679 return clang_getNullCursor();
3680 }
3681
3682 return clang_getNullCursor();
3683}
3684
3685unsigned clang_isCursorDefinition(CXCursor C) {
3686 if (!clang_isDeclaration(C.kind))
3687 return 0;
3688
3689 return clang_getCursorDefinition(C) == C;
3690}
3691
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003692unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003693 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003694 return 0;
3695
3696 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3697 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3698 return E->getNumDecls();
3699
3700 if (OverloadedTemplateStorage *S
3701 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3702 return S->size();
3703
3704 Decl *D = Storage.get<Decl*>();
3705 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003706 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003707 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3708 return Classes->size();
3709 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3710 return Protocols->protocol_size();
3711
3712 return 0;
3713}
3714
3715CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003716 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003717 return clang_getNullCursor();
3718
3719 if (index >= clang_getNumOverloadedDecls(cursor))
3720 return clang_getNullCursor();
3721
3722 ASTUnit *Unit = getCursorASTUnit(cursor);
3723 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3724 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3725 return MakeCXCursor(E->decls_begin()[index], Unit);
3726
3727 if (OverloadedTemplateStorage *S
3728 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3729 return MakeCXCursor(S->begin()[index], Unit);
3730
3731 Decl *D = Storage.get<Decl*>();
3732 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3733 // FIXME: This is, unfortunately, linear time.
3734 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3735 std::advance(Pos, index);
3736 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3737 }
3738
3739 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3740 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3741
3742 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3743 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3744
3745 return clang_getNullCursor();
3746}
3747
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003748void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003749 const char **startBuf,
3750 const char **endBuf,
3751 unsigned *startLine,
3752 unsigned *startColumn,
3753 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003754 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003755 assert(getCursorDecl(C) && "CXCursor has null decl");
3756 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003757 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3758 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003759
Steve Naroff4ade6d62009-09-23 17:52:52 +00003760 SourceManager &SM = FD->getASTContext().getSourceManager();
3761 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3762 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3763 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3764 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3765 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3766 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3767}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003768
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003769void clang_enableStackTraces(void) {
3770 llvm::sys::PrintStackTraceOnErrorSignal();
3771}
3772
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003773void clang_executeOnThread(void (*fn)(void*), void *user_data,
3774 unsigned stack_size) {
3775 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3776}
3777
Ted Kremenekfb480492010-01-13 21:46:36 +00003778} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003779
Ted Kremenekfb480492010-01-13 21:46:36 +00003780//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003781// Token-based Operations.
3782//===----------------------------------------------------------------------===//
3783
3784/* CXToken layout:
3785 * int_data[0]: a CXTokenKind
3786 * int_data[1]: starting token location
3787 * int_data[2]: token length
3788 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003789 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003790 * otherwise unused.
3791 */
3792extern "C" {
3793
3794CXTokenKind clang_getTokenKind(CXToken CXTok) {
3795 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3796}
3797
3798CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3799 switch (clang_getTokenKind(CXTok)) {
3800 case CXToken_Identifier:
3801 case CXToken_Keyword:
3802 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003803 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3804 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003805
3806 case CXToken_Literal: {
3807 // We have stashed the starting pointer in the ptr_data field. Use it.
3808 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003809 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003810 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003811
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003812 case CXToken_Punctuation:
3813 case CXToken_Comment:
3814 break;
3815 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003816
3817 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003818 // deconstructing the source location.
3819 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3820 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003821 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003822
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003823 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3824 std::pair<FileID, unsigned> LocInfo
3825 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003826 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003827 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003828 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3829 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003830 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003831
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003832 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003833}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003834
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003835CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3836 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3837 if (!CXXUnit)
3838 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003839
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003840 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3841 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3842}
3843
3844CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3845 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003846 if (!CXXUnit)
3847 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003848
3849 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003850 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3851}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003852
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003853void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3854 CXToken **Tokens, unsigned *NumTokens) {
3855 if (Tokens)
3856 *Tokens = 0;
3857 if (NumTokens)
3858 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003859
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003860 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3861 if (!CXXUnit || !Tokens || !NumTokens)
3862 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003863
Douglas Gregorbdf60622010-03-05 21:16:25 +00003864 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3865
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003866 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003867 if (R.isInvalid())
3868 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003869
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003870 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3871 std::pair<FileID, unsigned> BeginLocInfo
3872 = SourceMgr.getDecomposedLoc(R.getBegin());
3873 std::pair<FileID, unsigned> EndLocInfo
3874 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003875
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003876 // Cannot tokenize across files.
3877 if (BeginLocInfo.first != EndLocInfo.first)
3878 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003879
3880 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003881 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003882 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003883 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003884 if (Invalid)
3885 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003886
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003887 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3888 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003889 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003890 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003891
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003892 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003893 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003894 llvm::SmallVector<CXToken, 32> CXTokens;
3895 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003896 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003897 do {
3898 // Lex the next token
3899 Lex.LexFromRawLexer(Tok);
3900 if (Tok.is(tok::eof))
3901 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003902
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003903 // Initialize the CXToken.
3904 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003905
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003906 // - Common fields
3907 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3908 CXTok.int_data[2] = Tok.getLength();
3909 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003910
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003911 // - Kind-specific fields
3912 if (Tok.isLiteral()) {
3913 CXTok.int_data[0] = CXToken_Literal;
3914 CXTok.ptr_data = (void *)Tok.getLiteralData();
3915 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003916 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003917 std::pair<FileID, unsigned> LocInfo
3918 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003919 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003920 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003921 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3922 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003923 return;
3924
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003925 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003926 IdentifierInfo *II
3927 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003928
David Chisnall096428b2010-10-13 21:44:48 +00003929 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003930 CXTok.int_data[0] = CXToken_Keyword;
3931 }
3932 else {
3933 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3934 CXToken_Identifier
3935 : CXToken_Keyword;
3936 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003937 CXTok.ptr_data = II;
3938 } else if (Tok.is(tok::comment)) {
3939 CXTok.int_data[0] = CXToken_Comment;
3940 CXTok.ptr_data = 0;
3941 } else {
3942 CXTok.int_data[0] = CXToken_Punctuation;
3943 CXTok.ptr_data = 0;
3944 }
3945 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003946 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003947 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003948
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003949 if (CXTokens.empty())
3950 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003951
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003952 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3953 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3954 *NumTokens = CXTokens.size();
3955}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003956
Ted Kremenek6db61092010-05-05 00:55:15 +00003957void clang_disposeTokens(CXTranslationUnit TU,
3958 CXToken *Tokens, unsigned NumTokens) {
3959 free(Tokens);
3960}
3961
3962} // end: extern "C"
3963
3964//===----------------------------------------------------------------------===//
3965// Token annotation APIs.
3966//===----------------------------------------------------------------------===//
3967
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003968typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003969static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3970 CXCursor parent,
3971 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003972namespace {
3973class AnnotateTokensWorker {
3974 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003975 CXToken *Tokens;
3976 CXCursor *Cursors;
3977 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003978 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003979 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003980 CursorVisitor AnnotateVis;
3981 SourceManager &SrcMgr;
3982
3983 bool MoreTokens() const { return TokIdx < NumTokens; }
3984 unsigned NextToken() const { return TokIdx; }
3985 void AdvanceToken() { ++TokIdx; }
3986 SourceLocation GetTokenLoc(unsigned tokI) {
3987 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3988 }
3989
Ted Kremenek6db61092010-05-05 00:55:15 +00003990public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003991 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003992 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3993 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003994 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003995 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003996 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3997 Decl::MaxPCHLevel, RegionOfInterest),
3998 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003999
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004000 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00004001 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004002 void AnnotateTokens(CXCursor parent);
Ted Kremenekab979612010-11-11 08:05:23 +00004003 void AnnotateTokens() {
4004 AnnotateTokens(clang_getTranslationUnitCursor(AnnotateVis.getASTUnit()));
4005 }
Ted Kremenek6db61092010-05-05 00:55:15 +00004006};
4007}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004008
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004009void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
4010 // Walk the AST within the region of interest, annotating tokens
4011 // along the way.
4012 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00004013
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004014 for (unsigned I = 0 ; I < TokIdx ; ++I) {
4015 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00004016 if (Pos != Annotated.end() &&
4017 (clang_isInvalid(Cursors[I].kind) ||
4018 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004019 Cursors[I] = Pos->second;
4020 }
4021
4022 // Finish up annotating any tokens left.
4023 if (!MoreTokens())
4024 return;
4025
4026 const CXCursor &C = clang_getNullCursor();
4027 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
4028 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
4029 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00004030 }
4031}
4032
Ted Kremenek6db61092010-05-05 00:55:15 +00004033enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00004034AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004035 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00004036 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00004037 if (cursorRange.isInvalid())
4038 return CXChildVisit_Recurse;
4039
Douglas Gregor4419b672010-10-21 06:10:04 +00004040 if (clang_isPreprocessing(cursor.kind)) {
4041 // For macro instantiations, just note where the beginning of the macro
4042 // instantiation occurs.
4043 if (cursor.kind == CXCursor_MacroInstantiation) {
4044 Annotated[Loc.int_data] = cursor;
4045 return CXChildVisit_Recurse;
4046 }
4047
Douglas Gregor4419b672010-10-21 06:10:04 +00004048 // Items in the preprocessing record are kept separate from items in
4049 // declarations, so we keep a separate token index.
4050 unsigned SavedTokIdx = TokIdx;
4051 TokIdx = PreprocessingTokIdx;
4052
4053 // Skip tokens up until we catch up to the beginning of the preprocessing
4054 // entry.
4055 while (MoreTokens()) {
4056 const unsigned I = NextToken();
4057 SourceLocation TokLoc = GetTokenLoc(I);
4058 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4059 case RangeBefore:
4060 AdvanceToken();
4061 continue;
4062 case RangeAfter:
4063 case RangeOverlap:
4064 break;
4065 }
4066 break;
4067 }
4068
4069 // Look at all of the tokens within this range.
4070 while (MoreTokens()) {
4071 const unsigned I = NextToken();
4072 SourceLocation TokLoc = GetTokenLoc(I);
4073 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4074 case RangeBefore:
4075 assert(0 && "Infeasible");
4076 case RangeAfter:
4077 break;
4078 case RangeOverlap:
4079 Cursors[I] = cursor;
4080 AdvanceToken();
4081 continue;
4082 }
4083 break;
4084 }
4085
4086 // Save the preprocessing token index; restore the non-preprocessing
4087 // token index.
4088 PreprocessingTokIdx = TokIdx;
4089 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004090 return CXChildVisit_Recurse;
4091 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004092
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004093 if (cursorRange.isInvalid())
4094 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004095
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004096 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4097
Ted Kremeneka333c662010-05-12 05:29:33 +00004098 // Adjust the annotated range based specific declarations.
4099 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4100 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004101 Decl *D = cxcursor::getCursorDecl(cursor);
4102 // Don't visit synthesized ObjC methods, since they have no syntatic
4103 // representation in the source.
4104 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4105 if (MD->isSynthesized())
4106 return CXChildVisit_Continue;
4107 }
4108 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004109 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4110 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004111 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004112 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004113 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004114 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004115 }
4116 }
4117 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004118
Ted Kremenek3f404602010-08-14 01:14:06 +00004119 // If the location of the cursor occurs within a macro instantiation, record
4120 // the spelling location of the cursor in our annotation map. We can then
4121 // paper over the token labelings during a post-processing step to try and
4122 // get cursor mappings for tokens that are the *arguments* of a macro
4123 // instantiation.
4124 if (L.isMacroID()) {
4125 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4126 // Only invalidate the old annotation if it isn't part of a preprocessing
4127 // directive. Here we assume that the default construction of CXCursor
4128 // results in CXCursor.kind being an initialized value (i.e., 0). If
4129 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004130
Ted Kremenek3f404602010-08-14 01:14:06 +00004131 CXCursor &oldC = Annotated[rawEncoding];
4132 if (!clang_isPreprocessing(oldC.kind))
4133 oldC = cursor;
4134 }
4135
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004136 const enum CXCursorKind K = clang_getCursorKind(parent);
4137 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004138 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4139 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004140
4141 while (MoreTokens()) {
4142 const unsigned I = NextToken();
4143 SourceLocation TokLoc = GetTokenLoc(I);
4144 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4145 case RangeBefore:
4146 Cursors[I] = updateC;
4147 AdvanceToken();
4148 continue;
4149 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004150 case RangeOverlap:
4151 break;
4152 }
4153 break;
4154 }
4155
4156 // Visit children to get their cursor information.
4157 const unsigned BeforeChildren = NextToken();
4158 VisitChildren(cursor);
4159 const unsigned AfterChildren = NextToken();
4160
4161 // Adjust 'Last' to the last token within the extent of the cursor.
4162 while (MoreTokens()) {
4163 const unsigned I = NextToken();
4164 SourceLocation TokLoc = GetTokenLoc(I);
4165 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4166 case RangeBefore:
4167 assert(0 && "Infeasible");
4168 case RangeAfter:
4169 break;
4170 case RangeOverlap:
4171 Cursors[I] = updateC;
4172 AdvanceToken();
4173 continue;
4174 }
4175 break;
4176 }
4177 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004178
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004179 // Scan the tokens that are at the beginning of the cursor, but are not
4180 // capture by the child cursors.
4181
4182 // For AST elements within macros, rely on a post-annotate pass to
4183 // to correctly annotate the tokens with cursors. Otherwise we can
4184 // get confusing results of having tokens that map to cursors that really
4185 // are expanded by an instantiation.
4186 if (L.isMacroID())
4187 cursor = clang_getNullCursor();
4188
4189 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4190 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4191 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004192
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004193 Cursors[I] = cursor;
4194 }
4195 // Scan the tokens that are at the end of the cursor, but are not captured
4196 // but the child cursors.
4197 for (unsigned I = AfterChildren; I != Last; ++I)
4198 Cursors[I] = cursor;
4199
4200 TokIdx = Last;
4201 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004202}
4203
Ted Kremenek6db61092010-05-05 00:55:15 +00004204static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4205 CXCursor parent,
4206 CXClientData client_data) {
4207 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4208}
4209
Ted Kremenekab979612010-11-11 08:05:23 +00004210// This gets run a separate thread to avoid stack blowout.
4211static void runAnnotateTokensWorker(void *UserData) {
4212 ((AnnotateTokensWorker*)UserData)->AnnotateTokens();
4213}
4214
Ted Kremenek6db61092010-05-05 00:55:15 +00004215extern "C" {
4216
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004217void clang_annotateTokens(CXTranslationUnit TU,
4218 CXToken *Tokens, unsigned NumTokens,
4219 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004220
4221 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004222 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004223
Douglas Gregor4419b672010-10-21 06:10:04 +00004224 // Any token we don't specifically annotate will have a NULL cursor.
4225 CXCursor C = clang_getNullCursor();
4226 for (unsigned I = 0; I != NumTokens; ++I)
4227 Cursors[I] = C;
4228
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004229 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004230 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004231 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004232
Douglas Gregorbdf60622010-03-05 21:16:25 +00004233 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004234
Douglas Gregor0396f462010-03-19 05:22:59 +00004235 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004236 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004237 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4238 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004239 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4240 clang_getTokenLocation(TU,
4241 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004242
Douglas Gregor0396f462010-03-19 05:22:59 +00004243 // A mapping from the source locations found when re-lexing or traversing the
4244 // region of interest to the corresponding cursors.
4245 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004246
4247 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004248 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004249 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4250 std::pair<FileID, unsigned> BeginLocInfo
4251 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4252 std::pair<FileID, unsigned> EndLocInfo
4253 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004254
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004255 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004256 bool Invalid = false;
4257 if (BeginLocInfo.first == EndLocInfo.first &&
4258 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4259 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004260 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4261 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004262 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004263 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004264 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004265
4266 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004267 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004268 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004269 Token Tok;
4270 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004271
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004272 reprocess:
4273 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4274 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004275 // don't see it while preprocessing these tokens later, but keep track
4276 // of all of the token locations inside this preprocessing directive so
4277 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004278 //
4279 // FIXME: Some simple tests here could identify macro definitions and
4280 // #undefs, to provide specific cursor kinds for those.
4281 std::vector<SourceLocation> Locations;
4282 do {
4283 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004284 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004285 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004286
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004287 using namespace cxcursor;
4288 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004289 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4290 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004291 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004292 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4293 Annotated[Locations[I].getRawEncoding()] = Cursor;
4294 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004295
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004296 if (Tok.isAtStartOfLine())
4297 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004298
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004299 continue;
4300 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004301
Douglas Gregor48072312010-03-18 15:23:44 +00004302 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004303 break;
4304 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004305 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004306
Douglas Gregor0396f462010-03-19 05:22:59 +00004307 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004308 // a specific cursor.
4309 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4310 CXXUnit, RegionOfInterest);
Ted Kremenekab979612010-11-11 08:05:23 +00004311
4312 // Run the worker within a CrashRecoveryContext.
4313 llvm::CrashRecoveryContext CRC;
4314 if (!RunSafely(CRC, runAnnotateTokensWorker, &W)) {
4315 fprintf(stderr, "libclang: crash detected while annotating tokens\n");
4316 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004317}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004318} // end: extern "C"
4319
4320//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004321// Operations for querying linkage of a cursor.
4322//===----------------------------------------------------------------------===//
4323
4324extern "C" {
4325CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004326 if (!clang_isDeclaration(cursor.kind))
4327 return CXLinkage_Invalid;
4328
Ted Kremenek16b42592010-03-03 06:36:57 +00004329 Decl *D = cxcursor::getCursorDecl(cursor);
4330 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4331 switch (ND->getLinkage()) {
4332 case NoLinkage: return CXLinkage_NoLinkage;
4333 case InternalLinkage: return CXLinkage_Internal;
4334 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4335 case ExternalLinkage: return CXLinkage_External;
4336 };
4337
4338 return CXLinkage_Invalid;
4339}
4340} // end: extern "C"
4341
4342//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004343// Operations for querying language of a cursor.
4344//===----------------------------------------------------------------------===//
4345
4346static CXLanguageKind getDeclLanguage(const Decl *D) {
4347 switch (D->getKind()) {
4348 default:
4349 break;
4350 case Decl::ImplicitParam:
4351 case Decl::ObjCAtDefsField:
4352 case Decl::ObjCCategory:
4353 case Decl::ObjCCategoryImpl:
4354 case Decl::ObjCClass:
4355 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004356 case Decl::ObjCForwardProtocol:
4357 case Decl::ObjCImplementation:
4358 case Decl::ObjCInterface:
4359 case Decl::ObjCIvar:
4360 case Decl::ObjCMethod:
4361 case Decl::ObjCProperty:
4362 case Decl::ObjCPropertyImpl:
4363 case Decl::ObjCProtocol:
4364 return CXLanguage_ObjC;
4365 case Decl::CXXConstructor:
4366 case Decl::CXXConversion:
4367 case Decl::CXXDestructor:
4368 case Decl::CXXMethod:
4369 case Decl::CXXRecord:
4370 case Decl::ClassTemplate:
4371 case Decl::ClassTemplatePartialSpecialization:
4372 case Decl::ClassTemplateSpecialization:
4373 case Decl::Friend:
4374 case Decl::FriendTemplate:
4375 case Decl::FunctionTemplate:
4376 case Decl::LinkageSpec:
4377 case Decl::Namespace:
4378 case Decl::NamespaceAlias:
4379 case Decl::NonTypeTemplateParm:
4380 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004381 case Decl::TemplateTemplateParm:
4382 case Decl::TemplateTypeParm:
4383 case Decl::UnresolvedUsingTypename:
4384 case Decl::UnresolvedUsingValue:
4385 case Decl::Using:
4386 case Decl::UsingDirective:
4387 case Decl::UsingShadow:
4388 return CXLanguage_CPlusPlus;
4389 }
4390
4391 return CXLanguage_C;
4392}
4393
4394extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004395
4396enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4397 if (clang_isDeclaration(cursor.kind))
4398 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4399 if (D->hasAttr<UnavailableAttr>() ||
4400 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4401 return CXAvailability_Available;
4402
4403 if (D->hasAttr<DeprecatedAttr>())
4404 return CXAvailability_Deprecated;
4405 }
4406
4407 return CXAvailability_Available;
4408}
4409
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004410CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4411 if (clang_isDeclaration(cursor.kind))
4412 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4413
4414 return CXLanguage_Invalid;
4415}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004416
4417CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4418 if (clang_isDeclaration(cursor.kind)) {
4419 if (Decl *D = getCursorDecl(cursor)) {
4420 DeclContext *DC = D->getDeclContext();
4421 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4422 }
4423 }
4424
4425 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4426 if (Decl *D = getCursorDecl(cursor))
4427 return MakeCXCursor(D, getCursorASTUnit(cursor));
4428 }
4429
4430 return clang_getNullCursor();
4431}
4432
4433CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4434 if (clang_isDeclaration(cursor.kind)) {
4435 if (Decl *D = getCursorDecl(cursor)) {
4436 DeclContext *DC = D->getLexicalDeclContext();
4437 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4438 }
4439 }
4440
4441 // FIXME: Note that we can't easily compute the lexical context of a
4442 // statement or expression, so we return nothing.
4443 return clang_getNullCursor();
4444}
4445
Douglas Gregor9f592342010-10-01 20:25:15 +00004446static void CollectOverriddenMethods(DeclContext *Ctx,
4447 ObjCMethodDecl *Method,
4448 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4449 if (!Ctx)
4450 return;
4451
4452 // If we have a class or category implementation, jump straight to the
4453 // interface.
4454 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4455 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4456
4457 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4458 if (!Container)
4459 return;
4460
4461 // Check whether we have a matching method at this level.
4462 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4463 Method->isInstanceMethod()))
4464 if (Method != Overridden) {
4465 // We found an override at this level; there is no need to look
4466 // into other protocols or categories.
4467 Methods.push_back(Overridden);
4468 return;
4469 }
4470
4471 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4472 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4473 PEnd = Protocol->protocol_end();
4474 P != PEnd; ++P)
4475 CollectOverriddenMethods(*P, Method, Methods);
4476 }
4477
4478 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4479 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4480 PEnd = Category->protocol_end();
4481 P != PEnd; ++P)
4482 CollectOverriddenMethods(*P, Method, Methods);
4483 }
4484
4485 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4486 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4487 PEnd = Interface->protocol_end();
4488 P != PEnd; ++P)
4489 CollectOverriddenMethods(*P, Method, Methods);
4490
4491 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4492 Category; Category = Category->getNextClassCategory())
4493 CollectOverriddenMethods(Category, Method, Methods);
4494
4495 // We only look into the superclass if we haven't found anything yet.
4496 if (Methods.empty())
4497 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4498 return CollectOverriddenMethods(Super, Method, Methods);
4499 }
4500}
4501
4502void clang_getOverriddenCursors(CXCursor cursor,
4503 CXCursor **overridden,
4504 unsigned *num_overridden) {
4505 if (overridden)
4506 *overridden = 0;
4507 if (num_overridden)
4508 *num_overridden = 0;
4509 if (!overridden || !num_overridden)
4510 return;
4511
4512 if (!clang_isDeclaration(cursor.kind))
4513 return;
4514
4515 Decl *D = getCursorDecl(cursor);
4516 if (!D)
4517 return;
4518
4519 // Handle C++ member functions.
4520 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4521 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4522 *num_overridden = CXXMethod->size_overridden_methods();
4523 if (!*num_overridden)
4524 return;
4525
4526 *overridden = new CXCursor [*num_overridden];
4527 unsigned I = 0;
4528 for (CXXMethodDecl::method_iterator
4529 M = CXXMethod->begin_overridden_methods(),
4530 MEnd = CXXMethod->end_overridden_methods();
4531 M != MEnd; (void)++M, ++I)
4532 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4533 return;
4534 }
4535
4536 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4537 if (!Method)
4538 return;
4539
4540 // Handle Objective-C methods.
4541 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4542 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4543
4544 if (Methods.empty())
4545 return;
4546
4547 *num_overridden = Methods.size();
4548 *overridden = new CXCursor [Methods.size()];
4549 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4550 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4551}
4552
4553void clang_disposeOverriddenCursors(CXCursor *overridden) {
4554 delete [] overridden;
4555}
4556
Douglas Gregorecdcb882010-10-20 22:00:55 +00004557CXFile clang_getIncludedFile(CXCursor cursor) {
4558 if (cursor.kind != CXCursor_InclusionDirective)
4559 return 0;
4560
4561 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4562 return (void *)ID->getFile();
4563}
4564
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004565} // end: extern "C"
4566
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004567
4568//===----------------------------------------------------------------------===//
4569// C++ AST instrospection.
4570//===----------------------------------------------------------------------===//
4571
4572extern "C" {
4573unsigned clang_CXXMethod_isStatic(CXCursor C) {
4574 if (!clang_isDeclaration(C.kind))
4575 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004576
4577 CXXMethodDecl *Method = 0;
4578 Decl *D = cxcursor::getCursorDecl(C);
4579 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4580 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4581 else
4582 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4583 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004584}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004585
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004586} // end: extern "C"
4587
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004588//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004589// Attribute introspection.
4590//===----------------------------------------------------------------------===//
4591
4592extern "C" {
4593CXType clang_getIBOutletCollectionType(CXCursor C) {
4594 if (C.kind != CXCursor_IBOutletCollectionAttr)
4595 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4596
4597 IBOutletCollectionAttr *A =
4598 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4599
4600 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4601}
4602} // end: extern "C"
4603
4604//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004605// CXString Operations.
4606//===----------------------------------------------------------------------===//
4607
4608extern "C" {
4609const char *clang_getCString(CXString string) {
4610 return string.Spelling;
4611}
4612
4613void clang_disposeString(CXString string) {
4614 if (string.MustFreeString && string.Spelling)
4615 free((void*)string.Spelling);
4616}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004617
Ted Kremenekfb480492010-01-13 21:46:36 +00004618} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004619
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004620namespace clang { namespace cxstring {
4621CXString createCXString(const char *String, bool DupString){
4622 CXString Str;
4623 if (DupString) {
4624 Str.Spelling = strdup(String);
4625 Str.MustFreeString = 1;
4626 } else {
4627 Str.Spelling = String;
4628 Str.MustFreeString = 0;
4629 }
4630 return Str;
4631}
4632
4633CXString createCXString(llvm::StringRef String, bool DupString) {
4634 CXString Result;
4635 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4636 char *Spelling = (char *)malloc(String.size() + 1);
4637 memmove(Spelling, String.data(), String.size());
4638 Spelling[String.size()] = 0;
4639 Result.Spelling = Spelling;
4640 Result.MustFreeString = 1;
4641 } else {
4642 Result.Spelling = String.data();
4643 Result.MustFreeString = 0;
4644 }
4645 return Result;
4646}
4647}}
4648
Ted Kremenek04bb7162010-01-22 22:44:15 +00004649//===----------------------------------------------------------------------===//
4650// Misc. utility functions.
4651//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004652
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004653/// Default to using an 8 MB stack size on "safety" threads.
4654static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004655
4656namespace clang {
4657
4658bool RunSafely(llvm::CrashRecoveryContext &CRC,
4659 void (*Fn)(void*), void *UserData) {
4660 if (unsigned Size = GetSafetyThreadStackSize())
4661 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4662 return CRC.RunSafely(Fn, UserData);
4663}
4664
4665unsigned GetSafetyThreadStackSize() {
4666 return SafetyStackThreadSize;
4667}
4668
4669void SetSafetyThreadStackSize(unsigned Value) {
4670 SafetyStackThreadSize = Value;
4671}
4672
4673}
4674
Ted Kremenek04bb7162010-01-22 22:44:15 +00004675extern "C" {
4676
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004677CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004678 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004679}
4680
4681} // end: extern "C"