blob: 42617f0ce46c821a5f85faf000fd3381c0a42e3b [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 Gregorb6278712010-11-09 05:28:47 +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 Kremenekf0e23e82010-02-17 00:41:40 +0000126
Douglas Gregorb1373d02010-01-20 20:59:29 +0000127// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000128class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000129 public TypeLocVisitor<CursorVisitor, bool>,
130 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000131{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000133 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000134
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000136 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000137
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000138 /// \brief The declaration that serves at the parent of any statement or
139 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000140 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000141
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000142 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000143 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000144
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000145 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000146 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000147
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000148 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
149 // to the visitor. Declarations with a PCH level greater than this value will
150 // be suppressed.
151 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000152
153 /// \brief When valid, a source range to which the cursor should restrict
154 /// its search.
155 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000156
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000157 // FIXME: Eventually remove. This part of a hack to support proper
158 // iteration over all Decls contained lexically within an ObjC container.
159 DeclContext::decl_iterator *DI_current;
160 DeclContext::decl_iterator DE_current;
161
Douglas Gregorb1373d02010-01-20 20:59:29 +0000162 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000163 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000164 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000165
166 /// \brief Determine whether this particular source range comes before, comes
167 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000168 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000169 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000170 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
171
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000172 class SetParentRAII {
173 CXCursor &Parent;
174 Decl *&StmtParent;
175 CXCursor OldParent;
176
177 public:
178 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
179 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
180 {
181 Parent = NewParent;
182 if (clang_isDeclaration(Parent.kind))
183 StmtParent = getCursorDecl(Parent);
184 }
185
186 ~SetParentRAII() {
187 Parent = OldParent;
188 if (clang_isDeclaration(Parent.kind))
189 StmtParent = getCursorDecl(Parent);
190 }
191 };
192
Steve Naroff89922f82009-08-31 00:59:03 +0000193public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000194 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
195 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000196 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000197 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000198 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
199 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000200 {
201 Parent.kind = CXCursor_NoDeclFound;
202 Parent.data[0] = 0;
203 Parent.data[1] = 0;
204 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000205 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000206 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000207
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000209
210 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
211 getPreprocessedEntities();
212
Douglas Gregorb1373d02010-01-20 20:59:29 +0000213 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000214
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000215 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000216 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000217 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000218 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000219 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000220 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000221 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
222 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000223 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000224 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000225 bool VisitClassTemplatePartialSpecializationDecl(
226 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000227 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000228 bool VisitEnumConstantDecl(EnumConstantDecl *D);
229 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
230 bool VisitFunctionDecl(FunctionDecl *ND);
231 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000232 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000233 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000234 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000235 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000236 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000237 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
238 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
239 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
240 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000241 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000242 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
243 bool VisitObjCImplDecl(ObjCImplDecl *D);
244 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
245 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000246 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
247 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
248 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000249 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000250 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000251 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000252 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000253 bool VisitUsingDecl(UsingDecl *D);
254 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
255 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000256
Douglas Gregor01829d32010-08-31 14:41:23 +0000257 // Name visitor
258 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000259 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000260
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000261 // Template visitors
262 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000263 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000264 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
265
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000266 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000267 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000268 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000269 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000270 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
271 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000272 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000273 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000274 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000275 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
276 bool VisitPointerTypeLoc(PointerTypeLoc TL);
277 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
278 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
279 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
280 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000281 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000282 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000283 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000284 // FIXME: Implement visitors here when the unimplemented TypeLocs get
285 // implemented
286 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
287 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000288
Douglas Gregora59e3902010-01-21 23:27:09 +0000289 // Statement visitors
290 bool VisitStmt(Stmt *S);
291 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000292 bool VisitGotoStmt(GotoStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000293 bool VisitIfStmt(IfStmt *S);
294 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000295 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000296 bool VisitWhileStmt(WhileStmt *S);
297 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000298
Douglas Gregor336fd812010-01-23 00:40:08 +0000299 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000300 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000301 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000302 bool VisitBlockExpr(BlockExpr *B);
Ted Kremenek04c450c2010-11-08 21:14:15 +0000303 bool VisitBinaryOperator(BinaryOperator *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000304 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000305 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000306 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000307 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000308 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000309 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfbb4c982010-09-02 21:07:44 +0000310 bool VisitMemberExpr(MemberExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000311 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000312 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
313 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000314 bool VisitInitListExpr(InitListExpr *E);
315 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000316 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000317 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000318 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000319 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
320 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000321 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000322 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000323 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000324 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000325 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000326 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000327 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000328 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000329};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000330
Ted Kremenekab188932010-01-05 19:32:54 +0000331} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000332
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000333static SourceRange getRawCursorExtent(CXCursor C);
334
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000335RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000336 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
337}
338
Douglas Gregorb1373d02010-01-20 20:59:29 +0000339/// \brief Visit the given cursor and, if requested by the visitor,
340/// its children.
341///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000342/// \param Cursor the cursor to visit.
343///
344/// \param CheckRegionOfInterest if true, then the caller already checked that
345/// this cursor is within the region of interest.
346///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000347/// \returns true if the visitation should be aborted, false if it
348/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000349bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000350 if (clang_isInvalid(Cursor.kind))
351 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000352
Douglas Gregorb1373d02010-01-20 20:59:29 +0000353 if (clang_isDeclaration(Cursor.kind)) {
354 Decl *D = getCursorDecl(Cursor);
355 assert(D && "Invalid declaration cursor");
356 if (D->getPCHLevel() > MaxPCHLevel)
357 return false;
358
359 if (D->isImplicit())
360 return false;
361 }
362
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000363 // If we have a range of interest, and this cursor doesn't intersect with it,
364 // we're done.
365 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000366 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000367 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000368 return false;
369 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000370
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371 switch (Visitor(Cursor, Parent, ClientData)) {
372 case CXChildVisit_Break:
373 return true;
374
375 case CXChildVisit_Continue:
376 return false;
377
378 case CXChildVisit_Recurse:
379 return VisitChildren(Cursor);
380 }
381
Douglas Gregorfd643772010-01-25 16:45:46 +0000382 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000383}
384
Douglas Gregor788f5a12010-03-20 00:41:21 +0000385std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
386CursorVisitor::getPreprocessedEntities() {
387 PreprocessingRecord &PPRec
388 = *TU->getPreprocessor().getPreprocessingRecord();
389
390 bool OnlyLocalDecls
391 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
392
393 // There is no region of interest; we have to walk everything.
394 if (RegionOfInterest.isInvalid())
395 return std::make_pair(PPRec.begin(OnlyLocalDecls),
396 PPRec.end(OnlyLocalDecls));
397
398 // Find the file in which the region of interest lands.
399 SourceManager &SM = TU->getSourceManager();
400 std::pair<FileID, unsigned> Begin
401 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
402 std::pair<FileID, unsigned> End
403 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
404
405 // The region of interest spans files; we have to walk everything.
406 if (Begin.first != End.first)
407 return std::make_pair(PPRec.begin(OnlyLocalDecls),
408 PPRec.end(OnlyLocalDecls));
409
410 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
411 = TU->getPreprocessedEntitiesByFile();
412 if (ByFileMap.empty()) {
413 // Build the mapping from files to sets of preprocessed entities.
414 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
415 EEnd = PPRec.end(OnlyLocalDecls);
416 E != EEnd; ++E) {
417 std::pair<FileID, unsigned> P
418 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
419 ByFileMap[P.first].push_back(*E);
420 }
421 }
422
423 return std::make_pair(ByFileMap[Begin.first].begin(),
424 ByFileMap[Begin.first].end());
425}
426
Douglas Gregorb1373d02010-01-20 20:59:29 +0000427/// \brief Visit the children of the given cursor.
428///
429/// \returns true if the visitation should be aborted, false if it
430/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000431bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000432 if (clang_isReference(Cursor.kind)) {
433 // By definition, references have no children.
434 return false;
435 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000436
437 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000438 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000439 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000440
Douglas Gregorb1373d02010-01-20 20:59:29 +0000441 if (clang_isDeclaration(Cursor.kind)) {
442 Decl *D = getCursorDecl(Cursor);
443 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000444 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000446
Douglas Gregora59e3902010-01-21 23:27:09 +0000447 if (clang_isStatement(Cursor.kind))
448 return Visit(getCursorStmt(Cursor));
449 if (clang_isExpression(Cursor.kind))
450 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000451
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000453 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000454 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
455 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000456 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
457 TLEnd = CXXUnit->top_level_end();
458 TL != TLEnd; ++TL) {
459 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000460 return true;
461 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000462 } else if (VisitDeclContext(
463 CXXUnit->getASTContext().getTranslationUnitDecl()))
464 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000465
Douglas Gregor0396f462010-03-19 05:22:59 +0000466 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000467 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000468 // FIXME: Once we have the ability to deserialize a preprocessing record,
469 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000470 PreprocessingRecord::iterator E, EEnd;
471 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000472 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
473 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
474 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000475
Douglas Gregor0396f462010-03-19 05:22:59 +0000476 continue;
477 }
478
479 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
480 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
481 return true;
482
483 continue;
484 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000485
486 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
487 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
488 return true;
489
490 continue;
491 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000492 }
493 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000494 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000495 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000496
Douglas Gregorb1373d02010-01-20 20:59:29 +0000497 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000498 return false;
499}
500
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000501bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000502 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
503 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000504
Ted Kremenek664cffd2010-07-22 11:30:19 +0000505 if (Stmt *Body = B->getBody())
506 return Visit(MakeCXCursor(Body, StmtParent, TU));
507
508 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000509}
510
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000511llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
512 if (RegionOfInterest.isValid()) {
513 SourceRange Range = getRawCursorExtent(Cursor);
514 if (Range.isInvalid())
515 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000516
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000517 switch (CompareRegionOfInterest(Range)) {
518 case RangeBefore:
519 // This declaration comes before the region of interest; skip it.
520 return llvm::Optional<bool>();
521
522 case RangeAfter:
523 // This declaration comes after the region of interest; we're done.
524 return false;
525
526 case RangeOverlap:
527 // This declaration overlaps the region of interest; visit it.
528 break;
529 }
530 }
531 return true;
532}
533
534bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
535 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
536
537 // FIXME: Eventually remove. This part of a hack to support proper
538 // iteration over all Decls contained lexically within an ObjC container.
539 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
540 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
541
542 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000543 Decl *D = *I;
544 if (D->getLexicalDeclContext() != DC)
545 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000546 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000547 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
548 if (!V.hasValue())
549 continue;
550 if (!V.getValue())
551 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000552 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000553 return true;
554 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000555 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000556}
557
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000558bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
559 llvm_unreachable("Translation units are visited directly by Visit()");
560 return false;
561}
562
563bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
564 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
565 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000566
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000567 return false;
568}
569
570bool CursorVisitor::VisitTagDecl(TagDecl *D) {
571 return VisitDeclContext(D);
572}
573
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000574bool CursorVisitor::VisitClassTemplateSpecializationDecl(
575 ClassTemplateSpecializationDecl *D) {
576 bool ShouldVisitBody = false;
577 switch (D->getSpecializationKind()) {
578 case TSK_Undeclared:
579 case TSK_ImplicitInstantiation:
580 // Nothing to visit
581 return false;
582
583 case TSK_ExplicitInstantiationDeclaration:
584 case TSK_ExplicitInstantiationDefinition:
585 break;
586
587 case TSK_ExplicitSpecialization:
588 ShouldVisitBody = true;
589 break;
590 }
591
592 // Visit the template arguments used in the specialization.
593 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
594 TypeLoc TL = SpecType->getTypeLoc();
595 if (TemplateSpecializationTypeLoc *TSTLoc
596 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
597 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
598 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
599 return true;
600 }
601 }
602
603 if (ShouldVisitBody && VisitCXXRecordDecl(D))
604 return true;
605
606 return false;
607}
608
Douglas Gregor74dbe642010-08-31 19:31:58 +0000609bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
610 ClassTemplatePartialSpecializationDecl *D) {
611 // FIXME: Visit the "outer" template parameter lists on the TagDecl
612 // before visiting these template parameters.
613 if (VisitTemplateParameters(D->getTemplateParameters()))
614 return true;
615
616 // Visit the partial specialization arguments.
617 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
618 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
619 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
620 return true;
621
622 return VisitCXXRecordDecl(D);
623}
624
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000625bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000626 // Visit the default argument.
627 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
628 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
629 if (Visit(DefArg->getTypeLoc()))
630 return true;
631
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000632 return false;
633}
634
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000635bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
636 if (Expr *Init = D->getInitExpr())
637 return Visit(MakeCXCursor(Init, StmtParent, TU));
638 return false;
639}
640
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000641bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
642 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
643 if (Visit(TSInfo->getTypeLoc()))
644 return true;
645
646 return false;
647}
648
Douglas Gregora67e03f2010-09-09 21:42:20 +0000649/// \brief Compare two base or member initializers based on their source order.
650static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
651 CXXBaseOrMemberInitializer const * const *X
652 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
653 CXXBaseOrMemberInitializer const * const *Y
654 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
655
656 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
657 return -1;
658 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
659 return 1;
660 else
661 return 0;
662}
663
Douglas Gregorb1373d02010-01-20 20:59:29 +0000664bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000665 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
666 // Visit the function declaration's syntactic components in the order
667 // written. This requires a bit of work.
668 TypeLoc TL = TSInfo->getTypeLoc();
669 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
670
671 // If we have a function declared directly (without the use of a typedef),
672 // visit just the return type. Otherwise, just visit the function's type
673 // now.
674 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
675 (!FTL && Visit(TL)))
676 return true;
677
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000678 // Visit the nested-name-specifier, if present.
679 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
680 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
681 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000682
683 // Visit the declaration name.
684 if (VisitDeclarationNameInfo(ND->getNameInfo()))
685 return true;
686
687 // FIXME: Visit explicitly-specified template arguments!
688
689 // Visit the function parameters, if we have a function type.
690 if (FTL && VisitFunctionTypeLoc(*FTL, true))
691 return true;
692
693 // FIXME: Attributes?
694 }
695
Douglas Gregora67e03f2010-09-09 21:42:20 +0000696 if (ND->isThisDeclarationADefinition()) {
697 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
698 // Find the initializers that were written in the source.
699 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
700 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
701 IEnd = Constructor->init_end();
702 I != IEnd; ++I) {
703 if (!(*I)->isWritten())
704 continue;
705
706 WrittenInits.push_back(*I);
707 }
708
709 // Sort the initializers in source order
710 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
711 &CompareCXXBaseOrMemberInitializers);
712
713 // Visit the initializers in source order
714 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
715 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
716 if (Init->isMemberInitializer()) {
717 if (Visit(MakeCursorMemberRef(Init->getMember(),
718 Init->getMemberLocation(), TU)))
719 return true;
720 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
721 if (Visit(BaseInfo->getTypeLoc()))
722 return true;
723 }
724
725 // Visit the initializer value.
726 if (Expr *Initializer = Init->getInit())
727 if (Visit(MakeCXCursor(Initializer, ND, TU)))
728 return true;
729 }
730 }
731
732 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
733 return true;
734 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000735
Douglas Gregorb1373d02010-01-20 20:59:29 +0000736 return false;
737}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000738
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000739bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
740 if (VisitDeclaratorDecl(D))
741 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000742
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000743 if (Expr *BitWidth = D->getBitWidth())
744 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000745
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000746 return false;
747}
748
749bool CursorVisitor::VisitVarDecl(VarDecl *D) {
750 if (VisitDeclaratorDecl(D))
751 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000752
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000753 if (Expr *Init = D->getInit())
754 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000755
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000756 return false;
757}
758
Douglas Gregor84b51d72010-09-01 20:16:53 +0000759bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
760 if (VisitDeclaratorDecl(D))
761 return true;
762
763 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
764 if (Expr *DefArg = D->getDefaultArgument())
765 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
766
767 return false;
768}
769
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000770bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
771 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
772 // before visiting these template parameters.
773 if (VisitTemplateParameters(D->getTemplateParameters()))
774 return true;
775
776 return VisitFunctionDecl(D->getTemplatedDecl());
777}
778
Douglas Gregor39d6f072010-08-31 19:02:00 +0000779bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
780 // FIXME: Visit the "outer" template parameter lists on the TagDecl
781 // before visiting these template parameters.
782 if (VisitTemplateParameters(D->getTemplateParameters()))
783 return true;
784
785 return VisitCXXRecordDecl(D->getTemplatedDecl());
786}
787
Douglas Gregor84b51d72010-09-01 20:16:53 +0000788bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
789 if (VisitTemplateParameters(D->getTemplateParameters()))
790 return true;
791
792 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
793 VisitTemplateArgumentLoc(D->getDefaultArgument()))
794 return true;
795
796 return false;
797}
798
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000799bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000800 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
801 if (Visit(TSInfo->getTypeLoc()))
802 return true;
803
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 PEnd = ND->param_end();
806 P != PEnd; ++P) {
807 if (Visit(MakeCXCursor(*P, TU)))
808 return true;
809 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000810
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000811 if (ND->isThisDeclarationADefinition() &&
812 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
813 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000814
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000815 return false;
816}
817
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000818namespace {
819 struct ContainerDeclsSort {
820 SourceManager &SM;
821 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
822 bool operator()(Decl *A, Decl *B) {
823 SourceLocation L_A = A->getLocStart();
824 SourceLocation L_B = B->getLocStart();
825 assert(L_A.isValid() && L_B.isValid());
826 return SM.isBeforeInTranslationUnit(L_A, L_B);
827 }
828 };
829}
830
Douglas Gregora59e3902010-01-21 23:27:09 +0000831bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000832 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
833 // an @implementation can lexically contain Decls that are not properly
834 // nested in the AST. When we identify such cases, we need to retrofit
835 // this nesting here.
836 if (!DI_current)
837 return VisitDeclContext(D);
838
839 // Scan the Decls that immediately come after the container
840 // in the current DeclContext. If any fall within the
841 // container's lexical region, stash them into a vector
842 // for later processing.
843 llvm::SmallVector<Decl *, 24> DeclsInContainer;
844 SourceLocation EndLoc = D->getSourceRange().getEnd();
845 SourceManager &SM = TU->getSourceManager();
846 if (EndLoc.isValid()) {
847 DeclContext::decl_iterator next = *DI_current;
848 while (++next != DE_current) {
849 Decl *D_next = *next;
850 if (!D_next)
851 break;
852 SourceLocation L = D_next->getLocStart();
853 if (!L.isValid())
854 break;
855 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
856 *DI_current = next;
857 DeclsInContainer.push_back(D_next);
858 continue;
859 }
860 break;
861 }
862 }
863
864 // The common case.
865 if (DeclsInContainer.empty())
866 return VisitDeclContext(D);
867
868 // Get all the Decls in the DeclContext, and sort them with the
869 // additional ones we've collected. Then visit them.
870 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
871 I!=E; ++I) {
872 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000873 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
874 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000875 continue;
876 DeclsInContainer.push_back(subDecl);
877 }
878
879 // Now sort the Decls so that they appear in lexical order.
880 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
881 ContainerDeclsSort(SM));
882
883 // Now visit the decls.
884 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
885 E = DeclsInContainer.end(); I != E; ++I) {
886 CXCursor Cursor = MakeCXCursor(*I, TU);
887 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
888 if (!V.hasValue())
889 continue;
890 if (!V.getValue())
891 return false;
892 if (Visit(Cursor, true))
893 return true;
894 }
895 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000896}
897
Douglas Gregorb1373d02010-01-20 20:59:29 +0000898bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000899 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
900 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000901 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000902
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000903 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
904 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
905 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000906 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000907 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000908
Douglas Gregora59e3902010-01-21 23:27:09 +0000909 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000910}
911
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000912bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
913 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
914 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
915 E = PID->protocol_end(); I != E; ++I, ++PL)
916 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
917 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000918
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000919 return VisitObjCContainerDecl(PID);
920}
921
Ted Kremenek23173d72010-05-18 21:09:07 +0000922bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000923 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000924 return true;
925
Ted Kremenek23173d72010-05-18 21:09:07 +0000926 // FIXME: This implements a workaround with @property declarations also being
927 // installed in the DeclContext for the @interface. Eventually this code
928 // should be removed.
929 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
930 if (!CDecl || !CDecl->IsClassExtension())
931 return false;
932
933 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
934 if (!ID)
935 return false;
936
937 IdentifierInfo *PropertyId = PD->getIdentifier();
938 ObjCPropertyDecl *prevDecl =
939 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
940
941 if (!prevDecl)
942 return false;
943
944 // Visit synthesized methods since they will be skipped when visiting
945 // the @interface.
946 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000947 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000948 if (Visit(MakeCXCursor(MD, TU)))
949 return true;
950
951 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000952 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000953 if (Visit(MakeCXCursor(MD, TU)))
954 return true;
955
956 return false;
957}
958
Douglas Gregorb1373d02010-01-20 20:59:29 +0000959bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000960 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000961 if (D->getSuperClass() &&
962 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000963 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000964 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000965 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000966
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000967 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
968 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
969 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000970 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000971 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000972
Douglas Gregora59e3902010-01-21 23:27:09 +0000973 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000974}
975
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000976bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
977 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000978}
979
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000980bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000981 // 'ID' could be null when dealing with invalid code.
982 if (ObjCInterfaceDecl *ID = D->getClassInterface())
983 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
984 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000985
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000986 return VisitObjCImplDecl(D);
987}
988
989bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
990#if 0
991 // Issue callbacks for super class.
992 // FIXME: No source location information!
993 if (D->getSuperClass() &&
994 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000995 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000996 TU)))
997 return true;
998#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000999
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001000 return VisitObjCImplDecl(D);
1001}
1002
1003bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1004 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1005 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1006 E = D->protocol_end();
1007 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001008 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001009 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001010
1011 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001012}
1013
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001014bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1015 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1016 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1017 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001018
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001019 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001020}
1021
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001022bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1023 return VisitDeclContext(D);
1024}
1025
Douglas Gregor69319002010-08-31 23:48:11 +00001026bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001027 // Visit nested-name-specifier.
1028 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1029 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1030 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001031
1032 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1033 D->getTargetNameLoc(), TU));
1034}
1035
Douglas Gregor7e242562010-09-01 19:52:22 +00001036bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001037 // Visit nested-name-specifier.
1038 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1039 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1040 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001041
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001042 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1043 return true;
1044
Douglas Gregor7e242562010-09-01 19:52:22 +00001045 return VisitDeclarationNameInfo(D->getNameInfo());
1046}
1047
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001048bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001049 // Visit nested-name-specifier.
1050 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1051 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1052 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001053
1054 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1055 D->getIdentLocation(), TU));
1056}
1057
Douglas Gregor7e242562010-09-01 19:52:22 +00001058bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001059 // Visit nested-name-specifier.
1060 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1061 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1062 return true;
1063
Douglas Gregor7e242562010-09-01 19:52:22 +00001064 return VisitDeclarationNameInfo(D->getNameInfo());
1065}
1066
1067bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1068 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001069 // Visit nested-name-specifier.
1070 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1071 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1072 return true;
1073
Douglas Gregor7e242562010-09-01 19:52:22 +00001074 return false;
1075}
1076
Douglas Gregor01829d32010-08-31 14:41:23 +00001077bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1078 switch (Name.getName().getNameKind()) {
1079 case clang::DeclarationName::Identifier:
1080 case clang::DeclarationName::CXXLiteralOperatorName:
1081 case clang::DeclarationName::CXXOperatorName:
1082 case clang::DeclarationName::CXXUsingDirective:
1083 return false;
1084
1085 case clang::DeclarationName::CXXConstructorName:
1086 case clang::DeclarationName::CXXDestructorName:
1087 case clang::DeclarationName::CXXConversionFunctionName:
1088 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1089 return Visit(TSInfo->getTypeLoc());
1090 return false;
1091
1092 case clang::DeclarationName::ObjCZeroArgSelector:
1093 case clang::DeclarationName::ObjCOneArgSelector:
1094 case clang::DeclarationName::ObjCMultiArgSelector:
1095 // FIXME: Per-identifier location info?
1096 return false;
1097 }
1098
1099 return false;
1100}
1101
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001102bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1103 SourceRange Range) {
1104 // FIXME: This whole routine is a hack to work around the lack of proper
1105 // source information in nested-name-specifiers (PR5791). Since we do have
1106 // a beginning source location, we can visit the first component of the
1107 // nested-name-specifier, if it's a single-token component.
1108 if (!NNS)
1109 return false;
1110
1111 // Get the first component in the nested-name-specifier.
1112 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1113 NNS = Prefix;
1114
1115 switch (NNS->getKind()) {
1116 case NestedNameSpecifier::Namespace:
1117 // FIXME: The token at this source location might actually have been a
1118 // namespace alias, but we don't model that. Lame!
1119 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1120 TU));
1121
1122 case NestedNameSpecifier::TypeSpec: {
1123 // If the type has a form where we know that the beginning of the source
1124 // range matches up with a reference cursor. Visit the appropriate reference
1125 // cursor.
1126 Type *T = NNS->getAsType();
1127 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1128 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1129 if (const TagType *Tag = dyn_cast<TagType>(T))
1130 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1131 if (const TemplateSpecializationType *TST
1132 = dyn_cast<TemplateSpecializationType>(T))
1133 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1134 break;
1135 }
1136
1137 case NestedNameSpecifier::TypeSpecWithTemplate:
1138 case NestedNameSpecifier::Global:
1139 case NestedNameSpecifier::Identifier:
1140 break;
1141 }
1142
1143 return false;
1144}
1145
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001146bool CursorVisitor::VisitTemplateParameters(
1147 const TemplateParameterList *Params) {
1148 if (!Params)
1149 return false;
1150
1151 for (TemplateParameterList::const_iterator P = Params->begin(),
1152 PEnd = Params->end();
1153 P != PEnd; ++P) {
1154 if (Visit(MakeCXCursor(*P, TU)))
1155 return true;
1156 }
1157
1158 return false;
1159}
1160
Douglas Gregor0b36e612010-08-31 20:37:03 +00001161bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1162 switch (Name.getKind()) {
1163 case TemplateName::Template:
1164 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1165
1166 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001167 // Visit the overloaded template set.
1168 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1169 return true;
1170
Douglas Gregor0b36e612010-08-31 20:37:03 +00001171 return false;
1172
1173 case TemplateName::DependentTemplate:
1174 // FIXME: Visit nested-name-specifier.
1175 return false;
1176
1177 case TemplateName::QualifiedTemplate:
1178 // FIXME: Visit nested-name-specifier.
1179 return Visit(MakeCursorTemplateRef(
1180 Name.getAsQualifiedTemplateName()->getDecl(),
1181 Loc, TU));
1182 }
1183
1184 return false;
1185}
1186
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001187bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1188 switch (TAL.getArgument().getKind()) {
1189 case TemplateArgument::Null:
1190 case TemplateArgument::Integral:
1191 return false;
1192
1193 case TemplateArgument::Pack:
1194 // FIXME: Implement when variadic templates come along.
1195 return false;
1196
1197 case TemplateArgument::Type:
1198 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1199 return Visit(TSInfo->getTypeLoc());
1200 return false;
1201
1202 case TemplateArgument::Declaration:
1203 if (Expr *E = TAL.getSourceDeclExpression())
1204 return Visit(MakeCXCursor(E, StmtParent, TU));
1205 return false;
1206
1207 case TemplateArgument::Expression:
1208 if (Expr *E = TAL.getSourceExpression())
1209 return Visit(MakeCXCursor(E, StmtParent, TU));
1210 return false;
1211
1212 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001213 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1214 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001215 }
1216
1217 return false;
1218}
1219
Ted Kremeneka0536d82010-05-07 01:04:29 +00001220bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1221 return VisitDeclContext(D);
1222}
1223
Douglas Gregor01829d32010-08-31 14:41:23 +00001224bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1225 return Visit(TL.getUnqualifiedLoc());
1226}
1227
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001228bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1229 ASTContext &Context = TU->getASTContext();
1230
1231 // Some builtin types (such as Objective-C's "id", "sel", and
1232 // "Class") have associated declarations. Create cursors for those.
1233 QualType VisitType;
1234 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001235 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001236 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001237 case BuiltinType::Char_U:
1238 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001239 case BuiltinType::Char16:
1240 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001241 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001242 case BuiltinType::UInt:
1243 case BuiltinType::ULong:
1244 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001245 case BuiltinType::UInt128:
1246 case BuiltinType::Char_S:
1247 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001248 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001249 case BuiltinType::Short:
1250 case BuiltinType::Int:
1251 case BuiltinType::Long:
1252 case BuiltinType::LongLong:
1253 case BuiltinType::Int128:
1254 case BuiltinType::Float:
1255 case BuiltinType::Double:
1256 case BuiltinType::LongDouble:
1257 case BuiltinType::NullPtr:
1258 case BuiltinType::Overload:
1259 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001260 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001261
1262 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001263 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001264
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001265 case BuiltinType::ObjCId:
1266 VisitType = Context.getObjCIdType();
1267 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001268
1269 case BuiltinType::ObjCClass:
1270 VisitType = Context.getObjCClassType();
1271 break;
1272
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001273 case BuiltinType::ObjCSel:
1274 VisitType = Context.getObjCSelType();
1275 break;
1276 }
1277
1278 if (!VisitType.isNull()) {
1279 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001280 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001281 TU));
1282 }
1283
1284 return false;
1285}
1286
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001287bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1288 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1289}
1290
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001291bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1292 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1293}
1294
1295bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1296 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1297}
1298
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001299bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001300 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001301 // no context information with which we can match up the depth/index in the
1302 // type to the appropriate
1303 return false;
1304}
1305
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001306bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1307 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1308 return true;
1309
John McCallc12c5bb2010-05-15 11:32:37 +00001310 return false;
1311}
1312
1313bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1314 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1315 return true;
1316
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001317 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1318 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1319 TU)))
1320 return true;
1321 }
1322
1323 return false;
1324}
1325
1326bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001327 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001328}
1329
1330bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1331 return Visit(TL.getPointeeLoc());
1332}
1333
1334bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1335 return Visit(TL.getPointeeLoc());
1336}
1337
1338bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1339 return Visit(TL.getPointeeLoc());
1340}
1341
1342bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001343 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001344}
1345
1346bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001347 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001348}
1349
Douglas Gregor01829d32010-08-31 14:41:23 +00001350bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1351 bool SkipResultType) {
1352 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001353 return true;
1354
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001355 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001356 if (Decl *D = TL.getArg(I))
1357 if (Visit(MakeCXCursor(D, TU)))
1358 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001359
1360 return false;
1361}
1362
1363bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1364 if (Visit(TL.getElementLoc()))
1365 return true;
1366
1367 if (Expr *Size = TL.getSizeExpr())
1368 return Visit(MakeCXCursor(Size, StmtParent, TU));
1369
1370 return false;
1371}
1372
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001373bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1374 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001375 // Visit the template name.
1376 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1377 TL.getTemplateNameLoc()))
1378 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001379
1380 // Visit the template arguments.
1381 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1382 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1383 return true;
1384
1385 return false;
1386}
1387
Douglas Gregor2332c112010-01-21 20:48:56 +00001388bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1389 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1390}
1391
1392bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1393 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1394 return Visit(TSInfo->getTypeLoc());
1395
1396 return false;
1397}
1398
Douglas Gregora59e3902010-01-21 23:27:09 +00001399bool CursorVisitor::VisitStmt(Stmt *S) {
1400 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1401 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001402 if (Stmt *C = *Child)
1403 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1404 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001405 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001406
Douglas Gregora59e3902010-01-21 23:27:09 +00001407 return false;
1408}
1409
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001410bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1411 // Specially handle CaseStmts because they can be nested, e.g.:
1412 //
1413 // case 1:
1414 // case 2:
1415 //
1416 // In this case the second CaseStmt is the child of the first. Walking
1417 // these recursively can blow out the stack.
1418 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1419 while (true) {
1420 // Set the Parent field to Cursor, then back to its old value once we're
1421 // done.
1422 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1423
1424 if (Stmt *LHS = S->getLHS())
1425 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1426 return true;
1427 if (Stmt *RHS = S->getRHS())
1428 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1429 return true;
1430 if (Stmt *SubStmt = S->getSubStmt()) {
1431 if (!isa<CaseStmt>(SubStmt))
1432 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1433
1434 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1435 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1436 Cursor = MakeCXCursor(CS, StmtParent, TU);
1437 if (RegionOfInterest.isValid()) {
1438 SourceRange Range = CS->getSourceRange();
1439 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1440 return false;
1441 }
1442
1443 switch (Visitor(Cursor, Parent, ClientData)) {
1444 case CXChildVisit_Break: return true;
1445 case CXChildVisit_Continue: return false;
1446 case CXChildVisit_Recurse:
1447 // Perform tail-recursion manually.
1448 S = CS;
1449 continue;
1450 }
1451 }
1452 return false;
1453 }
1454}
1455
Douglas Gregora59e3902010-01-21 23:27:09 +00001456bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001457 bool isFirst = true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001458 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1459 D != DEnd; ++D) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001460 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001461 return true;
Ted Kremenek007a7c92010-11-01 23:26:51 +00001462 isFirst = false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001463 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001464
Douglas Gregora59e3902010-01-21 23:27:09 +00001465 return false;
1466}
1467
Douglas Gregor36897b02010-09-10 00:22:18 +00001468bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1469 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1470}
1471
Douglas Gregorf5bab412010-01-22 01:00:11 +00001472bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1473 if (VarDecl *Var = S->getConditionVariable()) {
1474 if (Visit(MakeCXCursor(Var, TU)))
1475 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001476 }
1477
Douglas Gregor263b47b2010-01-25 16:12:32 +00001478 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1479 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001480 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1481 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001482 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1483 return true;
1484
1485 return false;
1486}
1487
1488bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1489 if (VarDecl *Var = S->getConditionVariable()) {
1490 if (Visit(MakeCXCursor(Var, TU)))
1491 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001492 }
1493
Douglas Gregor263b47b2010-01-25 16:12:32 +00001494 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1495 return true;
1496 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1497 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001498
Douglas Gregor263b47b2010-01-25 16:12:32 +00001499 return false;
1500}
1501
1502bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1503 if (VarDecl *Var = S->getConditionVariable()) {
1504 if (Visit(MakeCXCursor(Var, TU)))
1505 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001506 }
1507
Douglas Gregor263b47b2010-01-25 16:12:32 +00001508 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1509 return true;
1510 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001511 return true;
1512
Douglas Gregor263b47b2010-01-25 16:12:32 +00001513 return false;
1514}
1515
1516bool CursorVisitor::VisitForStmt(ForStmt *S) {
1517 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1518 return true;
1519 if (VarDecl *Var = S->getConditionVariable()) {
1520 if (Visit(MakeCXCursor(Var, TU)))
1521 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001522 }
1523
Douglas Gregor263b47b2010-01-25 16:12:32 +00001524 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1525 return true;
1526 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1527 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001528 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1529 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001530
Douglas Gregorf5bab412010-01-22 01:00:11 +00001531 return false;
1532}
1533
Ted Kremenek04c450c2010-11-08 21:14:15 +00001534bool CursorVisitor::VisitBinaryOperator(BinaryOperator *B) {
1535 // We can blow the stack in some cases where we have deeply nested BinaryOperators,
1536 // often involving logical expressions, e.g.: '(x || y) || (y || z) || ...
1537 // To handle this, we visitation of BinaryOperators is data recursive instead of
1538 // directly recursive. This makes the algorithm more complicated, but handles
1539 // arbitrary depths. We should consider making the entire CursorVisitor data
1540 // recursive.
1541 typedef std::pair</* Current expression = */ Expr*, /* Parent = */ CXCursor>
1542 WorkListItem;
1543 typedef llvm::SmallVector<WorkListItem, 5> WorkList;
1544
1545 CXCursor Cursor = MakeCXCursor(B, StmtParent, TU);
1546 WorkList WL;
1547 WL.push_back(std::make_pair(B->getRHS(), Cursor));
1548 WL.push_back(std::make_pair(B->getLHS(), Cursor));
1549
1550 while (!WL.empty()) {
1551 // Dequeue the worklist item.
1552 WorkListItem LI = WL.back(); WL.pop_back(); Expr *Ex = LI.first;
1553
1554 // Set the Parent field, then back to its old value once we're done.
1555 SetParentRAII SetParent(Parent, StmtParent, LI.second);
1556
1557 // Update the current cursor.
1558 Cursor = MakeCXCursor(Ex, StmtParent, TU);
1559
1560 // For non-BinaryOperators, perform the default visitation.
1561 if (!isa<BinaryOperator>(Ex)) {
1562 if (Visit(Cursor)) {
1563 // Skip all other items in the worklist that also have
1564 // the same parent.
1565 while (!WL.empty()) {
1566 const WorkListItem &LIb = WL.back();
1567 if (LIb.second == LI.second)
1568 WL.pop_back();
1569 else
1570 break;
1571 }
1572 // If the worklist is now empty, we should immediately return
1573 // to the caller, since this is the base case.
1574 if (WL.empty())
1575 return true;
1576 }
1577 continue;
1578 }
1579 // For BinaryOperators, perform a custom visitation where we add the
1580 // children to a worklist.
1581 if (RegionOfInterest.isValid()) {
1582 SourceRange Range = getRawCursorExtent(Cursor);
1583 if (Range.isInvalid() || CompareRegionOfInterest(Range)) {
1584 // Proceed to the next item on the worklist.
1585 continue;
1586 }
1587 }
1588 switch (Visitor(Cursor, Parent, ClientData)) {
1589 case CXChildVisit_Break: {
1590 // Skip all other items in the worklist that also have
1591 // the same parent.
1592 while (!WL.empty()) {
1593 const WorkListItem &LIb = WL.back();
1594 if (LIb.second == LI.second)
1595 WL.pop_back();
1596 else
1597 break;
1598 }
1599 // If the worklist is now empty, we should immediately return
1600 // to the caller, since this is the base case.
1601 if (WL.empty())
1602 return true;
1603 break;
1604 }
1605 case CXChildVisit_Continue:
1606 break;
1607 case CXChildVisit_Recurse: {
1608 BinaryOperator *B = cast<BinaryOperator>(Ex);
1609 // FIXME: Note that we ignore parentheses, since these are often
1610 // unimportant during cursor visitation. If we care about these, we
1611 // can unroll the visitation one more level. Alternatively, we
1612 // can convert the entire visitor to be data recursive, eliminating
1613 // all edge cases.
1614 WL.push_back(std::make_pair(B->getRHS()->IgnoreParens(), Cursor));
1615 WL.push_back(std::make_pair(B->getLHS()->IgnoreParens(), Cursor));
1616 break;
1617 }
1618 }
1619 }
1620 return false;
1621}
1622
Douglas Gregor8947a752010-09-02 20:35:02 +00001623bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1624 // Visit nested-name-specifier, if present.
1625 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1626 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1627 return true;
1628
1629 // Visit declaration name.
1630 if (VisitDeclarationNameInfo(E->getNameInfo()))
1631 return true;
1632
1633 // Visit explicitly-specified template arguments.
1634 if (E->hasExplicitTemplateArgs()) {
1635 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1636 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1637 *ArgEnd = Arg + Args.NumTemplateArgs;
1638 Arg != ArgEnd; ++Arg)
1639 if (VisitTemplateArgumentLoc(*Arg))
1640 return true;
1641 }
1642
1643 return false;
1644}
1645
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001646bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1647 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1648 return true;
1649
1650 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1651 return true;
1652
1653 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1654 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1655 return true;
1656
1657 return false;
1658}
1659
Ted Kremenek3064ef92010-08-27 21:34:58 +00001660bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1661 if (D->isDefinition()) {
1662 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1663 E = D->bases_end(); I != E; ++I) {
1664 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1665 return true;
1666 }
1667 }
1668
1669 return VisitTagDecl(D);
1670}
1671
1672
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001673bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1674 return Visit(B->getBlockDecl());
1675}
1676
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001677bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001678 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001679 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1680 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001681
1682 // Visit the components of the offsetof expression.
1683 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1684 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1685 const OffsetOfNode &Node = E->getComponent(I);
1686 switch (Node.getKind()) {
1687 case OffsetOfNode::Array:
1688 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1689 StmtParent, TU)))
1690 return true;
1691 break;
1692
1693 case OffsetOfNode::Field:
1694 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1695 TU)))
1696 return true;
1697 break;
1698
1699 case OffsetOfNode::Identifier:
1700 case OffsetOfNode::Base:
1701 continue;
1702 }
1703 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001704
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001705 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001706}
1707
Douglas Gregor336fd812010-01-23 00:40:08 +00001708bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1709 if (E->isArgumentType()) {
1710 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1711 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001712
Douglas Gregor336fd812010-01-23 00:40:08 +00001713 return false;
1714 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001715
Douglas Gregor336fd812010-01-23 00:40:08 +00001716 return VisitExpr(E);
1717}
1718
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001719bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1720 // Visit the base expression.
1721 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1722 return true;
1723
1724 // Visit the nested-name-specifier
1725 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1726 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1727 return true;
1728
1729 // Visit the declaration name.
1730 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1731 return true;
1732
1733 // Visit the explicitly-specified template arguments, if any.
1734 if (E->hasExplicitTemplateArgs()) {
1735 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1736 *ArgEnd = Arg + E->getNumTemplateArgs();
1737 Arg != ArgEnd;
1738 ++Arg) {
1739 if (VisitTemplateArgumentLoc(*Arg))
1740 return true;
1741 }
1742 }
1743
1744 return false;
1745}
1746
Douglas Gregor336fd812010-01-23 00:40:08 +00001747bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1748 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1749 if (Visit(TSInfo->getTypeLoc()))
1750 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001751
Douglas Gregor336fd812010-01-23 00:40:08 +00001752 return VisitCastExpr(E);
1753}
1754
1755bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1756 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1757 if (Visit(TSInfo->getTypeLoc()))
1758 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001759
Douglas Gregor336fd812010-01-23 00:40:08 +00001760 return VisitExpr(E);
1761}
1762
Douglas Gregor36897b02010-09-10 00:22:18 +00001763bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1764 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1765}
1766
Douglas Gregor648220e2010-08-10 15:02:34 +00001767bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1768 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1769 Visit(E->getArgTInfo2()->getTypeLoc());
1770}
1771
1772bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1773 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1774 return true;
1775
1776 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1777}
1778
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001779bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1780 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001781 if (InitListExpr *Syntactic = E->getSyntacticForm())
1782 return VisitExpr(Syntactic);
1783
1784 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001785}
1786
1787bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1788 // Visit the designators.
1789 typedef DesignatedInitExpr::Designator Designator;
1790 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1791 DEnd = E->designators_end();
1792 D != DEnd; ++D) {
1793 if (D->isFieldDesignator()) {
1794 if (FieldDecl *Field = D->getField())
1795 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1796 return true;
1797
1798 continue;
1799 }
1800
1801 if (D->isArrayDesignator()) {
1802 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1803 return true;
1804
1805 continue;
1806 }
1807
1808 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1809 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1810 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1811 return true;
1812 }
1813
1814 // Visit the initializer value itself.
1815 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1816}
1817
Douglas Gregor94802292010-09-02 21:20:16 +00001818bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1819 if (E->isTypeOperand()) {
1820 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1821 return Visit(TSInfo->getTypeLoc());
1822
1823 return false;
1824 }
1825
1826 return VisitExpr(E);
1827}
1828
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001829bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1830 if (E->isTypeOperand()) {
1831 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1832 return Visit(TSInfo->getTypeLoc());
1833
1834 return false;
1835 }
1836
1837 return VisitExpr(E);
1838}
1839
Douglas Gregorab6677e2010-09-08 00:15:04 +00001840bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1841 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
Douglas Gregor40749ee2010-11-03 00:35:38 +00001842 if (Visit(TSInfo->getTypeLoc()))
1843 return true;
Douglas Gregorab6677e2010-09-08 00:15:04 +00001844
1845 return VisitExpr(E);
1846}
1847
1848bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1849 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1850 return Visit(TSInfo->getTypeLoc());
1851
1852 return false;
1853}
1854
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001855bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1856 // Visit placement arguments.
1857 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1858 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1859 return true;
1860
1861 // Visit the allocated type.
1862 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1863 if (Visit(TSInfo->getTypeLoc()))
1864 return true;
1865
1866 // Visit the array size, if any.
1867 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1868 return true;
1869
1870 // Visit the initializer or constructor arguments.
1871 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1872 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1873 return true;
1874
1875 return false;
1876}
1877
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001878bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1879 // Visit base expression.
1880 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1881 return true;
1882
1883 // Visit the nested-name-specifier.
1884 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1885 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1886 return true;
1887
1888 // Visit the scope type that looks disturbingly like the nested-name-specifier
1889 // but isn't.
1890 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1891 if (Visit(TSInfo->getTypeLoc()))
1892 return true;
1893
1894 // Visit the name of the type being destroyed.
1895 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1896 if (Visit(TSInfo->getTypeLoc()))
1897 return true;
1898
1899 return false;
1900}
1901
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001902bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1903 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1904}
1905
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001906bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001907 // Visit the nested-name-specifier.
1908 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1909 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1910 return true;
1911
1912 // Visit the declaration name.
1913 if (VisitDeclarationNameInfo(E->getNameInfo()))
1914 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001915
1916 // Visit the overloaded declaration reference.
1917 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1918 return true;
1919
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001920 // Visit the explicitly-specified template arguments.
1921 if (const ExplicitTemplateArgumentList *ArgList
1922 = E->getOptionalExplicitTemplateArgs()) {
1923 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1924 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1925 Arg != ArgEnd; ++Arg) {
1926 if (VisitTemplateArgumentLoc(*Arg))
1927 return true;
1928 }
1929 }
1930
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001931 return false;
1932}
1933
Douglas Gregorbfebed22010-09-03 17:24:10 +00001934bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1935 DependentScopeDeclRefExpr *E) {
1936 // Visit the nested-name-specifier.
1937 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1938 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1939 return true;
1940
1941 // Visit the declaration name.
1942 if (VisitDeclarationNameInfo(E->getNameInfo()))
1943 return true;
1944
1945 // Visit the explicitly-specified template arguments.
1946 if (const ExplicitTemplateArgumentList *ArgList
1947 = E->getOptionalExplicitTemplateArgs()) {
1948 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1949 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1950 Arg != ArgEnd; ++Arg) {
1951 if (VisitTemplateArgumentLoc(*Arg))
1952 return true;
1953 }
1954 }
1955
1956 return false;
1957}
1958
Douglas Gregorab6677e2010-09-08 00:15:04 +00001959bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1960 CXXUnresolvedConstructExpr *E) {
1961 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1962 if (Visit(TSInfo->getTypeLoc()))
1963 return true;
1964
1965 return VisitExpr(E);
1966}
1967
Douglas Gregor25d63622010-09-03 17:35:34 +00001968bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1969 CXXDependentScopeMemberExpr *E) {
1970 // Visit the base expression, if there is one.
1971 if (!E->isImplicitAccess() &&
1972 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1973 return true;
1974
1975 // Visit the nested-name-specifier.
1976 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1977 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1978 return true;
1979
1980 // Visit the declaration name.
1981 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1982 return true;
1983
1984 // Visit the explicitly-specified template arguments.
1985 if (const ExplicitTemplateArgumentList *ArgList
1986 = E->getOptionalExplicitTemplateArgs()) {
1987 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1988 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1989 Arg != ArgEnd; ++Arg) {
1990 if (VisitTemplateArgumentLoc(*Arg))
1991 return true;
1992 }
1993 }
1994
1995 return false;
1996}
1997
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001998bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1999 // Visit the base expression, if there is one.
2000 if (!E->isImplicitAccess() &&
2001 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
2002 return true;
2003
2004 return VisitOverloadExpr(E);
2005}
Douglas Gregor25d63622010-09-03 17:35:34 +00002006
Douglas Gregorc2350e52010-03-08 16:40:19 +00002007bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002008 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
2009 if (Visit(TSInfo->getTypeLoc()))
2010 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00002011
2012 return VisitExpr(E);
2013}
2014
Douglas Gregor81d34662010-04-20 15:39:42 +00002015bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2016 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
2017}
2018
2019
Ted Kremenek09dfa372010-02-18 05:46:33 +00002020bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00002021 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
2022 i != e; ++i)
2023 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00002024 return true;
2025
2026 return false;
2027}
2028
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002029static llvm::sys::Mutex EnableMultithreadingMutex;
2030static bool EnabledMultithreading;
2031
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002032extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002033CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2034 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002035 // Disable pretty stack trace functionality, which will otherwise be a very
2036 // poor citizen of the world and set up all sorts of signal handlers.
2037 llvm::DisablePrettyStackTrace = true;
2038
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002039 // We use crash recovery to make some of our APIs more reliable, implicitly
2040 // enable it.
2041 llvm::CrashRecoveryContext::Enable();
2042
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002043 // Enable support for multithreading in LLVM.
2044 {
2045 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2046 if (!EnabledMultithreading) {
2047 llvm::llvm_start_multithreaded();
2048 EnabledMultithreading = true;
2049 }
2050 }
2051
Douglas Gregora030b7c2010-01-22 20:35:53 +00002052 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002053 if (excludeDeclarationsFromPCH)
2054 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002055 if (displayDiagnostics)
2056 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002057 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002058}
2059
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002060void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002061 if (CIdx)
2062 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002063}
2064
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002065CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002066 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002067 if (!CIdx)
2068 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002069
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002070 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002071 FileSystemOptions FileSystemOpts;
2072 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002073
Douglas Gregor28019772010-04-05 23:52:57 +00002074 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002075 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002076 CXXIdx->getOnlyLocalDecls(),
2077 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002078}
2079
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002080unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002081 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002082 CXTranslationUnit_CacheCompletionResults |
2083 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002084}
2085
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002086CXTranslationUnit
2087clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2088 const char *source_filename,
2089 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002090 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002091 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002092 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002093 return clang_parseTranslationUnit(CIdx, source_filename,
2094 command_line_args, num_command_line_args,
2095 unsaved_files, num_unsaved_files,
2096 CXTranslationUnit_DetailedPreprocessingRecord);
2097}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002098
2099struct ParseTranslationUnitInfo {
2100 CXIndex CIdx;
2101 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002102 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002103 int num_command_line_args;
2104 struct CXUnsavedFile *unsaved_files;
2105 unsigned num_unsaved_files;
2106 unsigned options;
2107 CXTranslationUnit result;
2108};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002109static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002110 ParseTranslationUnitInfo *PTUI =
2111 static_cast<ParseTranslationUnitInfo*>(UserData);
2112 CXIndex CIdx = PTUI->CIdx;
2113 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002114 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002115 int num_command_line_args = PTUI->num_command_line_args;
2116 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2117 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2118 unsigned options = PTUI->options;
2119 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002120
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002121 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002122 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002123
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002124 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2125
Douglas Gregor44c181a2010-07-23 00:33:23 +00002126 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002127 bool CompleteTranslationUnit
2128 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002129 bool CacheCodeCompetionResults
2130 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002131 bool CXXPrecompilePreamble
2132 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2133 bool CXXChainedPCH
2134 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002135
Douglas Gregor5352ac02010-01-28 00:27:43 +00002136 // Configure the diagnostics.
2137 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002138 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2139 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002140
Douglas Gregor4db64a42010-01-23 00:14:00 +00002141 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2142 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002143 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002144 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002145 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002146 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2147 Buffer));
2148 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002149
Douglas Gregorb10daed2010-10-11 16:52:23 +00002150 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002151
Ted Kremenek139ba862009-10-22 00:03:57 +00002152 // The 'source_filename' argument is optional. If the caller does not
2153 // specify it then it is assumed that the source file is specified
2154 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002155 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002156 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002157
2158 // Since the Clang C library is primarily used by batch tools dealing with
2159 // (often very broken) source code, where spell-checking can have a
2160 // significant negative impact on performance (particularly when
2161 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002162 // Only do this if we haven't found a spell-checking-related argument.
2163 bool FoundSpellCheckingArgument = false;
2164 for (int I = 0; I != num_command_line_args; ++I) {
2165 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2166 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2167 FoundSpellCheckingArgument = true;
2168 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002169 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002170 }
2171 if (!FoundSpellCheckingArgument)
2172 Args.push_back("-fno-spell-checking");
2173
2174 Args.insert(Args.end(), command_line_args,
2175 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002176
Douglas Gregor44c181a2010-07-23 00:33:23 +00002177 // Do we need the detailed preprocessing record?
2178 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002179 Args.push_back("-Xclang");
2180 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002181 }
2182
Douglas Gregorb10daed2010-10-11 16:52:23 +00002183 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002184 llvm::OwningPtr<ASTUnit> Unit(
2185 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2186 Diags,
2187 CXXIdx->getClangResourcesPath(),
2188 CXXIdx->getOnlyLocalDecls(),
2189 RemappedFiles.data(),
2190 RemappedFiles.size(),
2191 /*CaptureDiagnostics=*/true,
2192 PrecompilePreamble,
2193 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002194 CacheCodeCompetionResults,
2195 CXXPrecompilePreamble,
2196 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002197
Douglas Gregorb10daed2010-10-11 16:52:23 +00002198 if (NumErrors != Diags->getNumErrors()) {
2199 // Make sure to check that 'Unit' is non-NULL.
2200 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2201 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2202 DEnd = Unit->stored_diag_end();
2203 D != DEnd; ++D) {
2204 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2205 CXString Msg = clang_formatDiagnostic(&Diag,
2206 clang_defaultDiagnosticDisplayOptions());
2207 fprintf(stderr, "%s\n", clang_getCString(Msg));
2208 clang_disposeString(Msg);
2209 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002210#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002211 // On Windows, force a flush, since there may be multiple copies of
2212 // stderr and stdout in the file system, all with different buffers
2213 // but writing to the same device.
2214 fflush(stderr);
2215#endif
2216 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002217 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002218
Douglas Gregorb10daed2010-10-11 16:52:23 +00002219 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002220}
2221CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2222 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002223 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002224 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002225 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002226 unsigned num_unsaved_files,
2227 unsigned options) {
2228 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002229 num_command_line_args, unsaved_files,
2230 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002231 llvm::CrashRecoveryContext CRC;
2232
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002233 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002234 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2235 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2236 fprintf(stderr, " 'command_line_args' : [");
2237 for (int i = 0; i != num_command_line_args; ++i) {
2238 if (i)
2239 fprintf(stderr, ", ");
2240 fprintf(stderr, "'%s'", command_line_args[i]);
2241 }
2242 fprintf(stderr, "],\n");
2243 fprintf(stderr, " 'unsaved_files' : [");
2244 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2245 if (i)
2246 fprintf(stderr, ", ");
2247 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2248 unsaved_files[i].Length);
2249 }
2250 fprintf(stderr, "],\n");
2251 fprintf(stderr, " 'options' : %d,\n", options);
2252 fprintf(stderr, "}\n");
2253
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002254 return 0;
2255 }
2256
2257 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002258}
2259
Douglas Gregor19998442010-08-13 15:35:05 +00002260unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2261 return CXSaveTranslationUnit_None;
2262}
2263
2264int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2265 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002266 if (!TU)
2267 return 1;
2268
2269 return static_cast<ASTUnit *>(TU)->Save(FileName);
2270}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002271
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002272void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002273 if (CTUnit) {
2274 // If the translation unit has been marked as unsafe to free, just discard
2275 // it.
2276 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2277 return;
2278
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002279 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002280 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002281}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002282
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002283unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2284 return CXReparse_None;
2285}
2286
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002287struct ReparseTranslationUnitInfo {
2288 CXTranslationUnit TU;
2289 unsigned num_unsaved_files;
2290 struct CXUnsavedFile *unsaved_files;
2291 unsigned options;
2292 int result;
2293};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002294
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002295static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002296 ReparseTranslationUnitInfo *RTUI =
2297 static_cast<ReparseTranslationUnitInfo*>(UserData);
2298 CXTranslationUnit TU = RTUI->TU;
2299 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2300 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2301 unsigned options = RTUI->options;
2302 (void) options;
2303 RTUI->result = 1;
2304
Douglas Gregorabc563f2010-07-19 21:46:24 +00002305 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002306 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002307
2308 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2309 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002310
2311 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2312 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2313 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2314 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002315 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002316 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2317 Buffer));
2318 }
2319
Douglas Gregor593b0c12010-09-23 18:47:53 +00002320 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2321 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002322}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002323
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002324int clang_reparseTranslationUnit(CXTranslationUnit TU,
2325 unsigned num_unsaved_files,
2326 struct CXUnsavedFile *unsaved_files,
2327 unsigned options) {
2328 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2329 options, 0 };
2330 llvm::CrashRecoveryContext CRC;
2331
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002332 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002333 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002334 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2335 return 1;
2336 }
2337
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002338
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002339 return RTUI.result;
2340}
2341
Douglas Gregordf95a132010-08-09 20:45:32 +00002342
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002343CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002344 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002345 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002346
Steve Naroff77accc12009-09-03 18:19:54 +00002347 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002348 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002349}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002350
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002351CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002352 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002353 return Result;
2354}
2355
Ted Kremenekfb480492010-01-13 21:46:36 +00002356} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002357
Ted Kremenekfb480492010-01-13 21:46:36 +00002358//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002359// CXSourceLocation and CXSourceRange Operations.
2360//===----------------------------------------------------------------------===//
2361
Douglas Gregorb9790342010-01-22 21:44:22 +00002362extern "C" {
2363CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002364 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002365 return Result;
2366}
2367
2368unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002369 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2370 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2371 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002372}
2373
2374CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2375 CXFile file,
2376 unsigned line,
2377 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002378 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002379 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002380
Douglas Gregorb9790342010-01-22 21:44:22 +00002381 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2382 SourceLocation SLoc
2383 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002384 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002385 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002386 if (SLoc.isInvalid()) return clang_getNullLocation();
2387
2388 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2389}
2390
2391CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2392 CXFile file,
2393 unsigned offset) {
2394 if (!tu || !file)
2395 return clang_getNullLocation();
2396
2397 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2398 SourceLocation Start
2399 = CXXUnit->getSourceManager().getLocation(
2400 static_cast<const FileEntry *>(file),
2401 1, 1);
2402 if (Start.isInvalid()) return clang_getNullLocation();
2403
2404 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2405
2406 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002407
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002408 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002409}
2410
Douglas Gregor5352ac02010-01-28 00:27:43 +00002411CXSourceRange clang_getNullRange() {
2412 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2413 return Result;
2414}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002415
Douglas Gregor5352ac02010-01-28 00:27:43 +00002416CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2417 if (begin.ptr_data[0] != end.ptr_data[0] ||
2418 begin.ptr_data[1] != end.ptr_data[1])
2419 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002420
2421 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002422 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002423 return Result;
2424}
2425
Douglas Gregor46766dc2010-01-26 19:19:08 +00002426void clang_getInstantiationLocation(CXSourceLocation location,
2427 CXFile *file,
2428 unsigned *line,
2429 unsigned *column,
2430 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002431 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2432
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002433 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002434 if (file)
2435 *file = 0;
2436 if (line)
2437 *line = 0;
2438 if (column)
2439 *column = 0;
2440 if (offset)
2441 *offset = 0;
2442 return;
2443 }
2444
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002445 const SourceManager &SM =
2446 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002447 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002448
2449 if (file)
2450 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2451 if (line)
2452 *line = SM.getInstantiationLineNumber(InstLoc);
2453 if (column)
2454 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002455 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002456 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002457}
2458
Douglas Gregorb6278712010-11-09 05:28:47 +00002459void clang_getSpellingLocation(CXSourceLocation location,
2460 CXFile *file,
2461 unsigned *line,
2462 unsigned *column,
2463 unsigned *offset) {
2464 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2465
2466 if (!location.ptr_data[0] || Loc.isInvalid()) {
2467 if (file)
2468 *file = 0;
2469 if (line)
2470 *line = 0;
2471 if (column)
2472 *column = 0;
2473 if (offset)
2474 *offset = 0;
2475 return;
2476 }
2477
2478 const SourceManager &SM =
2479 *static_cast<const SourceManager*>(location.ptr_data[0]);
2480 SourceLocation SpellLoc = SM.getSpellingLoc(Loc);
2481 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2482 FileID FID = LocInfo.first;
2483 unsigned FileOffset = LocInfo.second;
2484
2485 if (file)
2486 *file = (void *)SM.getFileEntryForID(FID);
2487 if (line)
2488 *line = SM.getLineNumber(FID, FileOffset);
2489 if (column)
2490 *column = SM.getColumnNumber(FID, FileOffset);
2491 if (offset)
2492 *offset = FileOffset;
2493}
2494
Douglas Gregor1db19de2010-01-19 21:36:55 +00002495CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002496 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002497 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002498 return Result;
2499}
2500
2501CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002502 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002503 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002504 return Result;
2505}
2506
Douglas Gregorb9790342010-01-22 21:44:22 +00002507} // end: extern "C"
2508
Douglas Gregor1db19de2010-01-19 21:36:55 +00002509//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002510// CXFile Operations.
2511//===----------------------------------------------------------------------===//
2512
2513extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002514CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002515 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002516 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002517
Steve Naroff88145032009-10-27 14:35:18 +00002518 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002519 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002520}
2521
2522time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002523 if (!SFile)
2524 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002525
Steve Naroff88145032009-10-27 14:35:18 +00002526 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2527 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002528}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002529
Douglas Gregorb9790342010-01-22 21:44:22 +00002530CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2531 if (!tu)
2532 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002533
Douglas Gregorb9790342010-01-22 21:44:22 +00002534 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002535
Douglas Gregorb9790342010-01-22 21:44:22 +00002536 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002537 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2538 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002539 return const_cast<FileEntry *>(File);
2540}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002541
Ted Kremenekfb480492010-01-13 21:46:36 +00002542} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002543
Ted Kremenekfb480492010-01-13 21:46:36 +00002544//===----------------------------------------------------------------------===//
2545// CXCursor Operations.
2546//===----------------------------------------------------------------------===//
2547
Ted Kremenekfb480492010-01-13 21:46:36 +00002548static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002549 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2550 return getDeclFromExpr(CE->getSubExpr());
2551
Ted Kremenekfb480492010-01-13 21:46:36 +00002552 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2553 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002554 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2555 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002556 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2557 return ME->getMemberDecl();
2558 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2559 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002560 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2561 return PRE->getProperty();
2562
Ted Kremenekfb480492010-01-13 21:46:36 +00002563 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2564 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002565 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2566 if (!CE->isElidable())
2567 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002568 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2569 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002570
Douglas Gregordb1314e2010-10-01 21:11:22 +00002571 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2572 return PE->getProtocol();
2573
Ted Kremenekfb480492010-01-13 21:46:36 +00002574 return 0;
2575}
2576
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002577static SourceLocation getLocationFromExpr(Expr *E) {
2578 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2579 return /*FIXME:*/Msg->getLeftLoc();
2580 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2581 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002582 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2583 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002584 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2585 return Member->getMemberLoc();
2586 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2587 return Ivar->getLocation();
2588 return E->getLocStart();
2589}
2590
Ted Kremenekfb480492010-01-13 21:46:36 +00002591extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002592
2593unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002594 CXCursorVisitor visitor,
2595 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002596 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002597
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002598 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2599 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002600 return CursorVis.VisitChildren(parent);
2601}
2602
David Chisnall3387c652010-11-03 14:12:26 +00002603#ifndef __has_feature
2604#define __has_feature(x) 0
2605#endif
2606#if __has_feature(blocks)
2607typedef enum CXChildVisitResult
2608 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2609
2610static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2611 CXClientData client_data) {
2612 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2613 return block(cursor, parent);
2614}
2615#else
2616// If we are compiled with a compiler that doesn't have native blocks support,
2617// define and call the block manually, so the
2618typedef struct _CXChildVisitResult
2619{
2620 void *isa;
2621 int flags;
2622 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002623 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2624 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002625} *CXCursorVisitorBlock;
2626
2627static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2628 CXClientData client_data) {
2629 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2630 return block->invoke(block, cursor, parent);
2631}
2632#endif
2633
2634
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002635unsigned clang_visitChildrenWithBlock(CXCursor parent,
2636 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002637 return clang_visitChildren(parent, visitWithBlock, block);
2638}
2639
Douglas Gregor78205d42010-01-20 21:45:58 +00002640static CXString getDeclSpelling(Decl *D) {
2641 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2642 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002643 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002644
Douglas Gregor78205d42010-01-20 21:45:58 +00002645 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002646 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002647
Douglas Gregor78205d42010-01-20 21:45:58 +00002648 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2649 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2650 // and returns different names. NamedDecl returns the class name and
2651 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002652 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002653
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002654 if (isa<UsingDirectiveDecl>(D))
2655 return createCXString("");
2656
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002657 llvm::SmallString<1024> S;
2658 llvm::raw_svector_ostream os(S);
2659 ND->printName(os);
2660
2661 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002662}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002663
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002664CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002665 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002666 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002667
Steve Narofff334b4e2009-09-02 18:26:48 +00002668 if (clang_isReference(C.kind)) {
2669 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002670 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002671 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002672 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002673 }
2674 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002675 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002676 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002677 }
2678 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002679 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002680 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002681 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002682 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002683 case CXCursor_CXXBaseSpecifier: {
2684 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2685 return createCXString(B->getType().getAsString());
2686 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002687 case CXCursor_TypeRef: {
2688 TypeDecl *Type = getCursorTypeRef(C).first;
2689 assert(Type && "Missing type decl");
2690
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002691 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2692 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002693 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002694 case CXCursor_TemplateRef: {
2695 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002696 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002697
2698 return createCXString(Template->getNameAsString());
2699 }
Douglas Gregor69319002010-08-31 23:48:11 +00002700
2701 case CXCursor_NamespaceRef: {
2702 NamedDecl *NS = getCursorNamespaceRef(C).first;
2703 assert(NS && "Missing namespace decl");
2704
2705 return createCXString(NS->getNameAsString());
2706 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002707
Douglas Gregora67e03f2010-09-09 21:42:20 +00002708 case CXCursor_MemberRef: {
2709 FieldDecl *Field = getCursorMemberRef(C).first;
2710 assert(Field && "Missing member decl");
2711
2712 return createCXString(Field->getNameAsString());
2713 }
2714
Douglas Gregor36897b02010-09-10 00:22:18 +00002715 case CXCursor_LabelRef: {
2716 LabelStmt *Label = getCursorLabelRef(C).first;
2717 assert(Label && "Missing label");
2718
2719 return createCXString(Label->getID()->getName());
2720 }
2721
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002722 case CXCursor_OverloadedDeclRef: {
2723 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2724 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2725 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2726 return createCXString(ND->getNameAsString());
2727 return createCXString("");
2728 }
2729 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2730 return createCXString(E->getName().getAsString());
2731 OverloadedTemplateStorage *Ovl
2732 = Storage.get<OverloadedTemplateStorage*>();
2733 if (Ovl->size() == 0)
2734 return createCXString("");
2735 return createCXString((*Ovl->begin())->getNameAsString());
2736 }
2737
Daniel Dunbaracca7252009-11-30 20:42:49 +00002738 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002739 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002740 }
2741 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002742
2743 if (clang_isExpression(C.kind)) {
2744 Decl *D = getDeclFromExpr(getCursorExpr(C));
2745 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002746 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002747 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002748 }
2749
Douglas Gregor36897b02010-09-10 00:22:18 +00002750 if (clang_isStatement(C.kind)) {
2751 Stmt *S = getCursorStmt(C);
2752 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2753 return createCXString(Label->getID()->getName());
2754
2755 return createCXString("");
2756 }
2757
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002758 if (C.kind == CXCursor_MacroInstantiation)
2759 return createCXString(getCursorMacroInstantiation(C)->getName()
2760 ->getNameStart());
2761
Douglas Gregor572feb22010-03-18 18:04:21 +00002762 if (C.kind == CXCursor_MacroDefinition)
2763 return createCXString(getCursorMacroDefinition(C)->getName()
2764 ->getNameStart());
2765
Douglas Gregorecdcb882010-10-20 22:00:55 +00002766 if (C.kind == CXCursor_InclusionDirective)
2767 return createCXString(getCursorInclusionDirective(C)->getFileName());
2768
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002769 if (clang_isDeclaration(C.kind))
2770 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002771
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002772 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002773}
2774
Douglas Gregor358559d2010-10-02 22:49:11 +00002775CXString clang_getCursorDisplayName(CXCursor C) {
2776 if (!clang_isDeclaration(C.kind))
2777 return clang_getCursorSpelling(C);
2778
2779 Decl *D = getCursorDecl(C);
2780 if (!D)
2781 return createCXString("");
2782
2783 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2784 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2785 D = FunTmpl->getTemplatedDecl();
2786
2787 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2788 llvm::SmallString<64> Str;
2789 llvm::raw_svector_ostream OS(Str);
2790 OS << Function->getNameAsString();
2791 if (Function->getPrimaryTemplate())
2792 OS << "<>";
2793 OS << "(";
2794 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2795 if (I)
2796 OS << ", ";
2797 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2798 }
2799
2800 if (Function->isVariadic()) {
2801 if (Function->getNumParams())
2802 OS << ", ";
2803 OS << "...";
2804 }
2805 OS << ")";
2806 return createCXString(OS.str());
2807 }
2808
2809 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2810 llvm::SmallString<64> Str;
2811 llvm::raw_svector_ostream OS(Str);
2812 OS << ClassTemplate->getNameAsString();
2813 OS << "<";
2814 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2815 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2816 if (I)
2817 OS << ", ";
2818
2819 NamedDecl *Param = Params->getParam(I);
2820 if (Param->getIdentifier()) {
2821 OS << Param->getIdentifier()->getName();
2822 continue;
2823 }
2824
2825 // There is no parameter name, which makes this tricky. Try to come up
2826 // with something useful that isn't too long.
2827 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2828 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2829 else if (NonTypeTemplateParmDecl *NTTP
2830 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2831 OS << NTTP->getType().getAsString(Policy);
2832 else
2833 OS << "template<...> class";
2834 }
2835
2836 OS << ">";
2837 return createCXString(OS.str());
2838 }
2839
2840 if (ClassTemplateSpecializationDecl *ClassSpec
2841 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2842 // If the type was explicitly written, use that.
2843 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2844 return createCXString(TSInfo->getType().getAsString(Policy));
2845
2846 llvm::SmallString<64> Str;
2847 llvm::raw_svector_ostream OS(Str);
2848 OS << ClassSpec->getNameAsString();
2849 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002850 ClassSpec->getTemplateArgs().data(),
2851 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002852 Policy);
2853 return createCXString(OS.str());
2854 }
2855
2856 return clang_getCursorSpelling(C);
2857}
2858
Ted Kremeneke68fff62010-02-17 00:41:32 +00002859CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002860 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002861 case CXCursor_FunctionDecl:
2862 return createCXString("FunctionDecl");
2863 case CXCursor_TypedefDecl:
2864 return createCXString("TypedefDecl");
2865 case CXCursor_EnumDecl:
2866 return createCXString("EnumDecl");
2867 case CXCursor_EnumConstantDecl:
2868 return createCXString("EnumConstantDecl");
2869 case CXCursor_StructDecl:
2870 return createCXString("StructDecl");
2871 case CXCursor_UnionDecl:
2872 return createCXString("UnionDecl");
2873 case CXCursor_ClassDecl:
2874 return createCXString("ClassDecl");
2875 case CXCursor_FieldDecl:
2876 return createCXString("FieldDecl");
2877 case CXCursor_VarDecl:
2878 return createCXString("VarDecl");
2879 case CXCursor_ParmDecl:
2880 return createCXString("ParmDecl");
2881 case CXCursor_ObjCInterfaceDecl:
2882 return createCXString("ObjCInterfaceDecl");
2883 case CXCursor_ObjCCategoryDecl:
2884 return createCXString("ObjCCategoryDecl");
2885 case CXCursor_ObjCProtocolDecl:
2886 return createCXString("ObjCProtocolDecl");
2887 case CXCursor_ObjCPropertyDecl:
2888 return createCXString("ObjCPropertyDecl");
2889 case CXCursor_ObjCIvarDecl:
2890 return createCXString("ObjCIvarDecl");
2891 case CXCursor_ObjCInstanceMethodDecl:
2892 return createCXString("ObjCInstanceMethodDecl");
2893 case CXCursor_ObjCClassMethodDecl:
2894 return createCXString("ObjCClassMethodDecl");
2895 case CXCursor_ObjCImplementationDecl:
2896 return createCXString("ObjCImplementationDecl");
2897 case CXCursor_ObjCCategoryImplDecl:
2898 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002899 case CXCursor_CXXMethod:
2900 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002901 case CXCursor_UnexposedDecl:
2902 return createCXString("UnexposedDecl");
2903 case CXCursor_ObjCSuperClassRef:
2904 return createCXString("ObjCSuperClassRef");
2905 case CXCursor_ObjCProtocolRef:
2906 return createCXString("ObjCProtocolRef");
2907 case CXCursor_ObjCClassRef:
2908 return createCXString("ObjCClassRef");
2909 case CXCursor_TypeRef:
2910 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002911 case CXCursor_TemplateRef:
2912 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002913 case CXCursor_NamespaceRef:
2914 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002915 case CXCursor_MemberRef:
2916 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002917 case CXCursor_LabelRef:
2918 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002919 case CXCursor_OverloadedDeclRef:
2920 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002921 case CXCursor_UnexposedExpr:
2922 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002923 case CXCursor_BlockExpr:
2924 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002925 case CXCursor_DeclRefExpr:
2926 return createCXString("DeclRefExpr");
2927 case CXCursor_MemberRefExpr:
2928 return createCXString("MemberRefExpr");
2929 case CXCursor_CallExpr:
2930 return createCXString("CallExpr");
2931 case CXCursor_ObjCMessageExpr:
2932 return createCXString("ObjCMessageExpr");
2933 case CXCursor_UnexposedStmt:
2934 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002935 case CXCursor_LabelStmt:
2936 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002937 case CXCursor_InvalidFile:
2938 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002939 case CXCursor_InvalidCode:
2940 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002941 case CXCursor_NoDeclFound:
2942 return createCXString("NoDeclFound");
2943 case CXCursor_NotImplemented:
2944 return createCXString("NotImplemented");
2945 case CXCursor_TranslationUnit:
2946 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002947 case CXCursor_UnexposedAttr:
2948 return createCXString("UnexposedAttr");
2949 case CXCursor_IBActionAttr:
2950 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002951 case CXCursor_IBOutletAttr:
2952 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002953 case CXCursor_IBOutletCollectionAttr:
2954 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002955 case CXCursor_PreprocessingDirective:
2956 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002957 case CXCursor_MacroDefinition:
2958 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002959 case CXCursor_MacroInstantiation:
2960 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002961 case CXCursor_InclusionDirective:
2962 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002963 case CXCursor_Namespace:
2964 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002965 case CXCursor_LinkageSpec:
2966 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002967 case CXCursor_CXXBaseSpecifier:
2968 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002969 case CXCursor_Constructor:
2970 return createCXString("CXXConstructor");
2971 case CXCursor_Destructor:
2972 return createCXString("CXXDestructor");
2973 case CXCursor_ConversionFunction:
2974 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002975 case CXCursor_TemplateTypeParameter:
2976 return createCXString("TemplateTypeParameter");
2977 case CXCursor_NonTypeTemplateParameter:
2978 return createCXString("NonTypeTemplateParameter");
2979 case CXCursor_TemplateTemplateParameter:
2980 return createCXString("TemplateTemplateParameter");
2981 case CXCursor_FunctionTemplate:
2982 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002983 case CXCursor_ClassTemplate:
2984 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002985 case CXCursor_ClassTemplatePartialSpecialization:
2986 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002987 case CXCursor_NamespaceAlias:
2988 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002989 case CXCursor_UsingDirective:
2990 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002991 case CXCursor_UsingDeclaration:
2992 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002993 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002994
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002995 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002996 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002997}
Steve Naroff89922f82009-08-31 00:59:03 +00002998
Ted Kremeneke68fff62010-02-17 00:41:32 +00002999enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3000 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003001 CXClientData client_data) {
3002 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003003
3004 // If our current best cursor is the construction of a temporary object,
3005 // don't replace that cursor with a type reference, because we want
3006 // clang_getCursor() to point at the constructor.
3007 if (clang_isExpression(BestCursor->kind) &&
3008 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3009 cursor.kind == CXCursor_TypeRef)
3010 return CXChildVisit_Recurse;
3011
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003012 *BestCursor = cursor;
3013 return CXChildVisit_Recurse;
3014}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003015
Douglas Gregorb9790342010-01-22 21:44:22 +00003016CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3017 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003018 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003019
Douglas Gregorb9790342010-01-22 21:44:22 +00003020 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003021 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3022
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003023 // Translate the given source location to make it point at the beginning of
3024 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003025 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003026
3027 // Guard against an invalid SourceLocation, or we may assert in one
3028 // of the following calls.
3029 if (SLoc.isInvalid())
3030 return clang_getNullCursor();
3031
Douglas Gregor40749ee2010-11-03 00:35:38 +00003032 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003033 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3034 CXXUnit->getASTContext().getLangOptions());
3035
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003036 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3037 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003038 // FIXME: Would be great to have a "hint" cursor, then walk from that
3039 // hint cursor upward until we find a cursor whose source range encloses
3040 // the region of interest, rather than starting from the translation unit.
3041 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003042 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003043 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003044 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003045 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003046
3047 if (Logging) {
3048 CXFile SearchFile;
3049 unsigned SearchLine, SearchColumn;
3050 CXFile ResultFile;
3051 unsigned ResultLine, ResultColumn;
3052 CXString SearchFileName, ResultFileName, KindSpelling;
3053 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3054
3055 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3056 0);
3057 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3058 &ResultColumn, 0);
3059 SearchFileName = clang_getFileName(SearchFile);
3060 ResultFileName = clang_getFileName(ResultFile);
3061 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3062 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3063 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3064 clang_getCString(KindSpelling),
3065 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3066 clang_disposeString(SearchFileName);
3067 clang_disposeString(ResultFileName);
3068 clang_disposeString(KindSpelling);
3069 }
3070
Ted Kremeneke68fff62010-02-17 00:41:32 +00003071 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003072}
3073
Ted Kremenek73885552009-11-17 19:28:59 +00003074CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003075 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003076}
3077
3078unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003079 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003080}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003081
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003082unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003083 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3084}
3085
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003086unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003087 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3088}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003089
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003090unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003091 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3092}
3093
Douglas Gregor97b98722010-01-19 23:20:36 +00003094unsigned clang_isExpression(enum CXCursorKind K) {
3095 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3096}
3097
3098unsigned clang_isStatement(enum CXCursorKind K) {
3099 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3100}
3101
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003102unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3103 return K == CXCursor_TranslationUnit;
3104}
3105
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003106unsigned clang_isPreprocessing(enum CXCursorKind K) {
3107 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3108}
3109
Ted Kremenekad6eff62010-03-08 21:17:29 +00003110unsigned clang_isUnexposed(enum CXCursorKind K) {
3111 switch (K) {
3112 case CXCursor_UnexposedDecl:
3113 case CXCursor_UnexposedExpr:
3114 case CXCursor_UnexposedStmt:
3115 case CXCursor_UnexposedAttr:
3116 return true;
3117 default:
3118 return false;
3119 }
3120}
3121
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003122CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003123 return C.kind;
3124}
3125
Douglas Gregor98258af2010-01-18 22:46:11 +00003126CXSourceLocation clang_getCursorLocation(CXCursor C) {
3127 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003128 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003129 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003130 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3131 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003132 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003133 }
3134
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003135 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003136 std::pair<ObjCProtocolDecl *, SourceLocation> P
3137 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003138 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003139 }
3140
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003141 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003142 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3143 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003144 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003145 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003146
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003147 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003148 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003149 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003150 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003151
3152 case CXCursor_TemplateRef: {
3153 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3154 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3155 }
3156
Douglas Gregor69319002010-08-31 23:48:11 +00003157 case CXCursor_NamespaceRef: {
3158 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3159 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3160 }
3161
Douglas Gregora67e03f2010-09-09 21:42:20 +00003162 case CXCursor_MemberRef: {
3163 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3164 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3165 }
3166
Ted Kremenek3064ef92010-08-27 21:34:58 +00003167 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003168 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3169 if (!BaseSpec)
3170 return clang_getNullLocation();
3171
3172 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3173 return cxloc::translateSourceLocation(getCursorContext(C),
3174 TSInfo->getTypeLoc().getBeginLoc());
3175
3176 return cxloc::translateSourceLocation(getCursorContext(C),
3177 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003178 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003179
Douglas Gregor36897b02010-09-10 00:22:18 +00003180 case CXCursor_LabelRef: {
3181 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3182 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3183 }
3184
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003185 case CXCursor_OverloadedDeclRef:
3186 return cxloc::translateSourceLocation(getCursorContext(C),
3187 getCursorOverloadedDeclRef(C).second);
3188
Douglas Gregorf46034a2010-01-18 23:41:10 +00003189 default:
3190 // FIXME: Need a way to enumerate all non-reference cases.
3191 llvm_unreachable("Missed a reference kind");
3192 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003193 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003194
3195 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003196 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003197 getLocationFromExpr(getCursorExpr(C)));
3198
Douglas Gregor36897b02010-09-10 00:22:18 +00003199 if (clang_isStatement(C.kind))
3200 return cxloc::translateSourceLocation(getCursorContext(C),
3201 getCursorStmt(C)->getLocStart());
3202
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003203 if (C.kind == CXCursor_PreprocessingDirective) {
3204 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3205 return cxloc::translateSourceLocation(getCursorContext(C), L);
3206 }
Douglas Gregor48072312010-03-18 15:23:44 +00003207
3208 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003209 SourceLocation L
3210 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003211 return cxloc::translateSourceLocation(getCursorContext(C), L);
3212 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003213
3214 if (C.kind == CXCursor_MacroDefinition) {
3215 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3216 return cxloc::translateSourceLocation(getCursorContext(C), L);
3217 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003218
3219 if (C.kind == CXCursor_InclusionDirective) {
3220 SourceLocation L
3221 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3222 return cxloc::translateSourceLocation(getCursorContext(C), L);
3223 }
3224
Ted Kremenek9a700d22010-05-12 06:16:13 +00003225 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003226 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003227
Douglas Gregorf46034a2010-01-18 23:41:10 +00003228 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003229 SourceLocation Loc = D->getLocation();
3230 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3231 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003232 // FIXME: Multiple variables declared in a single declaration
3233 // currently lack the information needed to correctly determine their
3234 // ranges when accounting for the type-specifier. We use context
3235 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3236 // and if so, whether it is the first decl.
3237 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3238 if (!cxcursor::isFirstInDeclGroup(C))
3239 Loc = VD->getLocation();
3240 }
3241
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003242 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003243}
Douglas Gregora7bde202010-01-19 00:34:46 +00003244
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003245} // end extern "C"
3246
3247static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003248 if (clang_isReference(C.kind)) {
3249 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003250 case CXCursor_ObjCSuperClassRef:
3251 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003252
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003253 case CXCursor_ObjCProtocolRef:
3254 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003255
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003256 case CXCursor_ObjCClassRef:
3257 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003258
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003259 case CXCursor_TypeRef:
3260 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003261
3262 case CXCursor_TemplateRef:
3263 return getCursorTemplateRef(C).second;
3264
Douglas Gregor69319002010-08-31 23:48:11 +00003265 case CXCursor_NamespaceRef:
3266 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003267
3268 case CXCursor_MemberRef:
3269 return getCursorMemberRef(C).second;
3270
Ted Kremenek3064ef92010-08-27 21:34:58 +00003271 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003272 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003273
Douglas Gregor36897b02010-09-10 00:22:18 +00003274 case CXCursor_LabelRef:
3275 return getCursorLabelRef(C).second;
3276
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003277 case CXCursor_OverloadedDeclRef:
3278 return getCursorOverloadedDeclRef(C).second;
3279
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003280 default:
3281 // FIXME: Need a way to enumerate all non-reference cases.
3282 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003283 }
3284 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003285
3286 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003287 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003288
3289 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003290 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003291
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003292 if (C.kind == CXCursor_PreprocessingDirective)
3293 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003294
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003295 if (C.kind == CXCursor_MacroInstantiation)
3296 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003297
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003298 if (C.kind == CXCursor_MacroDefinition)
3299 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003300
3301 if (C.kind == CXCursor_InclusionDirective)
3302 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3303
Ted Kremenek007a7c92010-11-01 23:26:51 +00003304 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3305 Decl *D = cxcursor::getCursorDecl(C);
3306 SourceRange R = D->getSourceRange();
3307 // FIXME: Multiple variables declared in a single declaration
3308 // currently lack the information needed to correctly determine their
3309 // ranges when accounting for the type-specifier. We use context
3310 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3311 // and if so, whether it is the first decl.
3312 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3313 if (!cxcursor::isFirstInDeclGroup(C))
3314 R.setBegin(VD->getLocation());
3315 }
3316 return R;
3317 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003318 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003319
3320extern "C" {
3321
3322CXSourceRange clang_getCursorExtent(CXCursor C) {
3323 SourceRange R = getRawCursorExtent(C);
3324 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003325 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003326
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003327 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003328}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003329
3330CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003331 if (clang_isInvalid(C.kind))
3332 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003333
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003334 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003335 if (clang_isDeclaration(C.kind)) {
3336 Decl *D = getCursorDecl(C);
3337 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3338 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3339 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3340 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3341 if (ObjCForwardProtocolDecl *Protocols
3342 = dyn_cast<ObjCForwardProtocolDecl>(D))
3343 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3344
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003345 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003346 }
3347
Douglas Gregor97b98722010-01-19 23:20:36 +00003348 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003349 Expr *E = getCursorExpr(C);
3350 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003351 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003352 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003353
3354 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3355 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3356
Douglas Gregor97b98722010-01-19 23:20:36 +00003357 return clang_getNullCursor();
3358 }
3359
Douglas Gregor36897b02010-09-10 00:22:18 +00003360 if (clang_isStatement(C.kind)) {
3361 Stmt *S = getCursorStmt(C);
3362 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3363 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3364 getCursorASTUnit(C));
3365
3366 return clang_getNullCursor();
3367 }
3368
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003369 if (C.kind == CXCursor_MacroInstantiation) {
3370 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3371 return MakeMacroDefinitionCursor(Def, CXXUnit);
3372 }
3373
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003374 if (!clang_isReference(C.kind))
3375 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003376
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003377 switch (C.kind) {
3378 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003379 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003380
3381 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003382 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003383
3384 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003385 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003386
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003387 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003388 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003389
3390 case CXCursor_TemplateRef:
3391 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3392
Douglas Gregor69319002010-08-31 23:48:11 +00003393 case CXCursor_NamespaceRef:
3394 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3395
Douglas Gregora67e03f2010-09-09 21:42:20 +00003396 case CXCursor_MemberRef:
3397 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3398
Ted Kremenek3064ef92010-08-27 21:34:58 +00003399 case CXCursor_CXXBaseSpecifier: {
3400 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3401 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3402 CXXUnit));
3403 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003404
Douglas Gregor36897b02010-09-10 00:22:18 +00003405 case CXCursor_LabelRef:
3406 // FIXME: We end up faking the "parent" declaration here because we
3407 // don't want to make CXCursor larger.
3408 return MakeCXCursor(getCursorLabelRef(C).first,
3409 CXXUnit->getASTContext().getTranslationUnitDecl(),
3410 CXXUnit);
3411
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003412 case CXCursor_OverloadedDeclRef:
3413 return C;
3414
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003415 default:
3416 // We would prefer to enumerate all non-reference cursor kinds here.
3417 llvm_unreachable("Unhandled reference cursor kind");
3418 break;
3419 }
3420 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003421
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003422 return clang_getNullCursor();
3423}
3424
Douglas Gregorb6998662010-01-19 19:34:47 +00003425CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003426 if (clang_isInvalid(C.kind))
3427 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003428
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003429 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003430
Douglas Gregorb6998662010-01-19 19:34:47 +00003431 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003432 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003433 C = clang_getCursorReferenced(C);
3434 WasReference = true;
3435 }
3436
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003437 if (C.kind == CXCursor_MacroInstantiation)
3438 return clang_getCursorReferenced(C);
3439
Douglas Gregorb6998662010-01-19 19:34:47 +00003440 if (!clang_isDeclaration(C.kind))
3441 return clang_getNullCursor();
3442
3443 Decl *D = getCursorDecl(C);
3444 if (!D)
3445 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003446
Douglas Gregorb6998662010-01-19 19:34:47 +00003447 switch (D->getKind()) {
3448 // Declaration kinds that don't really separate the notions of
3449 // declaration and definition.
3450 case Decl::Namespace:
3451 case Decl::Typedef:
3452 case Decl::TemplateTypeParm:
3453 case Decl::EnumConstant:
3454 case Decl::Field:
3455 case Decl::ObjCIvar:
3456 case Decl::ObjCAtDefsField:
3457 case Decl::ImplicitParam:
3458 case Decl::ParmVar:
3459 case Decl::NonTypeTemplateParm:
3460 case Decl::TemplateTemplateParm:
3461 case Decl::ObjCCategoryImpl:
3462 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003463 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003464 case Decl::LinkageSpec:
3465 case Decl::ObjCPropertyImpl:
3466 case Decl::FileScopeAsm:
3467 case Decl::StaticAssert:
3468 case Decl::Block:
3469 return C;
3470
3471 // Declaration kinds that don't make any sense here, but are
3472 // nonetheless harmless.
3473 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003474 break;
3475
3476 // Declaration kinds for which the definition is not resolvable.
3477 case Decl::UnresolvedUsingTypename:
3478 case Decl::UnresolvedUsingValue:
3479 break;
3480
3481 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003482 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3483 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003484
3485 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003486 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003487
3488 case Decl::Enum:
3489 case Decl::Record:
3490 case Decl::CXXRecord:
3491 case Decl::ClassTemplateSpecialization:
3492 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003493 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003494 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003495 return clang_getNullCursor();
3496
3497 case Decl::Function:
3498 case Decl::CXXMethod:
3499 case Decl::CXXConstructor:
3500 case Decl::CXXDestructor:
3501 case Decl::CXXConversion: {
3502 const FunctionDecl *Def = 0;
3503 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003504 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003505 return clang_getNullCursor();
3506 }
3507
3508 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003509 // Ask the variable if it has a definition.
3510 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3511 return MakeCXCursor(Def, CXXUnit);
3512 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003513 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003514
Douglas Gregorb6998662010-01-19 19:34:47 +00003515 case Decl::FunctionTemplate: {
3516 const FunctionDecl *Def = 0;
3517 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003518 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003519 return clang_getNullCursor();
3520 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003521
Douglas Gregorb6998662010-01-19 19:34:47 +00003522 case Decl::ClassTemplate: {
3523 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003524 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003525 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003526 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003527 return clang_getNullCursor();
3528 }
3529
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003530 case Decl::Using:
3531 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3532 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003533
3534 case Decl::UsingShadow:
3535 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003536 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003537 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003538
3539 case Decl::ObjCMethod: {
3540 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3541 if (Method->isThisDeclarationADefinition())
3542 return C;
3543
3544 // Dig out the method definition in the associated
3545 // @implementation, if we have it.
3546 // FIXME: The ASTs should make finding the definition easier.
3547 if (ObjCInterfaceDecl *Class
3548 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3549 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3550 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3551 Method->isInstanceMethod()))
3552 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003553 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003554
3555 return clang_getNullCursor();
3556 }
3557
3558 case Decl::ObjCCategory:
3559 if (ObjCCategoryImplDecl *Impl
3560 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003561 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003562 return clang_getNullCursor();
3563
3564 case Decl::ObjCProtocol:
3565 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3566 return C;
3567 return clang_getNullCursor();
3568
3569 case Decl::ObjCInterface:
3570 // There are two notions of a "definition" for an Objective-C
3571 // class: the interface and its implementation. When we resolved a
3572 // reference to an Objective-C class, produce the @interface as
3573 // the definition; when we were provided with the interface,
3574 // produce the @implementation as the definition.
3575 if (WasReference) {
3576 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3577 return C;
3578 } else if (ObjCImplementationDecl *Impl
3579 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003580 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003581 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003582
Douglas Gregorb6998662010-01-19 19:34:47 +00003583 case Decl::ObjCProperty:
3584 // FIXME: We don't really know where to find the
3585 // ObjCPropertyImplDecls that implement this property.
3586 return clang_getNullCursor();
3587
3588 case Decl::ObjCCompatibleAlias:
3589 if (ObjCInterfaceDecl *Class
3590 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3591 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003592 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003593
Douglas Gregorb6998662010-01-19 19:34:47 +00003594 return clang_getNullCursor();
3595
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003596 case Decl::ObjCForwardProtocol:
3597 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3598 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003599
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003600 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003601 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003602 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003603
3604 case Decl::Friend:
3605 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003606 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003607 return clang_getNullCursor();
3608
3609 case Decl::FriendTemplate:
3610 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003611 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003612 return clang_getNullCursor();
3613 }
3614
3615 return clang_getNullCursor();
3616}
3617
3618unsigned clang_isCursorDefinition(CXCursor C) {
3619 if (!clang_isDeclaration(C.kind))
3620 return 0;
3621
3622 return clang_getCursorDefinition(C) == C;
3623}
3624
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003625unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003626 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003627 return 0;
3628
3629 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3630 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3631 return E->getNumDecls();
3632
3633 if (OverloadedTemplateStorage *S
3634 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3635 return S->size();
3636
3637 Decl *D = Storage.get<Decl*>();
3638 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3639 return Using->getNumShadowDecls();
3640 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3641 return Classes->size();
3642 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3643 return Protocols->protocol_size();
3644
3645 return 0;
3646}
3647
3648CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003649 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003650 return clang_getNullCursor();
3651
3652 if (index >= clang_getNumOverloadedDecls(cursor))
3653 return clang_getNullCursor();
3654
3655 ASTUnit *Unit = getCursorASTUnit(cursor);
3656 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3657 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3658 return MakeCXCursor(E->decls_begin()[index], Unit);
3659
3660 if (OverloadedTemplateStorage *S
3661 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3662 return MakeCXCursor(S->begin()[index], Unit);
3663
3664 Decl *D = Storage.get<Decl*>();
3665 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3666 // FIXME: This is, unfortunately, linear time.
3667 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3668 std::advance(Pos, index);
3669 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3670 }
3671
3672 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3673 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3674
3675 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3676 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3677
3678 return clang_getNullCursor();
3679}
3680
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003681void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003682 const char **startBuf,
3683 const char **endBuf,
3684 unsigned *startLine,
3685 unsigned *startColumn,
3686 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003687 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003688 assert(getCursorDecl(C) && "CXCursor has null decl");
3689 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003690 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3691 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003692
Steve Naroff4ade6d62009-09-23 17:52:52 +00003693 SourceManager &SM = FD->getASTContext().getSourceManager();
3694 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3695 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3696 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3697 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3698 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3699 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3700}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003701
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003702void clang_enableStackTraces(void) {
3703 llvm::sys::PrintStackTraceOnErrorSignal();
3704}
3705
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003706void clang_executeOnThread(void (*fn)(void*), void *user_data,
3707 unsigned stack_size) {
3708 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3709}
3710
Ted Kremenekfb480492010-01-13 21:46:36 +00003711} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003712
Ted Kremenekfb480492010-01-13 21:46:36 +00003713//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003714// Token-based Operations.
3715//===----------------------------------------------------------------------===//
3716
3717/* CXToken layout:
3718 * int_data[0]: a CXTokenKind
3719 * int_data[1]: starting token location
3720 * int_data[2]: token length
3721 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003722 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003723 * otherwise unused.
3724 */
3725extern "C" {
3726
3727CXTokenKind clang_getTokenKind(CXToken CXTok) {
3728 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3729}
3730
3731CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3732 switch (clang_getTokenKind(CXTok)) {
3733 case CXToken_Identifier:
3734 case CXToken_Keyword:
3735 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003736 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3737 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003738
3739 case CXToken_Literal: {
3740 // We have stashed the starting pointer in the ptr_data field. Use it.
3741 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003742 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003743 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003744
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003745 case CXToken_Punctuation:
3746 case CXToken_Comment:
3747 break;
3748 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003749
3750 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003751 // deconstructing the source location.
3752 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3753 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003754 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003755
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003756 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3757 std::pair<FileID, unsigned> LocInfo
3758 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003759 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003760 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003761 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3762 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003763 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003764
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003765 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003766}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003767
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003768CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3769 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3770 if (!CXXUnit)
3771 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003772
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003773 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3774 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3775}
3776
3777CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3778 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003779 if (!CXXUnit)
3780 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003781
3782 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003783 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3784}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003785
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003786void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3787 CXToken **Tokens, unsigned *NumTokens) {
3788 if (Tokens)
3789 *Tokens = 0;
3790 if (NumTokens)
3791 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003792
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003793 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3794 if (!CXXUnit || !Tokens || !NumTokens)
3795 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003796
Douglas Gregorbdf60622010-03-05 21:16:25 +00003797 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3798
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003799 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003800 if (R.isInvalid())
3801 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003802
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003803 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3804 std::pair<FileID, unsigned> BeginLocInfo
3805 = SourceMgr.getDecomposedLoc(R.getBegin());
3806 std::pair<FileID, unsigned> EndLocInfo
3807 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003808
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003809 // Cannot tokenize across files.
3810 if (BeginLocInfo.first != EndLocInfo.first)
3811 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003812
3813 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003814 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003815 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003816 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003817 if (Invalid)
3818 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003819
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003820 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3821 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003822 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003823 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003824
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003825 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003826 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003827 llvm::SmallVector<CXToken, 32> CXTokens;
3828 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003829 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003830 do {
3831 // Lex the next token
3832 Lex.LexFromRawLexer(Tok);
3833 if (Tok.is(tok::eof))
3834 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003835
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003836 // Initialize the CXToken.
3837 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003838
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003839 // - Common fields
3840 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3841 CXTok.int_data[2] = Tok.getLength();
3842 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003843
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003844 // - Kind-specific fields
3845 if (Tok.isLiteral()) {
3846 CXTok.int_data[0] = CXToken_Literal;
3847 CXTok.ptr_data = (void *)Tok.getLiteralData();
3848 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003849 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003850 std::pair<FileID, unsigned> LocInfo
3851 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003852 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003853 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003854 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3855 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003856 return;
3857
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003858 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003859 IdentifierInfo *II
3860 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003861
David Chisnall096428b2010-10-13 21:44:48 +00003862 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003863 CXTok.int_data[0] = CXToken_Keyword;
3864 }
3865 else {
3866 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3867 CXToken_Identifier
3868 : CXToken_Keyword;
3869 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003870 CXTok.ptr_data = II;
3871 } else if (Tok.is(tok::comment)) {
3872 CXTok.int_data[0] = CXToken_Comment;
3873 CXTok.ptr_data = 0;
3874 } else {
3875 CXTok.int_data[0] = CXToken_Punctuation;
3876 CXTok.ptr_data = 0;
3877 }
3878 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003879 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003880 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003881
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003882 if (CXTokens.empty())
3883 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003884
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003885 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3886 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3887 *NumTokens = CXTokens.size();
3888}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003889
Ted Kremenek6db61092010-05-05 00:55:15 +00003890void clang_disposeTokens(CXTranslationUnit TU,
3891 CXToken *Tokens, unsigned NumTokens) {
3892 free(Tokens);
3893}
3894
3895} // end: extern "C"
3896
3897//===----------------------------------------------------------------------===//
3898// Token annotation APIs.
3899//===----------------------------------------------------------------------===//
3900
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003901typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003902static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3903 CXCursor parent,
3904 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003905namespace {
3906class AnnotateTokensWorker {
3907 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003908 CXToken *Tokens;
3909 CXCursor *Cursors;
3910 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003911 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003912 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003913 CursorVisitor AnnotateVis;
3914 SourceManager &SrcMgr;
3915
3916 bool MoreTokens() const { return TokIdx < NumTokens; }
3917 unsigned NextToken() const { return TokIdx; }
3918 void AdvanceToken() { ++TokIdx; }
3919 SourceLocation GetTokenLoc(unsigned tokI) {
3920 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3921 }
3922
Ted Kremenek6db61092010-05-05 00:55:15 +00003923public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003924 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003925 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3926 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003927 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003928 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003929 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3930 Decl::MaxPCHLevel, RegionOfInterest),
3931 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003932
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003933 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003934 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003935 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003936};
3937}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003938
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003939void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3940 // Walk the AST within the region of interest, annotating tokens
3941 // along the way.
3942 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003943
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003944 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3945 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003946 if (Pos != Annotated.end() &&
3947 (clang_isInvalid(Cursors[I].kind) ||
3948 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003949 Cursors[I] = Pos->second;
3950 }
3951
3952 // Finish up annotating any tokens left.
3953 if (!MoreTokens())
3954 return;
3955
3956 const CXCursor &C = clang_getNullCursor();
3957 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3958 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3959 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003960 }
3961}
3962
Ted Kremenek6db61092010-05-05 00:55:15 +00003963enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00003964AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003965 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00003966 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00003967 if (cursorRange.isInvalid())
3968 return CXChildVisit_Recurse;
3969
Douglas Gregor4419b672010-10-21 06:10:04 +00003970 if (clang_isPreprocessing(cursor.kind)) {
3971 // For macro instantiations, just note where the beginning of the macro
3972 // instantiation occurs.
3973 if (cursor.kind == CXCursor_MacroInstantiation) {
3974 Annotated[Loc.int_data] = cursor;
3975 return CXChildVisit_Recurse;
3976 }
3977
Douglas Gregor4419b672010-10-21 06:10:04 +00003978 // Items in the preprocessing record are kept separate from items in
3979 // declarations, so we keep a separate token index.
3980 unsigned SavedTokIdx = TokIdx;
3981 TokIdx = PreprocessingTokIdx;
3982
3983 // Skip tokens up until we catch up to the beginning of the preprocessing
3984 // entry.
3985 while (MoreTokens()) {
3986 const unsigned I = NextToken();
3987 SourceLocation TokLoc = GetTokenLoc(I);
3988 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3989 case RangeBefore:
3990 AdvanceToken();
3991 continue;
3992 case RangeAfter:
3993 case RangeOverlap:
3994 break;
3995 }
3996 break;
3997 }
3998
3999 // Look at all of the tokens within this range.
4000 while (MoreTokens()) {
4001 const unsigned I = NextToken();
4002 SourceLocation TokLoc = GetTokenLoc(I);
4003 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4004 case RangeBefore:
4005 assert(0 && "Infeasible");
4006 case RangeAfter:
4007 break;
4008 case RangeOverlap:
4009 Cursors[I] = cursor;
4010 AdvanceToken();
4011 continue;
4012 }
4013 break;
4014 }
4015
4016 // Save the preprocessing token index; restore the non-preprocessing
4017 // token index.
4018 PreprocessingTokIdx = TokIdx;
4019 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004020 return CXChildVisit_Recurse;
4021 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004022
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004023 if (cursorRange.isInvalid())
4024 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004025
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004026 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4027
Ted Kremeneka333c662010-05-12 05:29:33 +00004028 // Adjust the annotated range based specific declarations.
4029 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4030 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004031 Decl *D = cxcursor::getCursorDecl(cursor);
4032 // Don't visit synthesized ObjC methods, since they have no syntatic
4033 // representation in the source.
4034 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4035 if (MD->isSynthesized())
4036 return CXChildVisit_Continue;
4037 }
4038 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004039 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4040 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004041 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004042 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004043 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004044 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004045 }
4046 }
4047 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004048
Ted Kremenek3f404602010-08-14 01:14:06 +00004049 // If the location of the cursor occurs within a macro instantiation, record
4050 // the spelling location of the cursor in our annotation map. We can then
4051 // paper over the token labelings during a post-processing step to try and
4052 // get cursor mappings for tokens that are the *arguments* of a macro
4053 // instantiation.
4054 if (L.isMacroID()) {
4055 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4056 // Only invalidate the old annotation if it isn't part of a preprocessing
4057 // directive. Here we assume that the default construction of CXCursor
4058 // results in CXCursor.kind being an initialized value (i.e., 0). If
4059 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004060
Ted Kremenek3f404602010-08-14 01:14:06 +00004061 CXCursor &oldC = Annotated[rawEncoding];
4062 if (!clang_isPreprocessing(oldC.kind))
4063 oldC = cursor;
4064 }
4065
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004066 const enum CXCursorKind K = clang_getCursorKind(parent);
4067 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004068 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4069 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004070
4071 while (MoreTokens()) {
4072 const unsigned I = NextToken();
4073 SourceLocation TokLoc = GetTokenLoc(I);
4074 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4075 case RangeBefore:
4076 Cursors[I] = updateC;
4077 AdvanceToken();
4078 continue;
4079 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004080 case RangeOverlap:
4081 break;
4082 }
4083 break;
4084 }
4085
4086 // Visit children to get their cursor information.
4087 const unsigned BeforeChildren = NextToken();
4088 VisitChildren(cursor);
4089 const unsigned AfterChildren = NextToken();
4090
4091 // Adjust 'Last' to the last token within the extent of the cursor.
4092 while (MoreTokens()) {
4093 const unsigned I = NextToken();
4094 SourceLocation TokLoc = GetTokenLoc(I);
4095 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4096 case RangeBefore:
4097 assert(0 && "Infeasible");
4098 case RangeAfter:
4099 break;
4100 case RangeOverlap:
4101 Cursors[I] = updateC;
4102 AdvanceToken();
4103 continue;
4104 }
4105 break;
4106 }
4107 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004108
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004109 // Scan the tokens that are at the beginning of the cursor, but are not
4110 // capture by the child cursors.
4111
4112 // For AST elements within macros, rely on a post-annotate pass to
4113 // to correctly annotate the tokens with cursors. Otherwise we can
4114 // get confusing results of having tokens that map to cursors that really
4115 // are expanded by an instantiation.
4116 if (L.isMacroID())
4117 cursor = clang_getNullCursor();
4118
4119 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4120 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4121 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004122
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004123 Cursors[I] = cursor;
4124 }
4125 // Scan the tokens that are at the end of the cursor, but are not captured
4126 // but the child cursors.
4127 for (unsigned I = AfterChildren; I != Last; ++I)
4128 Cursors[I] = cursor;
4129
4130 TokIdx = Last;
4131 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004132}
4133
Ted Kremenek6db61092010-05-05 00:55:15 +00004134static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4135 CXCursor parent,
4136 CXClientData client_data) {
4137 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4138}
4139
4140extern "C" {
4141
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004142void clang_annotateTokens(CXTranslationUnit TU,
4143 CXToken *Tokens, unsigned NumTokens,
4144 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004145
4146 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004147 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004148
Douglas Gregor4419b672010-10-21 06:10:04 +00004149 // Any token we don't specifically annotate will have a NULL cursor.
4150 CXCursor C = clang_getNullCursor();
4151 for (unsigned I = 0; I != NumTokens; ++I)
4152 Cursors[I] = C;
4153
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004154 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004155 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004156 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004157
Douglas Gregorbdf60622010-03-05 21:16:25 +00004158 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004159
Douglas Gregor0396f462010-03-19 05:22:59 +00004160 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004161 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004162 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4163 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004164 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4165 clang_getTokenLocation(TU,
4166 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004167
Douglas Gregor0396f462010-03-19 05:22:59 +00004168 // A mapping from the source locations found when re-lexing or traversing the
4169 // region of interest to the corresponding cursors.
4170 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004171
4172 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004173 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004174 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4175 std::pair<FileID, unsigned> BeginLocInfo
4176 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4177 std::pair<FileID, unsigned> EndLocInfo
4178 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004179
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004180 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004181 bool Invalid = false;
4182 if (BeginLocInfo.first == EndLocInfo.first &&
4183 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4184 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004185 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4186 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004187 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004188 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004189 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004190
4191 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004192 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004193 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004194 Token Tok;
4195 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004196
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004197 reprocess:
4198 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4199 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004200 // don't see it while preprocessing these tokens later, but keep track
4201 // of all of the token locations inside this preprocessing directive so
4202 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004203 //
4204 // FIXME: Some simple tests here could identify macro definitions and
4205 // #undefs, to provide specific cursor kinds for those.
4206 std::vector<SourceLocation> Locations;
4207 do {
4208 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004209 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004210 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004211
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004212 using namespace cxcursor;
4213 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004214 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4215 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004216 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004217 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4218 Annotated[Locations[I].getRawEncoding()] = Cursor;
4219 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004220
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004221 if (Tok.isAtStartOfLine())
4222 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004223
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004224 continue;
4225 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004226
Douglas Gregor48072312010-03-18 15:23:44 +00004227 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004228 break;
4229 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004230 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004231
Douglas Gregor0396f462010-03-19 05:22:59 +00004232 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004233 // a specific cursor.
4234 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4235 CXXUnit, RegionOfInterest);
4236 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004237}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004238} // end: extern "C"
4239
4240//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004241// Operations for querying linkage of a cursor.
4242//===----------------------------------------------------------------------===//
4243
4244extern "C" {
4245CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004246 if (!clang_isDeclaration(cursor.kind))
4247 return CXLinkage_Invalid;
4248
Ted Kremenek16b42592010-03-03 06:36:57 +00004249 Decl *D = cxcursor::getCursorDecl(cursor);
4250 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4251 switch (ND->getLinkage()) {
4252 case NoLinkage: return CXLinkage_NoLinkage;
4253 case InternalLinkage: return CXLinkage_Internal;
4254 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4255 case ExternalLinkage: return CXLinkage_External;
4256 };
4257
4258 return CXLinkage_Invalid;
4259}
4260} // end: extern "C"
4261
4262//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004263// Operations for querying language of a cursor.
4264//===----------------------------------------------------------------------===//
4265
4266static CXLanguageKind getDeclLanguage(const Decl *D) {
4267 switch (D->getKind()) {
4268 default:
4269 break;
4270 case Decl::ImplicitParam:
4271 case Decl::ObjCAtDefsField:
4272 case Decl::ObjCCategory:
4273 case Decl::ObjCCategoryImpl:
4274 case Decl::ObjCClass:
4275 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004276 case Decl::ObjCForwardProtocol:
4277 case Decl::ObjCImplementation:
4278 case Decl::ObjCInterface:
4279 case Decl::ObjCIvar:
4280 case Decl::ObjCMethod:
4281 case Decl::ObjCProperty:
4282 case Decl::ObjCPropertyImpl:
4283 case Decl::ObjCProtocol:
4284 return CXLanguage_ObjC;
4285 case Decl::CXXConstructor:
4286 case Decl::CXXConversion:
4287 case Decl::CXXDestructor:
4288 case Decl::CXXMethod:
4289 case Decl::CXXRecord:
4290 case Decl::ClassTemplate:
4291 case Decl::ClassTemplatePartialSpecialization:
4292 case Decl::ClassTemplateSpecialization:
4293 case Decl::Friend:
4294 case Decl::FriendTemplate:
4295 case Decl::FunctionTemplate:
4296 case Decl::LinkageSpec:
4297 case Decl::Namespace:
4298 case Decl::NamespaceAlias:
4299 case Decl::NonTypeTemplateParm:
4300 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004301 case Decl::TemplateTemplateParm:
4302 case Decl::TemplateTypeParm:
4303 case Decl::UnresolvedUsingTypename:
4304 case Decl::UnresolvedUsingValue:
4305 case Decl::Using:
4306 case Decl::UsingDirective:
4307 case Decl::UsingShadow:
4308 return CXLanguage_CPlusPlus;
4309 }
4310
4311 return CXLanguage_C;
4312}
4313
4314extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004315
4316enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4317 if (clang_isDeclaration(cursor.kind))
4318 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4319 if (D->hasAttr<UnavailableAttr>() ||
4320 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4321 return CXAvailability_Available;
4322
4323 if (D->hasAttr<DeprecatedAttr>())
4324 return CXAvailability_Deprecated;
4325 }
4326
4327 return CXAvailability_Available;
4328}
4329
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004330CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4331 if (clang_isDeclaration(cursor.kind))
4332 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4333
4334 return CXLanguage_Invalid;
4335}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004336
4337CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4338 if (clang_isDeclaration(cursor.kind)) {
4339 if (Decl *D = getCursorDecl(cursor)) {
4340 DeclContext *DC = D->getDeclContext();
4341 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4342 }
4343 }
4344
4345 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4346 if (Decl *D = getCursorDecl(cursor))
4347 return MakeCXCursor(D, getCursorASTUnit(cursor));
4348 }
4349
4350 return clang_getNullCursor();
4351}
4352
4353CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4354 if (clang_isDeclaration(cursor.kind)) {
4355 if (Decl *D = getCursorDecl(cursor)) {
4356 DeclContext *DC = D->getLexicalDeclContext();
4357 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4358 }
4359 }
4360
4361 // FIXME: Note that we can't easily compute the lexical context of a
4362 // statement or expression, so we return nothing.
4363 return clang_getNullCursor();
4364}
4365
Douglas Gregor9f592342010-10-01 20:25:15 +00004366static void CollectOverriddenMethods(DeclContext *Ctx,
4367 ObjCMethodDecl *Method,
4368 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4369 if (!Ctx)
4370 return;
4371
4372 // If we have a class or category implementation, jump straight to the
4373 // interface.
4374 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4375 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4376
4377 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4378 if (!Container)
4379 return;
4380
4381 // Check whether we have a matching method at this level.
4382 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4383 Method->isInstanceMethod()))
4384 if (Method != Overridden) {
4385 // We found an override at this level; there is no need to look
4386 // into other protocols or categories.
4387 Methods.push_back(Overridden);
4388 return;
4389 }
4390
4391 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4392 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4393 PEnd = Protocol->protocol_end();
4394 P != PEnd; ++P)
4395 CollectOverriddenMethods(*P, Method, Methods);
4396 }
4397
4398 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4399 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4400 PEnd = Category->protocol_end();
4401 P != PEnd; ++P)
4402 CollectOverriddenMethods(*P, Method, Methods);
4403 }
4404
4405 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4406 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4407 PEnd = Interface->protocol_end();
4408 P != PEnd; ++P)
4409 CollectOverriddenMethods(*P, Method, Methods);
4410
4411 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4412 Category; Category = Category->getNextClassCategory())
4413 CollectOverriddenMethods(Category, Method, Methods);
4414
4415 // We only look into the superclass if we haven't found anything yet.
4416 if (Methods.empty())
4417 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4418 return CollectOverriddenMethods(Super, Method, Methods);
4419 }
4420}
4421
4422void clang_getOverriddenCursors(CXCursor cursor,
4423 CXCursor **overridden,
4424 unsigned *num_overridden) {
4425 if (overridden)
4426 *overridden = 0;
4427 if (num_overridden)
4428 *num_overridden = 0;
4429 if (!overridden || !num_overridden)
4430 return;
4431
4432 if (!clang_isDeclaration(cursor.kind))
4433 return;
4434
4435 Decl *D = getCursorDecl(cursor);
4436 if (!D)
4437 return;
4438
4439 // Handle C++ member functions.
4440 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4441 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4442 *num_overridden = CXXMethod->size_overridden_methods();
4443 if (!*num_overridden)
4444 return;
4445
4446 *overridden = new CXCursor [*num_overridden];
4447 unsigned I = 0;
4448 for (CXXMethodDecl::method_iterator
4449 M = CXXMethod->begin_overridden_methods(),
4450 MEnd = CXXMethod->end_overridden_methods();
4451 M != MEnd; (void)++M, ++I)
4452 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4453 return;
4454 }
4455
4456 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4457 if (!Method)
4458 return;
4459
4460 // Handle Objective-C methods.
4461 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4462 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4463
4464 if (Methods.empty())
4465 return;
4466
4467 *num_overridden = Methods.size();
4468 *overridden = new CXCursor [Methods.size()];
4469 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4470 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4471}
4472
4473void clang_disposeOverriddenCursors(CXCursor *overridden) {
4474 delete [] overridden;
4475}
4476
Douglas Gregorecdcb882010-10-20 22:00:55 +00004477CXFile clang_getIncludedFile(CXCursor cursor) {
4478 if (cursor.kind != CXCursor_InclusionDirective)
4479 return 0;
4480
4481 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4482 return (void *)ID->getFile();
4483}
4484
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004485} // end: extern "C"
4486
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004487
4488//===----------------------------------------------------------------------===//
4489// C++ AST instrospection.
4490//===----------------------------------------------------------------------===//
4491
4492extern "C" {
4493unsigned clang_CXXMethod_isStatic(CXCursor C) {
4494 if (!clang_isDeclaration(C.kind))
4495 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004496
4497 CXXMethodDecl *Method = 0;
4498 Decl *D = cxcursor::getCursorDecl(C);
4499 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4500 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4501 else
4502 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4503 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004504}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004505
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004506} // end: extern "C"
4507
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004508//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004509// Attribute introspection.
4510//===----------------------------------------------------------------------===//
4511
4512extern "C" {
4513CXType clang_getIBOutletCollectionType(CXCursor C) {
4514 if (C.kind != CXCursor_IBOutletCollectionAttr)
4515 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4516
4517 IBOutletCollectionAttr *A =
4518 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4519
4520 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4521}
4522} // end: extern "C"
4523
4524//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004525// CXString Operations.
4526//===----------------------------------------------------------------------===//
4527
4528extern "C" {
4529const char *clang_getCString(CXString string) {
4530 return string.Spelling;
4531}
4532
4533void clang_disposeString(CXString string) {
4534 if (string.MustFreeString && string.Spelling)
4535 free((void*)string.Spelling);
4536}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004537
Ted Kremenekfb480492010-01-13 21:46:36 +00004538} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004539
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004540namespace clang { namespace cxstring {
4541CXString createCXString(const char *String, bool DupString){
4542 CXString Str;
4543 if (DupString) {
4544 Str.Spelling = strdup(String);
4545 Str.MustFreeString = 1;
4546 } else {
4547 Str.Spelling = String;
4548 Str.MustFreeString = 0;
4549 }
4550 return Str;
4551}
4552
4553CXString createCXString(llvm::StringRef String, bool DupString) {
4554 CXString Result;
4555 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4556 char *Spelling = (char *)malloc(String.size() + 1);
4557 memmove(Spelling, String.data(), String.size());
4558 Spelling[String.size()] = 0;
4559 Result.Spelling = Spelling;
4560 Result.MustFreeString = 1;
4561 } else {
4562 Result.Spelling = String.data();
4563 Result.MustFreeString = 0;
4564 }
4565 return Result;
4566}
4567}}
4568
Ted Kremenek04bb7162010-01-22 22:44:15 +00004569//===----------------------------------------------------------------------===//
4570// Misc. utility functions.
4571//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004572
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004573/// Default to using an 8 MB stack size on "safety" threads.
4574static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004575
4576namespace clang {
4577
4578bool RunSafely(llvm::CrashRecoveryContext &CRC,
4579 void (*Fn)(void*), void *UserData) {
4580 if (unsigned Size = GetSafetyThreadStackSize())
4581 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4582 return CRC.RunSafely(Fn, UserData);
4583}
4584
4585unsigned GetSafetyThreadStackSize() {
4586 return SafetyStackThreadSize;
4587}
4588
4589void SetSafetyThreadStackSize(unsigned Value) {
4590 SafetyStackThreadSize = Value;
4591}
4592
4593}
4594
Ted Kremenek04bb7162010-01-22 22:44:15 +00004595extern "C" {
4596
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004597CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004598 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004599}
4600
4601} // end: extern "C"