blob: 496833c7234d8dd2e037c5436576fe998b3f8445 [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.
Douglas Gregor27a31fe2010-11-09 05:52:02 +0000107 // FIXME: How do do this with a macro instantiation location?
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000108 SourceLocation EndLoc = R.getEnd();
Chris Lattner0a76aae2010-06-18 22:45:06 +0000109 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000110 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000111 EndLoc = EndLoc.getFileLocWithOffset(Length);
112 }
113
114 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
115 R.getBegin().getRawEncoding(),
116 EndLoc.getRawEncoding() };
117 return Result;
118}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000119
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000120//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000121// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000122//===----------------------------------------------------------------------===//
123
Steve Naroff89922f82009-08-31 00:59:03 +0000124namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000125
Douglas Gregorb1373d02010-01-20 20:59:29 +0000126// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000127class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000128 public TypeLocVisitor<CursorVisitor, bool>,
129 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000130{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000131 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000132 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000133
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000134 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000135 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000136
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000137 /// \brief The declaration that serves at the parent of any statement or
138 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000139 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000140
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000141 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000142 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000143
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000144 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000145 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000146
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000147 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
148 // to the visitor. Declarations with a PCH level greater than this value will
149 // be suppressed.
150 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000151
152 /// \brief When valid, a source range to which the cursor should restrict
153 /// its search.
154 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000155
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000156 // FIXME: Eventually remove. This part of a hack to support proper
157 // iteration over all Decls contained lexically within an ObjC container.
158 DeclContext::decl_iterator *DI_current;
159 DeclContext::decl_iterator DE_current;
160
Douglas Gregorb1373d02010-01-20 20:59:29 +0000161 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000162 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000163 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000164
165 /// \brief Determine whether this particular source range comes before, comes
166 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000167 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000168 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000169 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
170
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000171 class SetParentRAII {
172 CXCursor &Parent;
173 Decl *&StmtParent;
174 CXCursor OldParent;
175
176 public:
177 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
178 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
179 {
180 Parent = NewParent;
181 if (clang_isDeclaration(Parent.kind))
182 StmtParent = getCursorDecl(Parent);
183 }
184
185 ~SetParentRAII() {
186 Parent = OldParent;
187 if (clang_isDeclaration(Parent.kind))
188 StmtParent = getCursorDecl(Parent);
189 }
190 };
191
Steve Naroff89922f82009-08-31 00:59:03 +0000192public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000193 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
194 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000195 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000196 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000197 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
198 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000199 {
200 Parent.kind = CXCursor_NoDeclFound;
201 Parent.data[0] = 0;
202 Parent.data[1] = 0;
203 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000204 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000205 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000206
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000207 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000208
209 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
210 getPreprocessedEntities();
211
Douglas Gregorb1373d02010-01-20 20:59:29 +0000212 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000213
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000214 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000215 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000216 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000217 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000218 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000219 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000220 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
221 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000222 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000223 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000224 bool VisitClassTemplatePartialSpecializationDecl(
225 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000226 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000227 bool VisitEnumConstantDecl(EnumConstantDecl *D);
228 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
229 bool VisitFunctionDecl(FunctionDecl *ND);
230 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000231 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000232 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000233 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000234 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000235 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000236 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
237 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
238 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
239 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000240 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000241 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
242 bool VisitObjCImplDecl(ObjCImplDecl *D);
243 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
244 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000245 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
246 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
247 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000248 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000249 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000250 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000251 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000252 bool VisitUsingDecl(UsingDecl *D);
253 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
254 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000255
Douglas Gregor01829d32010-08-31 14:41:23 +0000256 // Name visitor
257 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000258 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000259
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000260 // Template visitors
261 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000262 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000263 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
264
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000265 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000266 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000267 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000268 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000269 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
270 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000271 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000272 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000273 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000274 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
275 bool VisitPointerTypeLoc(PointerTypeLoc TL);
276 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
277 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
278 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
279 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000280 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000281 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000282 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000283 // FIXME: Implement visitors here when the unimplemented TypeLocs get
284 // implemented
285 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
286 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000287
Douglas Gregora59e3902010-01-21 23:27:09 +0000288 // Statement visitors
289 bool VisitStmt(Stmt *S);
290 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000291 bool VisitGotoStmt(GotoStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000292 bool VisitIfStmt(IfStmt *S);
293 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000294 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000295 bool VisitWhileStmt(WhileStmt *S);
296 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000297
Douglas Gregor336fd812010-01-23 00:40:08 +0000298 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000299 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000300 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000301 bool VisitBlockExpr(BlockExpr *B);
Ted Kremenek04c450c2010-11-08 21:14:15 +0000302 bool VisitBinaryOperator(BinaryOperator *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000303 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000304 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000305 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000306 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000307 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000308 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfbb4c982010-09-02 21:07:44 +0000309 bool VisitMemberExpr(MemberExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000310 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000311 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
312 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000313 bool VisitInitListExpr(InitListExpr *E);
314 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000315 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000316 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000317 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000318 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
319 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000320 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000321 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000322 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000323 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000324 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000325 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000326 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000327 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000328};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000329
Ted Kremenekab188932010-01-05 19:32:54 +0000330} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000331
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000332static SourceRange getRawCursorExtent(CXCursor C);
333
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000334RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000335 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
336}
337
Douglas Gregorb1373d02010-01-20 20:59:29 +0000338/// \brief Visit the given cursor and, if requested by the visitor,
339/// its children.
340///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000341/// \param Cursor the cursor to visit.
342///
343/// \param CheckRegionOfInterest if true, then the caller already checked that
344/// this cursor is within the region of interest.
345///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000346/// \returns true if the visitation should be aborted, false if it
347/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000348bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000349 if (clang_isInvalid(Cursor.kind))
350 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000351
Douglas Gregorb1373d02010-01-20 20:59:29 +0000352 if (clang_isDeclaration(Cursor.kind)) {
353 Decl *D = getCursorDecl(Cursor);
354 assert(D && "Invalid declaration cursor");
355 if (D->getPCHLevel() > MaxPCHLevel)
356 return false;
357
358 if (D->isImplicit())
359 return false;
360 }
361
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000362 // If we have a range of interest, and this cursor doesn't intersect with it,
363 // we're done.
364 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000365 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000366 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000367 return false;
368 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000369
Douglas Gregorb1373d02010-01-20 20:59:29 +0000370 switch (Visitor(Cursor, Parent, ClientData)) {
371 case CXChildVisit_Break:
372 return true;
373
374 case CXChildVisit_Continue:
375 return false;
376
377 case CXChildVisit_Recurse:
378 return VisitChildren(Cursor);
379 }
380
Douglas Gregorfd643772010-01-25 16:45:46 +0000381 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000382}
383
Douglas Gregor788f5a12010-03-20 00:41:21 +0000384std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
385CursorVisitor::getPreprocessedEntities() {
386 PreprocessingRecord &PPRec
387 = *TU->getPreprocessor().getPreprocessingRecord();
388
389 bool OnlyLocalDecls
390 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
391
392 // There is no region of interest; we have to walk everything.
393 if (RegionOfInterest.isInvalid())
394 return std::make_pair(PPRec.begin(OnlyLocalDecls),
395 PPRec.end(OnlyLocalDecls));
396
397 // Find the file in which the region of interest lands.
398 SourceManager &SM = TU->getSourceManager();
399 std::pair<FileID, unsigned> Begin
400 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
401 std::pair<FileID, unsigned> End
402 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
403
404 // The region of interest spans files; we have to walk everything.
405 if (Begin.first != End.first)
406 return std::make_pair(PPRec.begin(OnlyLocalDecls),
407 PPRec.end(OnlyLocalDecls));
408
409 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
410 = TU->getPreprocessedEntitiesByFile();
411 if (ByFileMap.empty()) {
412 // Build the mapping from files to sets of preprocessed entities.
413 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
414 EEnd = PPRec.end(OnlyLocalDecls);
415 E != EEnd; ++E) {
416 std::pair<FileID, unsigned> P
417 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
418 ByFileMap[P.first].push_back(*E);
419 }
420 }
421
422 return std::make_pair(ByFileMap[Begin.first].begin(),
423 ByFileMap[Begin.first].end());
424}
425
Douglas Gregorb1373d02010-01-20 20:59:29 +0000426/// \brief Visit the children of the given cursor.
427///
428/// \returns true if the visitation should be aborted, false if it
429/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000430bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000431 if (clang_isReference(Cursor.kind)) {
432 // By definition, references have no children.
433 return false;
434 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000435
436 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000437 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000438 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000439
Douglas Gregorb1373d02010-01-20 20:59:29 +0000440 if (clang_isDeclaration(Cursor.kind)) {
441 Decl *D = getCursorDecl(Cursor);
442 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000443 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000444 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000445
Douglas Gregora59e3902010-01-21 23:27:09 +0000446 if (clang_isStatement(Cursor.kind))
447 return Visit(getCursorStmt(Cursor));
448 if (clang_isExpression(Cursor.kind))
449 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000450
Douglas Gregorb1373d02010-01-20 20:59:29 +0000451 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000452 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000453 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
454 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000455 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
456 TLEnd = CXXUnit->top_level_end();
457 TL != TLEnd; ++TL) {
458 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000459 return true;
460 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000461 } else if (VisitDeclContext(
462 CXXUnit->getASTContext().getTranslationUnitDecl()))
463 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000464
Douglas Gregor0396f462010-03-19 05:22:59 +0000465 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000466 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000467 // FIXME: Once we have the ability to deserialize a preprocessing record,
468 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000469 PreprocessingRecord::iterator E, EEnd;
470 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000471 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
472 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
473 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000474
Douglas Gregor0396f462010-03-19 05:22:59 +0000475 continue;
476 }
477
478 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
479 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
480 return true;
481
482 continue;
483 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000484
485 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
486 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
487 return true;
488
489 continue;
490 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000491 }
492 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000493 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000494 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000495
Douglas Gregorb1373d02010-01-20 20:59:29 +0000496 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000497 return false;
498}
499
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000500bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000501 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
502 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000503
Ted Kremenek664cffd2010-07-22 11:30:19 +0000504 if (Stmt *Body = B->getBody())
505 return Visit(MakeCXCursor(Body, StmtParent, TU));
506
507 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000508}
509
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000510llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
511 if (RegionOfInterest.isValid()) {
512 SourceRange Range = getRawCursorExtent(Cursor);
513 if (Range.isInvalid())
514 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000515
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000516 switch (CompareRegionOfInterest(Range)) {
517 case RangeBefore:
518 // This declaration comes before the region of interest; skip it.
519 return llvm::Optional<bool>();
520
521 case RangeAfter:
522 // This declaration comes after the region of interest; we're done.
523 return false;
524
525 case RangeOverlap:
526 // This declaration overlaps the region of interest; visit it.
527 break;
528 }
529 }
530 return true;
531}
532
533bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
534 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
535
536 // FIXME: Eventually remove. This part of a hack to support proper
537 // iteration over all Decls contained lexically within an ObjC container.
538 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
539 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
540
541 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000542 Decl *D = *I;
543 if (D->getLexicalDeclContext() != DC)
544 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000545 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000546 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
547 if (!V.hasValue())
548 continue;
549 if (!V.getValue())
550 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000551 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000552 return true;
553 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000554 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000555}
556
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000557bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
558 llvm_unreachable("Translation units are visited directly by Visit()");
559 return false;
560}
561
562bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
563 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
564 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000565
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000566 return false;
567}
568
569bool CursorVisitor::VisitTagDecl(TagDecl *D) {
570 return VisitDeclContext(D);
571}
572
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000573bool CursorVisitor::VisitClassTemplateSpecializationDecl(
574 ClassTemplateSpecializationDecl *D) {
575 bool ShouldVisitBody = false;
576 switch (D->getSpecializationKind()) {
577 case TSK_Undeclared:
578 case TSK_ImplicitInstantiation:
579 // Nothing to visit
580 return false;
581
582 case TSK_ExplicitInstantiationDeclaration:
583 case TSK_ExplicitInstantiationDefinition:
584 break;
585
586 case TSK_ExplicitSpecialization:
587 ShouldVisitBody = true;
588 break;
589 }
590
591 // Visit the template arguments used in the specialization.
592 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
593 TypeLoc TL = SpecType->getTypeLoc();
594 if (TemplateSpecializationTypeLoc *TSTLoc
595 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
596 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
597 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
598 return true;
599 }
600 }
601
602 if (ShouldVisitBody && VisitCXXRecordDecl(D))
603 return true;
604
605 return false;
606}
607
Douglas Gregor74dbe642010-08-31 19:31:58 +0000608bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
609 ClassTemplatePartialSpecializationDecl *D) {
610 // FIXME: Visit the "outer" template parameter lists on the TagDecl
611 // before visiting these template parameters.
612 if (VisitTemplateParameters(D->getTemplateParameters()))
613 return true;
614
615 // Visit the partial specialization arguments.
616 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
617 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
618 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
619 return true;
620
621 return VisitCXXRecordDecl(D);
622}
623
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000624bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000625 // Visit the default argument.
626 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
627 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
628 if (Visit(DefArg->getTypeLoc()))
629 return true;
630
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000631 return false;
632}
633
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000634bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
635 if (Expr *Init = D->getInitExpr())
636 return Visit(MakeCXCursor(Init, StmtParent, TU));
637 return false;
638}
639
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000640bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
641 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
642 if (Visit(TSInfo->getTypeLoc()))
643 return true;
644
645 return false;
646}
647
Douglas Gregora67e03f2010-09-09 21:42:20 +0000648/// \brief Compare two base or member initializers based on their source order.
649static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
650 CXXBaseOrMemberInitializer const * const *X
651 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
652 CXXBaseOrMemberInitializer const * const *Y
653 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
654
655 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
656 return -1;
657 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
658 return 1;
659 else
660 return 0;
661}
662
Douglas Gregorb1373d02010-01-20 20:59:29 +0000663bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000664 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
665 // Visit the function declaration's syntactic components in the order
666 // written. This requires a bit of work.
667 TypeLoc TL = TSInfo->getTypeLoc();
668 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
669
670 // If we have a function declared directly (without the use of a typedef),
671 // visit just the return type. Otherwise, just visit the function's type
672 // now.
673 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
674 (!FTL && Visit(TL)))
675 return true;
676
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000677 // Visit the nested-name-specifier, if present.
678 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
679 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
680 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000681
682 // Visit the declaration name.
683 if (VisitDeclarationNameInfo(ND->getNameInfo()))
684 return true;
685
686 // FIXME: Visit explicitly-specified template arguments!
687
688 // Visit the function parameters, if we have a function type.
689 if (FTL && VisitFunctionTypeLoc(*FTL, true))
690 return true;
691
692 // FIXME: Attributes?
693 }
694
Douglas Gregora67e03f2010-09-09 21:42:20 +0000695 if (ND->isThisDeclarationADefinition()) {
696 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
697 // Find the initializers that were written in the source.
698 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
699 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
700 IEnd = Constructor->init_end();
701 I != IEnd; ++I) {
702 if (!(*I)->isWritten())
703 continue;
704
705 WrittenInits.push_back(*I);
706 }
707
708 // Sort the initializers in source order
709 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
710 &CompareCXXBaseOrMemberInitializers);
711
712 // Visit the initializers in source order
713 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
714 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
715 if (Init->isMemberInitializer()) {
716 if (Visit(MakeCursorMemberRef(Init->getMember(),
717 Init->getMemberLocation(), TU)))
718 return true;
719 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
720 if (Visit(BaseInfo->getTypeLoc()))
721 return true;
722 }
723
724 // Visit the initializer value.
725 if (Expr *Initializer = Init->getInit())
726 if (Visit(MakeCXCursor(Initializer, ND, TU)))
727 return true;
728 }
729 }
730
731 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
732 return true;
733 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000734
Douglas Gregorb1373d02010-01-20 20:59:29 +0000735 return false;
736}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000737
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000738bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
739 if (VisitDeclaratorDecl(D))
740 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000741
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000742 if (Expr *BitWidth = D->getBitWidth())
743 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000744
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000745 return false;
746}
747
748bool CursorVisitor::VisitVarDecl(VarDecl *D) {
749 if (VisitDeclaratorDecl(D))
750 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000751
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000752 if (Expr *Init = D->getInit())
753 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000754
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000755 return false;
756}
757
Douglas Gregor84b51d72010-09-01 20:16:53 +0000758bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
759 if (VisitDeclaratorDecl(D))
760 return true;
761
762 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
763 if (Expr *DefArg = D->getDefaultArgument())
764 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
765
766 return false;
767}
768
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000769bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
770 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
771 // before visiting these template parameters.
772 if (VisitTemplateParameters(D->getTemplateParameters()))
773 return true;
774
775 return VisitFunctionDecl(D->getTemplatedDecl());
776}
777
Douglas Gregor39d6f072010-08-31 19:02:00 +0000778bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
779 // FIXME: Visit the "outer" template parameter lists on the TagDecl
780 // before visiting these template parameters.
781 if (VisitTemplateParameters(D->getTemplateParameters()))
782 return true;
783
784 return VisitCXXRecordDecl(D->getTemplatedDecl());
785}
786
Douglas Gregor84b51d72010-09-01 20:16:53 +0000787bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
788 if (VisitTemplateParameters(D->getTemplateParameters()))
789 return true;
790
791 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
792 VisitTemplateArgumentLoc(D->getDefaultArgument()))
793 return true;
794
795 return false;
796}
797
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000798bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000799 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
800 if (Visit(TSInfo->getTypeLoc()))
801 return true;
802
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000803 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000804 PEnd = ND->param_end();
805 P != PEnd; ++P) {
806 if (Visit(MakeCXCursor(*P, TU)))
807 return true;
808 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000809
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000810 if (ND->isThisDeclarationADefinition() &&
811 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
812 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000813
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000814 return false;
815}
816
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000817namespace {
818 struct ContainerDeclsSort {
819 SourceManager &SM;
820 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
821 bool operator()(Decl *A, Decl *B) {
822 SourceLocation L_A = A->getLocStart();
823 SourceLocation L_B = B->getLocStart();
824 assert(L_A.isValid() && L_B.isValid());
825 return SM.isBeforeInTranslationUnit(L_A, L_B);
826 }
827 };
828}
829
Douglas Gregora59e3902010-01-21 23:27:09 +0000830bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000831 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
832 // an @implementation can lexically contain Decls that are not properly
833 // nested in the AST. When we identify such cases, we need to retrofit
834 // this nesting here.
835 if (!DI_current)
836 return VisitDeclContext(D);
837
838 // Scan the Decls that immediately come after the container
839 // in the current DeclContext. If any fall within the
840 // container's lexical region, stash them into a vector
841 // for later processing.
842 llvm::SmallVector<Decl *, 24> DeclsInContainer;
843 SourceLocation EndLoc = D->getSourceRange().getEnd();
844 SourceManager &SM = TU->getSourceManager();
845 if (EndLoc.isValid()) {
846 DeclContext::decl_iterator next = *DI_current;
847 while (++next != DE_current) {
848 Decl *D_next = *next;
849 if (!D_next)
850 break;
851 SourceLocation L = D_next->getLocStart();
852 if (!L.isValid())
853 break;
854 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
855 *DI_current = next;
856 DeclsInContainer.push_back(D_next);
857 continue;
858 }
859 break;
860 }
861 }
862
863 // The common case.
864 if (DeclsInContainer.empty())
865 return VisitDeclContext(D);
866
867 // Get all the Decls in the DeclContext, and sort them with the
868 // additional ones we've collected. Then visit them.
869 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
870 I!=E; ++I) {
871 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000872 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
873 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000874 continue;
875 DeclsInContainer.push_back(subDecl);
876 }
877
878 // Now sort the Decls so that they appear in lexical order.
879 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
880 ContainerDeclsSort(SM));
881
882 // Now visit the decls.
883 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
884 E = DeclsInContainer.end(); I != E; ++I) {
885 CXCursor Cursor = MakeCXCursor(*I, TU);
886 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
887 if (!V.hasValue())
888 continue;
889 if (!V.getValue())
890 return false;
891 if (Visit(Cursor, true))
892 return true;
893 }
894 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000895}
896
Douglas Gregorb1373d02010-01-20 20:59:29 +0000897bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000898 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
899 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000900 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000901
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000902 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
903 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
904 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000905 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000906 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000907
Douglas Gregora59e3902010-01-21 23:27:09 +0000908 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000909}
910
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000911bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
912 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
913 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
914 E = PID->protocol_end(); I != E; ++I, ++PL)
915 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
916 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000917
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000918 return VisitObjCContainerDecl(PID);
919}
920
Ted Kremenek23173d72010-05-18 21:09:07 +0000921bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000922 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000923 return true;
924
Ted Kremenek23173d72010-05-18 21:09:07 +0000925 // FIXME: This implements a workaround with @property declarations also being
926 // installed in the DeclContext for the @interface. Eventually this code
927 // should be removed.
928 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
929 if (!CDecl || !CDecl->IsClassExtension())
930 return false;
931
932 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
933 if (!ID)
934 return false;
935
936 IdentifierInfo *PropertyId = PD->getIdentifier();
937 ObjCPropertyDecl *prevDecl =
938 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
939
940 if (!prevDecl)
941 return false;
942
943 // Visit synthesized methods since they will be skipped when visiting
944 // the @interface.
945 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000946 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000947 if (Visit(MakeCXCursor(MD, TU)))
948 return true;
949
950 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000951 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000952 if (Visit(MakeCXCursor(MD, TU)))
953 return true;
954
955 return false;
956}
957
Douglas Gregorb1373d02010-01-20 20:59:29 +0000958bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000959 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000960 if (D->getSuperClass() &&
961 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000962 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000963 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000964 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000965
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000966 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
967 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
968 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000969 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000970 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000971
Douglas Gregora59e3902010-01-21 23:27:09 +0000972 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000973}
974
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000975bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
976 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000977}
978
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000979bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000980 // 'ID' could be null when dealing with invalid code.
981 if (ObjCInterfaceDecl *ID = D->getClassInterface())
982 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
983 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000984
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000985 return VisitObjCImplDecl(D);
986}
987
988bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
989#if 0
990 // Issue callbacks for super class.
991 // FIXME: No source location information!
992 if (D->getSuperClass() &&
993 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000994 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000995 TU)))
996 return true;
997#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000998
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000999 return VisitObjCImplDecl(D);
1000}
1001
1002bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1003 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1004 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1005 E = D->protocol_end();
1006 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001007 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001008 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001009
1010 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001011}
1012
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001013bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1014 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1015 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1016 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001017
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001018 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001019}
1020
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001021bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1022 return VisitDeclContext(D);
1023}
1024
Douglas Gregor69319002010-08-31 23:48:11 +00001025bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001026 // Visit nested-name-specifier.
1027 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1028 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1029 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001030
1031 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1032 D->getTargetNameLoc(), TU));
1033}
1034
Douglas Gregor7e242562010-09-01 19:52:22 +00001035bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001036 // Visit nested-name-specifier.
1037 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1038 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1039 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001040
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001041 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1042 return true;
1043
Douglas Gregor7e242562010-09-01 19:52:22 +00001044 return VisitDeclarationNameInfo(D->getNameInfo());
1045}
1046
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001047bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001048 // Visit nested-name-specifier.
1049 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1050 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1051 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001052
1053 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1054 D->getIdentLocation(), TU));
1055}
1056
Douglas Gregor7e242562010-09-01 19:52:22 +00001057bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001058 // Visit nested-name-specifier.
1059 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1060 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1061 return true;
1062
Douglas Gregor7e242562010-09-01 19:52:22 +00001063 return VisitDeclarationNameInfo(D->getNameInfo());
1064}
1065
1066bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1067 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001068 // Visit nested-name-specifier.
1069 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1070 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1071 return true;
1072
Douglas Gregor7e242562010-09-01 19:52:22 +00001073 return false;
1074}
1075
Douglas Gregor01829d32010-08-31 14:41:23 +00001076bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1077 switch (Name.getName().getNameKind()) {
1078 case clang::DeclarationName::Identifier:
1079 case clang::DeclarationName::CXXLiteralOperatorName:
1080 case clang::DeclarationName::CXXOperatorName:
1081 case clang::DeclarationName::CXXUsingDirective:
1082 return false;
1083
1084 case clang::DeclarationName::CXXConstructorName:
1085 case clang::DeclarationName::CXXDestructorName:
1086 case clang::DeclarationName::CXXConversionFunctionName:
1087 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1088 return Visit(TSInfo->getTypeLoc());
1089 return false;
1090
1091 case clang::DeclarationName::ObjCZeroArgSelector:
1092 case clang::DeclarationName::ObjCOneArgSelector:
1093 case clang::DeclarationName::ObjCMultiArgSelector:
1094 // FIXME: Per-identifier location info?
1095 return false;
1096 }
1097
1098 return false;
1099}
1100
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001101bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1102 SourceRange Range) {
1103 // FIXME: This whole routine is a hack to work around the lack of proper
1104 // source information in nested-name-specifiers (PR5791). Since we do have
1105 // a beginning source location, we can visit the first component of the
1106 // nested-name-specifier, if it's a single-token component.
1107 if (!NNS)
1108 return false;
1109
1110 // Get the first component in the nested-name-specifier.
1111 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1112 NNS = Prefix;
1113
1114 switch (NNS->getKind()) {
1115 case NestedNameSpecifier::Namespace:
1116 // FIXME: The token at this source location might actually have been a
1117 // namespace alias, but we don't model that. Lame!
1118 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1119 TU));
1120
1121 case NestedNameSpecifier::TypeSpec: {
1122 // If the type has a form where we know that the beginning of the source
1123 // range matches up with a reference cursor. Visit the appropriate reference
1124 // cursor.
1125 Type *T = NNS->getAsType();
1126 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1127 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1128 if (const TagType *Tag = dyn_cast<TagType>(T))
1129 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1130 if (const TemplateSpecializationType *TST
1131 = dyn_cast<TemplateSpecializationType>(T))
1132 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1133 break;
1134 }
1135
1136 case NestedNameSpecifier::TypeSpecWithTemplate:
1137 case NestedNameSpecifier::Global:
1138 case NestedNameSpecifier::Identifier:
1139 break;
1140 }
1141
1142 return false;
1143}
1144
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001145bool CursorVisitor::VisitTemplateParameters(
1146 const TemplateParameterList *Params) {
1147 if (!Params)
1148 return false;
1149
1150 for (TemplateParameterList::const_iterator P = Params->begin(),
1151 PEnd = Params->end();
1152 P != PEnd; ++P) {
1153 if (Visit(MakeCXCursor(*P, TU)))
1154 return true;
1155 }
1156
1157 return false;
1158}
1159
Douglas Gregor0b36e612010-08-31 20:37:03 +00001160bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1161 switch (Name.getKind()) {
1162 case TemplateName::Template:
1163 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1164
1165 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001166 // Visit the overloaded template set.
1167 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1168 return true;
1169
Douglas Gregor0b36e612010-08-31 20:37:03 +00001170 return false;
1171
1172 case TemplateName::DependentTemplate:
1173 // FIXME: Visit nested-name-specifier.
1174 return false;
1175
1176 case TemplateName::QualifiedTemplate:
1177 // FIXME: Visit nested-name-specifier.
1178 return Visit(MakeCursorTemplateRef(
1179 Name.getAsQualifiedTemplateName()->getDecl(),
1180 Loc, TU));
1181 }
1182
1183 return false;
1184}
1185
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001186bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1187 switch (TAL.getArgument().getKind()) {
1188 case TemplateArgument::Null:
1189 case TemplateArgument::Integral:
1190 return false;
1191
1192 case TemplateArgument::Pack:
1193 // FIXME: Implement when variadic templates come along.
1194 return false;
1195
1196 case TemplateArgument::Type:
1197 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1198 return Visit(TSInfo->getTypeLoc());
1199 return false;
1200
1201 case TemplateArgument::Declaration:
1202 if (Expr *E = TAL.getSourceDeclExpression())
1203 return Visit(MakeCXCursor(E, StmtParent, TU));
1204 return false;
1205
1206 case TemplateArgument::Expression:
1207 if (Expr *E = TAL.getSourceExpression())
1208 return Visit(MakeCXCursor(E, StmtParent, TU));
1209 return false;
1210
1211 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001212 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1213 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001214 }
1215
1216 return false;
1217}
1218
Ted Kremeneka0536d82010-05-07 01:04:29 +00001219bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1220 return VisitDeclContext(D);
1221}
1222
Douglas Gregor01829d32010-08-31 14:41:23 +00001223bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1224 return Visit(TL.getUnqualifiedLoc());
1225}
1226
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001227bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1228 ASTContext &Context = TU->getASTContext();
1229
1230 // Some builtin types (such as Objective-C's "id", "sel", and
1231 // "Class") have associated declarations. Create cursors for those.
1232 QualType VisitType;
1233 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001234 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001235 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001236 case BuiltinType::Char_U:
1237 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001238 case BuiltinType::Char16:
1239 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001240 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001241 case BuiltinType::UInt:
1242 case BuiltinType::ULong:
1243 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001244 case BuiltinType::UInt128:
1245 case BuiltinType::Char_S:
1246 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001247 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001248 case BuiltinType::Short:
1249 case BuiltinType::Int:
1250 case BuiltinType::Long:
1251 case BuiltinType::LongLong:
1252 case BuiltinType::Int128:
1253 case BuiltinType::Float:
1254 case BuiltinType::Double:
1255 case BuiltinType::LongDouble:
1256 case BuiltinType::NullPtr:
1257 case BuiltinType::Overload:
1258 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001259 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001260
1261 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001262 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001263
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001264 case BuiltinType::ObjCId:
1265 VisitType = Context.getObjCIdType();
1266 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001267
1268 case BuiltinType::ObjCClass:
1269 VisitType = Context.getObjCClassType();
1270 break;
1271
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001272 case BuiltinType::ObjCSel:
1273 VisitType = Context.getObjCSelType();
1274 break;
1275 }
1276
1277 if (!VisitType.isNull()) {
1278 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001279 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001280 TU));
1281 }
1282
1283 return false;
1284}
1285
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001286bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1287 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1288}
1289
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001290bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1291 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1292}
1293
1294bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1295 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1296}
1297
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001298bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001299 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001300 // no context information with which we can match up the depth/index in the
1301 // type to the appropriate
1302 return false;
1303}
1304
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001305bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1306 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1307 return true;
1308
John McCallc12c5bb2010-05-15 11:32:37 +00001309 return false;
1310}
1311
1312bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1313 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1314 return true;
1315
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001316 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1317 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1318 TU)))
1319 return true;
1320 }
1321
1322 return false;
1323}
1324
1325bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001326 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001327}
1328
1329bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1330 return Visit(TL.getPointeeLoc());
1331}
1332
1333bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1334 return Visit(TL.getPointeeLoc());
1335}
1336
1337bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1338 return Visit(TL.getPointeeLoc());
1339}
1340
1341bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001342 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001343}
1344
1345bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001346 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001347}
1348
Douglas Gregor01829d32010-08-31 14:41:23 +00001349bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1350 bool SkipResultType) {
1351 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001352 return true;
1353
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001354 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001355 if (Decl *D = TL.getArg(I))
1356 if (Visit(MakeCXCursor(D, TU)))
1357 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001358
1359 return false;
1360}
1361
1362bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1363 if (Visit(TL.getElementLoc()))
1364 return true;
1365
1366 if (Expr *Size = TL.getSizeExpr())
1367 return Visit(MakeCXCursor(Size, StmtParent, TU));
1368
1369 return false;
1370}
1371
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001372bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1373 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001374 // Visit the template name.
1375 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1376 TL.getTemplateNameLoc()))
1377 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001378
1379 // Visit the template arguments.
1380 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1381 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1382 return true;
1383
1384 return false;
1385}
1386
Douglas Gregor2332c112010-01-21 20:48:56 +00001387bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1388 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1389}
1390
1391bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1392 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1393 return Visit(TSInfo->getTypeLoc());
1394
1395 return false;
1396}
1397
Douglas Gregora59e3902010-01-21 23:27:09 +00001398bool CursorVisitor::VisitStmt(Stmt *S) {
1399 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1400 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001401 if (Stmt *C = *Child)
1402 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1403 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001404 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001405
Douglas Gregora59e3902010-01-21 23:27:09 +00001406 return false;
1407}
1408
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001409bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1410 // Specially handle CaseStmts because they can be nested, e.g.:
1411 //
1412 // case 1:
1413 // case 2:
1414 //
1415 // In this case the second CaseStmt is the child of the first. Walking
1416 // these recursively can blow out the stack.
1417 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1418 while (true) {
1419 // Set the Parent field to Cursor, then back to its old value once we're
1420 // done.
1421 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1422
1423 if (Stmt *LHS = S->getLHS())
1424 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1425 return true;
1426 if (Stmt *RHS = S->getRHS())
1427 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1428 return true;
1429 if (Stmt *SubStmt = S->getSubStmt()) {
1430 if (!isa<CaseStmt>(SubStmt))
1431 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1432
1433 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1434 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1435 Cursor = MakeCXCursor(CS, StmtParent, TU);
1436 if (RegionOfInterest.isValid()) {
1437 SourceRange Range = CS->getSourceRange();
1438 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1439 return false;
1440 }
1441
1442 switch (Visitor(Cursor, Parent, ClientData)) {
1443 case CXChildVisit_Break: return true;
1444 case CXChildVisit_Continue: return false;
1445 case CXChildVisit_Recurse:
1446 // Perform tail-recursion manually.
1447 S = CS;
1448 continue;
1449 }
1450 }
1451 return false;
1452 }
1453}
1454
Douglas Gregora59e3902010-01-21 23:27:09 +00001455bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001456 bool isFirst = true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001457 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1458 D != DEnd; ++D) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001459 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001460 return true;
Ted Kremenek007a7c92010-11-01 23:26:51 +00001461 isFirst = false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001462 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001463
Douglas Gregora59e3902010-01-21 23:27:09 +00001464 return false;
1465}
1466
Douglas Gregor36897b02010-09-10 00:22:18 +00001467bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1468 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1469}
1470
Douglas Gregorf5bab412010-01-22 01:00:11 +00001471bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1472 if (VarDecl *Var = S->getConditionVariable()) {
1473 if (Visit(MakeCXCursor(Var, TU)))
1474 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001475 }
1476
Douglas Gregor263b47b2010-01-25 16:12:32 +00001477 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1478 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001479 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1480 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001481 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1482 return true;
1483
1484 return false;
1485}
1486
1487bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1488 if (VarDecl *Var = S->getConditionVariable()) {
1489 if (Visit(MakeCXCursor(Var, TU)))
1490 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001491 }
1492
Douglas Gregor263b47b2010-01-25 16:12:32 +00001493 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1494 return true;
1495 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1496 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001497
Douglas Gregor263b47b2010-01-25 16:12:32 +00001498 return false;
1499}
1500
1501bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1502 if (VarDecl *Var = S->getConditionVariable()) {
1503 if (Visit(MakeCXCursor(Var, TU)))
1504 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001505 }
1506
Douglas Gregor263b47b2010-01-25 16:12:32 +00001507 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1508 return true;
1509 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001510 return true;
1511
Douglas Gregor263b47b2010-01-25 16:12:32 +00001512 return false;
1513}
1514
1515bool CursorVisitor::VisitForStmt(ForStmt *S) {
1516 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1517 return true;
1518 if (VarDecl *Var = S->getConditionVariable()) {
1519 if (Visit(MakeCXCursor(Var, TU)))
1520 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001521 }
1522
Douglas Gregor263b47b2010-01-25 16:12:32 +00001523 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1524 return true;
1525 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1526 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001527 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1528 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001529
Douglas Gregorf5bab412010-01-22 01:00:11 +00001530 return false;
1531}
1532
Ted Kremenek04c450c2010-11-08 21:14:15 +00001533bool CursorVisitor::VisitBinaryOperator(BinaryOperator *B) {
1534 // We can blow the stack in some cases where we have deeply nested BinaryOperators,
1535 // often involving logical expressions, e.g.: '(x || y) || (y || z) || ...
1536 // To handle this, we visitation of BinaryOperators is data recursive instead of
1537 // directly recursive. This makes the algorithm more complicated, but handles
1538 // arbitrary depths. We should consider making the entire CursorVisitor data
1539 // recursive.
1540 typedef std::pair</* Current expression = */ Expr*, /* Parent = */ CXCursor>
1541 WorkListItem;
1542 typedef llvm::SmallVector<WorkListItem, 5> WorkList;
1543
1544 CXCursor Cursor = MakeCXCursor(B, StmtParent, TU);
1545 WorkList WL;
1546 WL.push_back(std::make_pair(B->getRHS(), Cursor));
1547 WL.push_back(std::make_pair(B->getLHS(), Cursor));
1548
1549 while (!WL.empty()) {
1550 // Dequeue the worklist item.
1551 WorkListItem LI = WL.back(); WL.pop_back(); Expr *Ex = LI.first;
1552
1553 // Set the Parent field, then back to its old value once we're done.
1554 SetParentRAII SetParent(Parent, StmtParent, LI.second);
1555
1556 // Update the current cursor.
1557 Cursor = MakeCXCursor(Ex, StmtParent, TU);
1558
1559 // For non-BinaryOperators, perform the default visitation.
1560 if (!isa<BinaryOperator>(Ex)) {
1561 if (Visit(Cursor)) {
1562 // Skip all other items in the worklist that also have
1563 // the same parent.
1564 while (!WL.empty()) {
1565 const WorkListItem &LIb = WL.back();
1566 if (LIb.second == LI.second)
1567 WL.pop_back();
1568 else
1569 break;
1570 }
1571 // If the worklist is now empty, we should immediately return
1572 // to the caller, since this is the base case.
1573 if (WL.empty())
1574 return true;
1575 }
1576 continue;
1577 }
1578 // For BinaryOperators, perform a custom visitation where we add the
1579 // children to a worklist.
1580 if (RegionOfInterest.isValid()) {
1581 SourceRange Range = getRawCursorExtent(Cursor);
1582 if (Range.isInvalid() || CompareRegionOfInterest(Range)) {
1583 // Proceed to the next item on the worklist.
1584 continue;
1585 }
1586 }
1587 switch (Visitor(Cursor, Parent, ClientData)) {
1588 case CXChildVisit_Break: {
1589 // Skip all other items in the worklist that also have
1590 // the same parent.
1591 while (!WL.empty()) {
1592 const WorkListItem &LIb = WL.back();
1593 if (LIb.second == LI.second)
1594 WL.pop_back();
1595 else
1596 break;
1597 }
1598 // If the worklist is now empty, we should immediately return
1599 // to the caller, since this is the base case.
1600 if (WL.empty())
1601 return true;
1602 break;
1603 }
1604 case CXChildVisit_Continue:
1605 break;
1606 case CXChildVisit_Recurse: {
1607 BinaryOperator *B = cast<BinaryOperator>(Ex);
1608 // FIXME: Note that we ignore parentheses, since these are often
1609 // unimportant during cursor visitation. If we care about these, we
1610 // can unroll the visitation one more level. Alternatively, we
1611 // can convert the entire visitor to be data recursive, eliminating
1612 // all edge cases.
1613 WL.push_back(std::make_pair(B->getRHS()->IgnoreParens(), Cursor));
1614 WL.push_back(std::make_pair(B->getLHS()->IgnoreParens(), Cursor));
1615 break;
1616 }
1617 }
1618 }
1619 return false;
1620}
1621
Douglas Gregor8947a752010-09-02 20:35:02 +00001622bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1623 // Visit nested-name-specifier, if present.
1624 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1625 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1626 return true;
1627
1628 // Visit declaration name.
1629 if (VisitDeclarationNameInfo(E->getNameInfo()))
1630 return true;
1631
1632 // Visit explicitly-specified template arguments.
1633 if (E->hasExplicitTemplateArgs()) {
1634 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1635 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1636 *ArgEnd = Arg + Args.NumTemplateArgs;
1637 Arg != ArgEnd; ++Arg)
1638 if (VisitTemplateArgumentLoc(*Arg))
1639 return true;
1640 }
1641
1642 return false;
1643}
1644
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001645bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1646 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1647 return true;
1648
1649 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1650 return true;
1651
1652 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1653 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1654 return true;
1655
1656 return false;
1657}
1658
Ted Kremenek3064ef92010-08-27 21:34:58 +00001659bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1660 if (D->isDefinition()) {
1661 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1662 E = D->bases_end(); I != E; ++I) {
1663 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1664 return true;
1665 }
1666 }
1667
1668 return VisitTagDecl(D);
1669}
1670
1671
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001672bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1673 return Visit(B->getBlockDecl());
1674}
1675
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001676bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001677 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001678 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1679 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001680
1681 // Visit the components of the offsetof expression.
1682 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1683 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1684 const OffsetOfNode &Node = E->getComponent(I);
1685 switch (Node.getKind()) {
1686 case OffsetOfNode::Array:
1687 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1688 StmtParent, TU)))
1689 return true;
1690 break;
1691
1692 case OffsetOfNode::Field:
1693 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1694 TU)))
1695 return true;
1696 break;
1697
1698 case OffsetOfNode::Identifier:
1699 case OffsetOfNode::Base:
1700 continue;
1701 }
1702 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001703
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001704 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001705}
1706
Douglas Gregor336fd812010-01-23 00:40:08 +00001707bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1708 if (E->isArgumentType()) {
1709 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1710 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001711
Douglas Gregor336fd812010-01-23 00:40:08 +00001712 return false;
1713 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001714
Douglas Gregor336fd812010-01-23 00:40:08 +00001715 return VisitExpr(E);
1716}
1717
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001718bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1719 // Visit the base expression.
1720 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1721 return true;
1722
1723 // Visit the nested-name-specifier
1724 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1725 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1726 return true;
1727
1728 // Visit the declaration name.
1729 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1730 return true;
1731
1732 // Visit the explicitly-specified template arguments, if any.
1733 if (E->hasExplicitTemplateArgs()) {
1734 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1735 *ArgEnd = Arg + E->getNumTemplateArgs();
1736 Arg != ArgEnd;
1737 ++Arg) {
1738 if (VisitTemplateArgumentLoc(*Arg))
1739 return true;
1740 }
1741 }
1742
1743 return false;
1744}
1745
Douglas Gregor336fd812010-01-23 00:40:08 +00001746bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1747 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1748 if (Visit(TSInfo->getTypeLoc()))
1749 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001750
Douglas Gregor336fd812010-01-23 00:40:08 +00001751 return VisitCastExpr(E);
1752}
1753
1754bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1755 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1756 if (Visit(TSInfo->getTypeLoc()))
1757 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001758
Douglas Gregor336fd812010-01-23 00:40:08 +00001759 return VisitExpr(E);
1760}
1761
Douglas Gregor36897b02010-09-10 00:22:18 +00001762bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1763 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1764}
1765
Douglas Gregor648220e2010-08-10 15:02:34 +00001766bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1767 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1768 Visit(E->getArgTInfo2()->getTypeLoc());
1769}
1770
1771bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1772 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1773 return true;
1774
1775 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1776}
1777
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001778bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1779 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001780 if (InitListExpr *Syntactic = E->getSyntacticForm())
1781 return VisitExpr(Syntactic);
1782
1783 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001784}
1785
1786bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1787 // Visit the designators.
1788 typedef DesignatedInitExpr::Designator Designator;
1789 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1790 DEnd = E->designators_end();
1791 D != DEnd; ++D) {
1792 if (D->isFieldDesignator()) {
1793 if (FieldDecl *Field = D->getField())
1794 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1795 return true;
1796
1797 continue;
1798 }
1799
1800 if (D->isArrayDesignator()) {
1801 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1802 return true;
1803
1804 continue;
1805 }
1806
1807 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1808 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1809 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1810 return true;
1811 }
1812
1813 // Visit the initializer value itself.
1814 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1815}
1816
Douglas Gregor94802292010-09-02 21:20:16 +00001817bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1818 if (E->isTypeOperand()) {
1819 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1820 return Visit(TSInfo->getTypeLoc());
1821
1822 return false;
1823 }
1824
1825 return VisitExpr(E);
1826}
1827
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001828bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1829 if (E->isTypeOperand()) {
1830 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1831 return Visit(TSInfo->getTypeLoc());
1832
1833 return false;
1834 }
1835
1836 return VisitExpr(E);
1837}
1838
Douglas Gregorab6677e2010-09-08 00:15:04 +00001839bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1840 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
Douglas Gregor40749ee2010-11-03 00:35:38 +00001841 if (Visit(TSInfo->getTypeLoc()))
1842 return true;
Douglas Gregorab6677e2010-09-08 00:15:04 +00001843
1844 return VisitExpr(E);
1845}
1846
1847bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1848 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1849 return Visit(TSInfo->getTypeLoc());
1850
1851 return false;
1852}
1853
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001854bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1855 // Visit placement arguments.
1856 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1857 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1858 return true;
1859
1860 // Visit the allocated type.
1861 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1862 if (Visit(TSInfo->getTypeLoc()))
1863 return true;
1864
1865 // Visit the array size, if any.
1866 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1867 return true;
1868
1869 // Visit the initializer or constructor arguments.
1870 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1871 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1872 return true;
1873
1874 return false;
1875}
1876
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001877bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1878 // Visit base expression.
1879 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1880 return true;
1881
1882 // Visit the nested-name-specifier.
1883 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1884 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1885 return true;
1886
1887 // Visit the scope type that looks disturbingly like the nested-name-specifier
1888 // but isn't.
1889 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1890 if (Visit(TSInfo->getTypeLoc()))
1891 return true;
1892
1893 // Visit the name of the type being destroyed.
1894 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1895 if (Visit(TSInfo->getTypeLoc()))
1896 return true;
1897
1898 return false;
1899}
1900
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001901bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1902 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1903}
1904
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001905bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001906 // Visit the nested-name-specifier.
1907 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1908 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1909 return true;
1910
1911 // Visit the declaration name.
1912 if (VisitDeclarationNameInfo(E->getNameInfo()))
1913 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001914
1915 // Visit the overloaded declaration reference.
1916 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1917 return true;
1918
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001919 // Visit the explicitly-specified template arguments.
1920 if (const ExplicitTemplateArgumentList *ArgList
1921 = E->getOptionalExplicitTemplateArgs()) {
1922 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1923 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1924 Arg != ArgEnd; ++Arg) {
1925 if (VisitTemplateArgumentLoc(*Arg))
1926 return true;
1927 }
1928 }
1929
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001930 return false;
1931}
1932
Douglas Gregorbfebed22010-09-03 17:24:10 +00001933bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1934 DependentScopeDeclRefExpr *E) {
1935 // Visit the nested-name-specifier.
1936 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1937 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1938 return true;
1939
1940 // Visit the declaration name.
1941 if (VisitDeclarationNameInfo(E->getNameInfo()))
1942 return true;
1943
1944 // Visit the explicitly-specified template arguments.
1945 if (const ExplicitTemplateArgumentList *ArgList
1946 = E->getOptionalExplicitTemplateArgs()) {
1947 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1948 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1949 Arg != ArgEnd; ++Arg) {
1950 if (VisitTemplateArgumentLoc(*Arg))
1951 return true;
1952 }
1953 }
1954
1955 return false;
1956}
1957
Douglas Gregorab6677e2010-09-08 00:15:04 +00001958bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1959 CXXUnresolvedConstructExpr *E) {
1960 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1961 if (Visit(TSInfo->getTypeLoc()))
1962 return true;
1963
1964 return VisitExpr(E);
1965}
1966
Douglas Gregor25d63622010-09-03 17:35:34 +00001967bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1968 CXXDependentScopeMemberExpr *E) {
1969 // Visit the base expression, if there is one.
1970 if (!E->isImplicitAccess() &&
1971 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1972 return true;
1973
1974 // Visit the nested-name-specifier.
1975 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1976 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1977 return true;
1978
1979 // Visit the declaration name.
1980 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1981 return true;
1982
1983 // Visit the explicitly-specified template arguments.
1984 if (const ExplicitTemplateArgumentList *ArgList
1985 = E->getOptionalExplicitTemplateArgs()) {
1986 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1987 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1988 Arg != ArgEnd; ++Arg) {
1989 if (VisitTemplateArgumentLoc(*Arg))
1990 return true;
1991 }
1992 }
1993
1994 return false;
1995}
1996
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001997bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1998 // Visit the base expression, if there is one.
1999 if (!E->isImplicitAccess() &&
2000 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
2001 return true;
2002
2003 return VisitOverloadExpr(E);
2004}
Douglas Gregor25d63622010-09-03 17:35:34 +00002005
Douglas Gregorc2350e52010-03-08 16:40:19 +00002006bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002007 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
2008 if (Visit(TSInfo->getTypeLoc()))
2009 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00002010
2011 return VisitExpr(E);
2012}
2013
Douglas Gregor81d34662010-04-20 15:39:42 +00002014bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2015 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
2016}
2017
2018
Ted Kremenek09dfa372010-02-18 05:46:33 +00002019bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00002020 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
2021 i != e; ++i)
2022 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00002023 return true;
2024
2025 return false;
2026}
2027
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002028static llvm::sys::Mutex EnableMultithreadingMutex;
2029static bool EnabledMultithreading;
2030
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002031extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002032CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2033 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002034 // Disable pretty stack trace functionality, which will otherwise be a very
2035 // poor citizen of the world and set up all sorts of signal handlers.
2036 llvm::DisablePrettyStackTrace = true;
2037
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002038 // We use crash recovery to make some of our APIs more reliable, implicitly
2039 // enable it.
2040 llvm::CrashRecoveryContext::Enable();
2041
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002042 // Enable support for multithreading in LLVM.
2043 {
2044 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2045 if (!EnabledMultithreading) {
2046 llvm::llvm_start_multithreaded();
2047 EnabledMultithreading = true;
2048 }
2049 }
2050
Douglas Gregora030b7c2010-01-22 20:35:53 +00002051 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002052 if (excludeDeclarationsFromPCH)
2053 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002054 if (displayDiagnostics)
2055 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002056 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002057}
2058
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002059void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002060 if (CIdx)
2061 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002062}
2063
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002064CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002065 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002066 if (!CIdx)
2067 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002068
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002069 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002070 FileSystemOptions FileSystemOpts;
2071 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002072
Douglas Gregor28019772010-04-05 23:52:57 +00002073 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002074 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002075 CXXIdx->getOnlyLocalDecls(),
2076 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002077}
2078
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002079unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002080 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002081 CXTranslationUnit_CacheCompletionResults |
2082 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002083}
2084
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002085CXTranslationUnit
2086clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2087 const char *source_filename,
2088 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002089 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002090 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002091 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002092 return clang_parseTranslationUnit(CIdx, source_filename,
2093 command_line_args, num_command_line_args,
2094 unsaved_files, num_unsaved_files,
2095 CXTranslationUnit_DetailedPreprocessingRecord);
2096}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002097
2098struct ParseTranslationUnitInfo {
2099 CXIndex CIdx;
2100 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002101 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002102 int num_command_line_args;
2103 struct CXUnsavedFile *unsaved_files;
2104 unsigned num_unsaved_files;
2105 unsigned options;
2106 CXTranslationUnit result;
2107};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002108static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002109 ParseTranslationUnitInfo *PTUI =
2110 static_cast<ParseTranslationUnitInfo*>(UserData);
2111 CXIndex CIdx = PTUI->CIdx;
2112 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002113 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002114 int num_command_line_args = PTUI->num_command_line_args;
2115 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2116 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2117 unsigned options = PTUI->options;
2118 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002119
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002120 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002121 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002122
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002123 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2124
Douglas Gregor44c181a2010-07-23 00:33:23 +00002125 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002126 bool CompleteTranslationUnit
2127 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002128 bool CacheCodeCompetionResults
2129 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002130 bool CXXPrecompilePreamble
2131 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2132 bool CXXChainedPCH
2133 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002134
Douglas Gregor5352ac02010-01-28 00:27:43 +00002135 // Configure the diagnostics.
2136 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002137 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2138 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002139
Douglas Gregor4db64a42010-01-23 00:14:00 +00002140 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2141 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002142 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002143 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002144 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002145 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2146 Buffer));
2147 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002148
Douglas Gregorb10daed2010-10-11 16:52:23 +00002149 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002150
Ted Kremenek139ba862009-10-22 00:03:57 +00002151 // The 'source_filename' argument is optional. If the caller does not
2152 // specify it then it is assumed that the source file is specified
2153 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002154 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002155 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002156
2157 // Since the Clang C library is primarily used by batch tools dealing with
2158 // (often very broken) source code, where spell-checking can have a
2159 // significant negative impact on performance (particularly when
2160 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002161 // Only do this if we haven't found a spell-checking-related argument.
2162 bool FoundSpellCheckingArgument = false;
2163 for (int I = 0; I != num_command_line_args; ++I) {
2164 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2165 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2166 FoundSpellCheckingArgument = true;
2167 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002168 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002169 }
2170 if (!FoundSpellCheckingArgument)
2171 Args.push_back("-fno-spell-checking");
2172
2173 Args.insert(Args.end(), command_line_args,
2174 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002175
Douglas Gregor44c181a2010-07-23 00:33:23 +00002176 // Do we need the detailed preprocessing record?
2177 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002178 Args.push_back("-Xclang");
2179 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002180 }
2181
Douglas Gregorb10daed2010-10-11 16:52:23 +00002182 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002183 llvm::OwningPtr<ASTUnit> Unit(
2184 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2185 Diags,
2186 CXXIdx->getClangResourcesPath(),
2187 CXXIdx->getOnlyLocalDecls(),
2188 RemappedFiles.data(),
2189 RemappedFiles.size(),
2190 /*CaptureDiagnostics=*/true,
2191 PrecompilePreamble,
2192 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002193 CacheCodeCompetionResults,
2194 CXXPrecompilePreamble,
2195 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002196
Douglas Gregorb10daed2010-10-11 16:52:23 +00002197 if (NumErrors != Diags->getNumErrors()) {
2198 // Make sure to check that 'Unit' is non-NULL.
2199 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2200 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2201 DEnd = Unit->stored_diag_end();
2202 D != DEnd; ++D) {
2203 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2204 CXString Msg = clang_formatDiagnostic(&Diag,
2205 clang_defaultDiagnosticDisplayOptions());
2206 fprintf(stderr, "%s\n", clang_getCString(Msg));
2207 clang_disposeString(Msg);
2208 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002209#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002210 // On Windows, force a flush, since there may be multiple copies of
2211 // stderr and stdout in the file system, all with different buffers
2212 // but writing to the same device.
2213 fflush(stderr);
2214#endif
2215 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002216 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002217
Douglas Gregorb10daed2010-10-11 16:52:23 +00002218 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002219}
2220CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2221 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002222 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002223 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002224 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002225 unsigned num_unsaved_files,
2226 unsigned options) {
2227 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002228 num_command_line_args, unsaved_files,
2229 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002230 llvm::CrashRecoveryContext CRC;
2231
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002232 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002233 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2234 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2235 fprintf(stderr, " 'command_line_args' : [");
2236 for (int i = 0; i != num_command_line_args; ++i) {
2237 if (i)
2238 fprintf(stderr, ", ");
2239 fprintf(stderr, "'%s'", command_line_args[i]);
2240 }
2241 fprintf(stderr, "],\n");
2242 fprintf(stderr, " 'unsaved_files' : [");
2243 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2244 if (i)
2245 fprintf(stderr, ", ");
2246 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2247 unsaved_files[i].Length);
2248 }
2249 fprintf(stderr, "],\n");
2250 fprintf(stderr, " 'options' : %d,\n", options);
2251 fprintf(stderr, "}\n");
2252
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002253 return 0;
2254 }
2255
2256 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002257}
2258
Douglas Gregor19998442010-08-13 15:35:05 +00002259unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2260 return CXSaveTranslationUnit_None;
2261}
2262
2263int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2264 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002265 if (!TU)
2266 return 1;
2267
2268 return static_cast<ASTUnit *>(TU)->Save(FileName);
2269}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002270
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002271void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002272 if (CTUnit) {
2273 // If the translation unit has been marked as unsafe to free, just discard
2274 // it.
2275 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2276 return;
2277
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002278 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002279 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002280}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002281
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002282unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2283 return CXReparse_None;
2284}
2285
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002286struct ReparseTranslationUnitInfo {
2287 CXTranslationUnit TU;
2288 unsigned num_unsaved_files;
2289 struct CXUnsavedFile *unsaved_files;
2290 unsigned options;
2291 int result;
2292};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002293
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002294static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002295 ReparseTranslationUnitInfo *RTUI =
2296 static_cast<ReparseTranslationUnitInfo*>(UserData);
2297 CXTranslationUnit TU = RTUI->TU;
2298 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2299 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2300 unsigned options = RTUI->options;
2301 (void) options;
2302 RTUI->result = 1;
2303
Douglas Gregorabc563f2010-07-19 21:46:24 +00002304 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002305 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002306
2307 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2308 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002309
2310 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2311 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2312 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2313 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002314 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002315 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2316 Buffer));
2317 }
2318
Douglas Gregor593b0c12010-09-23 18:47:53 +00002319 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2320 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002321}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002322
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002323int clang_reparseTranslationUnit(CXTranslationUnit TU,
2324 unsigned num_unsaved_files,
2325 struct CXUnsavedFile *unsaved_files,
2326 unsigned options) {
2327 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2328 options, 0 };
2329 llvm::CrashRecoveryContext CRC;
2330
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002331 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002332 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002333 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2334 return 1;
2335 }
2336
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002337
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002338 return RTUI.result;
2339}
2340
Douglas Gregordf95a132010-08-09 20:45:32 +00002341
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002342CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002343 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002344 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002345
Steve Naroff77accc12009-09-03 18:19:54 +00002346 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002347 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002348}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002349
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002350CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002351 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002352 return Result;
2353}
2354
Ted Kremenekfb480492010-01-13 21:46:36 +00002355} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002356
Ted Kremenekfb480492010-01-13 21:46:36 +00002357//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002358// CXSourceLocation and CXSourceRange Operations.
2359//===----------------------------------------------------------------------===//
2360
Douglas Gregorb9790342010-01-22 21:44:22 +00002361extern "C" {
2362CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002363 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002364 return Result;
2365}
2366
2367unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002368 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2369 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2370 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002371}
2372
2373CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2374 CXFile file,
2375 unsigned line,
2376 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002377 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002378 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002379
Douglas Gregorb9790342010-01-22 21:44:22 +00002380 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2381 SourceLocation SLoc
2382 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002383 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002384 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002385 if (SLoc.isInvalid()) return clang_getNullLocation();
2386
2387 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2388}
2389
2390CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2391 CXFile file,
2392 unsigned offset) {
2393 if (!tu || !file)
2394 return clang_getNullLocation();
2395
2396 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2397 SourceLocation Start
2398 = CXXUnit->getSourceManager().getLocation(
2399 static_cast<const FileEntry *>(file),
2400 1, 1);
2401 if (Start.isInvalid()) return clang_getNullLocation();
2402
2403 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2404
2405 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002406
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002407 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002408}
2409
Douglas Gregor5352ac02010-01-28 00:27:43 +00002410CXSourceRange clang_getNullRange() {
2411 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2412 return Result;
2413}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002414
Douglas Gregor5352ac02010-01-28 00:27:43 +00002415CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2416 if (begin.ptr_data[0] != end.ptr_data[0] ||
2417 begin.ptr_data[1] != end.ptr_data[1])
2418 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002419
2420 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002421 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002422 return Result;
2423}
2424
Douglas Gregor46766dc2010-01-26 19:19:08 +00002425void clang_getInstantiationLocation(CXSourceLocation location,
2426 CXFile *file,
2427 unsigned *line,
2428 unsigned *column,
2429 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002430 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2431
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002432 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002433 if (file)
2434 *file = 0;
2435 if (line)
2436 *line = 0;
2437 if (column)
2438 *column = 0;
2439 if (offset)
2440 *offset = 0;
2441 return;
2442 }
2443
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002444 const SourceManager &SM =
2445 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002446 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002447
2448 if (file)
2449 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2450 if (line)
2451 *line = SM.getInstantiationLineNumber(InstLoc);
2452 if (column)
2453 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002454 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002455 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002456}
2457
Douglas Gregor1db19de2010-01-19 21:36:55 +00002458CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002459 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002460 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002461 return Result;
2462}
2463
2464CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002465 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002466 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002467 return Result;
2468}
2469
Douglas Gregorb9790342010-01-22 21:44:22 +00002470} // end: extern "C"
2471
Douglas Gregor1db19de2010-01-19 21:36:55 +00002472//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002473// CXFile Operations.
2474//===----------------------------------------------------------------------===//
2475
2476extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002477CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002478 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002479 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002480
Steve Naroff88145032009-10-27 14:35:18 +00002481 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002482 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002483}
2484
2485time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002486 if (!SFile)
2487 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002488
Steve Naroff88145032009-10-27 14:35:18 +00002489 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2490 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002491}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002492
Douglas Gregorb9790342010-01-22 21:44:22 +00002493CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2494 if (!tu)
2495 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002496
Douglas Gregorb9790342010-01-22 21:44:22 +00002497 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002498
Douglas Gregorb9790342010-01-22 21:44:22 +00002499 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002500 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2501 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002502 return const_cast<FileEntry *>(File);
2503}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002504
Ted Kremenekfb480492010-01-13 21:46:36 +00002505} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002506
Ted Kremenekfb480492010-01-13 21:46:36 +00002507//===----------------------------------------------------------------------===//
2508// CXCursor Operations.
2509//===----------------------------------------------------------------------===//
2510
Ted Kremenekfb480492010-01-13 21:46:36 +00002511static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002512 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2513 return getDeclFromExpr(CE->getSubExpr());
2514
Ted Kremenekfb480492010-01-13 21:46:36 +00002515 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2516 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002517 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2518 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002519 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2520 return ME->getMemberDecl();
2521 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2522 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002523 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2524 return PRE->getProperty();
2525
Ted Kremenekfb480492010-01-13 21:46:36 +00002526 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2527 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002528 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2529 if (!CE->isElidable())
2530 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002531 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2532 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002533
Douglas Gregordb1314e2010-10-01 21:11:22 +00002534 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2535 return PE->getProtocol();
2536
Ted Kremenekfb480492010-01-13 21:46:36 +00002537 return 0;
2538}
2539
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002540static SourceLocation getLocationFromExpr(Expr *E) {
2541 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2542 return /*FIXME:*/Msg->getLeftLoc();
2543 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2544 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002545 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2546 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002547 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2548 return Member->getMemberLoc();
2549 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2550 return Ivar->getLocation();
2551 return E->getLocStart();
2552}
2553
Ted Kremenekfb480492010-01-13 21:46:36 +00002554extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002555
2556unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002557 CXCursorVisitor visitor,
2558 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002559 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002560
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002561 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2562 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002563 return CursorVis.VisitChildren(parent);
2564}
2565
David Chisnall3387c652010-11-03 14:12:26 +00002566#ifndef __has_feature
2567#define __has_feature(x) 0
2568#endif
2569#if __has_feature(blocks)
2570typedef enum CXChildVisitResult
2571 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2572
2573static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2574 CXClientData client_data) {
2575 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2576 return block(cursor, parent);
2577}
2578#else
2579// If we are compiled with a compiler that doesn't have native blocks support,
2580// define and call the block manually, so the
2581typedef struct _CXChildVisitResult
2582{
2583 void *isa;
2584 int flags;
2585 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002586 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2587 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002588} *CXCursorVisitorBlock;
2589
2590static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2591 CXClientData client_data) {
2592 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2593 return block->invoke(block, cursor, parent);
2594}
2595#endif
2596
2597
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002598unsigned clang_visitChildrenWithBlock(CXCursor parent,
2599 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002600 return clang_visitChildren(parent, visitWithBlock, block);
2601}
2602
Douglas Gregor78205d42010-01-20 21:45:58 +00002603static CXString getDeclSpelling(Decl *D) {
2604 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2605 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002606 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002607
Douglas Gregor78205d42010-01-20 21:45:58 +00002608 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002609 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002610
Douglas Gregor78205d42010-01-20 21:45:58 +00002611 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2612 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2613 // and returns different names. NamedDecl returns the class name and
2614 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002615 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002616
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002617 if (isa<UsingDirectiveDecl>(D))
2618 return createCXString("");
2619
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002620 llvm::SmallString<1024> S;
2621 llvm::raw_svector_ostream os(S);
2622 ND->printName(os);
2623
2624 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002625}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002626
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002627CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002628 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002629 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002630
Steve Narofff334b4e2009-09-02 18:26:48 +00002631 if (clang_isReference(C.kind)) {
2632 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002633 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002634 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002635 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002636 }
2637 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002638 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002639 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002640 }
2641 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002642 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002643 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002644 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002645 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002646 case CXCursor_CXXBaseSpecifier: {
2647 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2648 return createCXString(B->getType().getAsString());
2649 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002650 case CXCursor_TypeRef: {
2651 TypeDecl *Type = getCursorTypeRef(C).first;
2652 assert(Type && "Missing type decl");
2653
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002654 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2655 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002656 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002657 case CXCursor_TemplateRef: {
2658 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002659 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002660
2661 return createCXString(Template->getNameAsString());
2662 }
Douglas Gregor69319002010-08-31 23:48:11 +00002663
2664 case CXCursor_NamespaceRef: {
2665 NamedDecl *NS = getCursorNamespaceRef(C).first;
2666 assert(NS && "Missing namespace decl");
2667
2668 return createCXString(NS->getNameAsString());
2669 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002670
Douglas Gregora67e03f2010-09-09 21:42:20 +00002671 case CXCursor_MemberRef: {
2672 FieldDecl *Field = getCursorMemberRef(C).first;
2673 assert(Field && "Missing member decl");
2674
2675 return createCXString(Field->getNameAsString());
2676 }
2677
Douglas Gregor36897b02010-09-10 00:22:18 +00002678 case CXCursor_LabelRef: {
2679 LabelStmt *Label = getCursorLabelRef(C).first;
2680 assert(Label && "Missing label");
2681
2682 return createCXString(Label->getID()->getName());
2683 }
2684
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002685 case CXCursor_OverloadedDeclRef: {
2686 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2687 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2688 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2689 return createCXString(ND->getNameAsString());
2690 return createCXString("");
2691 }
2692 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2693 return createCXString(E->getName().getAsString());
2694 OverloadedTemplateStorage *Ovl
2695 = Storage.get<OverloadedTemplateStorage*>();
2696 if (Ovl->size() == 0)
2697 return createCXString("");
2698 return createCXString((*Ovl->begin())->getNameAsString());
2699 }
2700
Daniel Dunbaracca7252009-11-30 20:42:49 +00002701 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002702 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002703 }
2704 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002705
2706 if (clang_isExpression(C.kind)) {
2707 Decl *D = getDeclFromExpr(getCursorExpr(C));
2708 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002709 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002710 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002711 }
2712
Douglas Gregor36897b02010-09-10 00:22:18 +00002713 if (clang_isStatement(C.kind)) {
2714 Stmt *S = getCursorStmt(C);
2715 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2716 return createCXString(Label->getID()->getName());
2717
2718 return createCXString("");
2719 }
2720
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002721 if (C.kind == CXCursor_MacroInstantiation)
2722 return createCXString(getCursorMacroInstantiation(C)->getName()
2723 ->getNameStart());
2724
Douglas Gregor572feb22010-03-18 18:04:21 +00002725 if (C.kind == CXCursor_MacroDefinition)
2726 return createCXString(getCursorMacroDefinition(C)->getName()
2727 ->getNameStart());
2728
Douglas Gregorecdcb882010-10-20 22:00:55 +00002729 if (C.kind == CXCursor_InclusionDirective)
2730 return createCXString(getCursorInclusionDirective(C)->getFileName());
2731
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002732 if (clang_isDeclaration(C.kind))
2733 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002734
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002735 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002736}
2737
Douglas Gregor358559d2010-10-02 22:49:11 +00002738CXString clang_getCursorDisplayName(CXCursor C) {
2739 if (!clang_isDeclaration(C.kind))
2740 return clang_getCursorSpelling(C);
2741
2742 Decl *D = getCursorDecl(C);
2743 if (!D)
2744 return createCXString("");
2745
2746 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2747 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2748 D = FunTmpl->getTemplatedDecl();
2749
2750 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2751 llvm::SmallString<64> Str;
2752 llvm::raw_svector_ostream OS(Str);
2753 OS << Function->getNameAsString();
2754 if (Function->getPrimaryTemplate())
2755 OS << "<>";
2756 OS << "(";
2757 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2758 if (I)
2759 OS << ", ";
2760 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2761 }
2762
2763 if (Function->isVariadic()) {
2764 if (Function->getNumParams())
2765 OS << ", ";
2766 OS << "...";
2767 }
2768 OS << ")";
2769 return createCXString(OS.str());
2770 }
2771
2772 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2773 llvm::SmallString<64> Str;
2774 llvm::raw_svector_ostream OS(Str);
2775 OS << ClassTemplate->getNameAsString();
2776 OS << "<";
2777 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2778 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2779 if (I)
2780 OS << ", ";
2781
2782 NamedDecl *Param = Params->getParam(I);
2783 if (Param->getIdentifier()) {
2784 OS << Param->getIdentifier()->getName();
2785 continue;
2786 }
2787
2788 // There is no parameter name, which makes this tricky. Try to come up
2789 // with something useful that isn't too long.
2790 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2791 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2792 else if (NonTypeTemplateParmDecl *NTTP
2793 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2794 OS << NTTP->getType().getAsString(Policy);
2795 else
2796 OS << "template<...> class";
2797 }
2798
2799 OS << ">";
2800 return createCXString(OS.str());
2801 }
2802
2803 if (ClassTemplateSpecializationDecl *ClassSpec
2804 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2805 // If the type was explicitly written, use that.
2806 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2807 return createCXString(TSInfo->getType().getAsString(Policy));
2808
2809 llvm::SmallString<64> Str;
2810 llvm::raw_svector_ostream OS(Str);
2811 OS << ClassSpec->getNameAsString();
2812 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002813 ClassSpec->getTemplateArgs().data(),
2814 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002815 Policy);
2816 return createCXString(OS.str());
2817 }
2818
2819 return clang_getCursorSpelling(C);
2820}
2821
Ted Kremeneke68fff62010-02-17 00:41:32 +00002822CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002823 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002824 case CXCursor_FunctionDecl:
2825 return createCXString("FunctionDecl");
2826 case CXCursor_TypedefDecl:
2827 return createCXString("TypedefDecl");
2828 case CXCursor_EnumDecl:
2829 return createCXString("EnumDecl");
2830 case CXCursor_EnumConstantDecl:
2831 return createCXString("EnumConstantDecl");
2832 case CXCursor_StructDecl:
2833 return createCXString("StructDecl");
2834 case CXCursor_UnionDecl:
2835 return createCXString("UnionDecl");
2836 case CXCursor_ClassDecl:
2837 return createCXString("ClassDecl");
2838 case CXCursor_FieldDecl:
2839 return createCXString("FieldDecl");
2840 case CXCursor_VarDecl:
2841 return createCXString("VarDecl");
2842 case CXCursor_ParmDecl:
2843 return createCXString("ParmDecl");
2844 case CXCursor_ObjCInterfaceDecl:
2845 return createCXString("ObjCInterfaceDecl");
2846 case CXCursor_ObjCCategoryDecl:
2847 return createCXString("ObjCCategoryDecl");
2848 case CXCursor_ObjCProtocolDecl:
2849 return createCXString("ObjCProtocolDecl");
2850 case CXCursor_ObjCPropertyDecl:
2851 return createCXString("ObjCPropertyDecl");
2852 case CXCursor_ObjCIvarDecl:
2853 return createCXString("ObjCIvarDecl");
2854 case CXCursor_ObjCInstanceMethodDecl:
2855 return createCXString("ObjCInstanceMethodDecl");
2856 case CXCursor_ObjCClassMethodDecl:
2857 return createCXString("ObjCClassMethodDecl");
2858 case CXCursor_ObjCImplementationDecl:
2859 return createCXString("ObjCImplementationDecl");
2860 case CXCursor_ObjCCategoryImplDecl:
2861 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002862 case CXCursor_CXXMethod:
2863 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002864 case CXCursor_UnexposedDecl:
2865 return createCXString("UnexposedDecl");
2866 case CXCursor_ObjCSuperClassRef:
2867 return createCXString("ObjCSuperClassRef");
2868 case CXCursor_ObjCProtocolRef:
2869 return createCXString("ObjCProtocolRef");
2870 case CXCursor_ObjCClassRef:
2871 return createCXString("ObjCClassRef");
2872 case CXCursor_TypeRef:
2873 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002874 case CXCursor_TemplateRef:
2875 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002876 case CXCursor_NamespaceRef:
2877 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002878 case CXCursor_MemberRef:
2879 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002880 case CXCursor_LabelRef:
2881 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002882 case CXCursor_OverloadedDeclRef:
2883 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002884 case CXCursor_UnexposedExpr:
2885 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002886 case CXCursor_BlockExpr:
2887 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002888 case CXCursor_DeclRefExpr:
2889 return createCXString("DeclRefExpr");
2890 case CXCursor_MemberRefExpr:
2891 return createCXString("MemberRefExpr");
2892 case CXCursor_CallExpr:
2893 return createCXString("CallExpr");
2894 case CXCursor_ObjCMessageExpr:
2895 return createCXString("ObjCMessageExpr");
2896 case CXCursor_UnexposedStmt:
2897 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002898 case CXCursor_LabelStmt:
2899 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002900 case CXCursor_InvalidFile:
2901 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002902 case CXCursor_InvalidCode:
2903 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002904 case CXCursor_NoDeclFound:
2905 return createCXString("NoDeclFound");
2906 case CXCursor_NotImplemented:
2907 return createCXString("NotImplemented");
2908 case CXCursor_TranslationUnit:
2909 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002910 case CXCursor_UnexposedAttr:
2911 return createCXString("UnexposedAttr");
2912 case CXCursor_IBActionAttr:
2913 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002914 case CXCursor_IBOutletAttr:
2915 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002916 case CXCursor_IBOutletCollectionAttr:
2917 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002918 case CXCursor_PreprocessingDirective:
2919 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002920 case CXCursor_MacroDefinition:
2921 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002922 case CXCursor_MacroInstantiation:
2923 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002924 case CXCursor_InclusionDirective:
2925 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002926 case CXCursor_Namespace:
2927 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002928 case CXCursor_LinkageSpec:
2929 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002930 case CXCursor_CXXBaseSpecifier:
2931 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002932 case CXCursor_Constructor:
2933 return createCXString("CXXConstructor");
2934 case CXCursor_Destructor:
2935 return createCXString("CXXDestructor");
2936 case CXCursor_ConversionFunction:
2937 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002938 case CXCursor_TemplateTypeParameter:
2939 return createCXString("TemplateTypeParameter");
2940 case CXCursor_NonTypeTemplateParameter:
2941 return createCXString("NonTypeTemplateParameter");
2942 case CXCursor_TemplateTemplateParameter:
2943 return createCXString("TemplateTemplateParameter");
2944 case CXCursor_FunctionTemplate:
2945 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002946 case CXCursor_ClassTemplate:
2947 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002948 case CXCursor_ClassTemplatePartialSpecialization:
2949 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002950 case CXCursor_NamespaceAlias:
2951 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002952 case CXCursor_UsingDirective:
2953 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00002954 case CXCursor_UsingDeclaration:
2955 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00002956 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00002957
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00002958 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002959 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00002960}
Steve Naroff89922f82009-08-31 00:59:03 +00002961
Ted Kremeneke68fff62010-02-17 00:41:32 +00002962enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
2963 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002964 CXClientData client_data) {
2965 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00002966
2967 // If our current best cursor is the construction of a temporary object,
2968 // don't replace that cursor with a type reference, because we want
2969 // clang_getCursor() to point at the constructor.
2970 if (clang_isExpression(BestCursor->kind) &&
2971 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
2972 cursor.kind == CXCursor_TypeRef)
2973 return CXChildVisit_Recurse;
2974
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002975 *BestCursor = cursor;
2976 return CXChildVisit_Recurse;
2977}
Ted Kremeneke68fff62010-02-17 00:41:32 +00002978
Douglas Gregorb9790342010-01-22 21:44:22 +00002979CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
2980 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00002981 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00002982
Douglas Gregorb9790342010-01-22 21:44:22 +00002983 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00002984 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
2985
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002986 // Translate the given source location to make it point at the beginning of
2987 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00002988 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00002989
2990 // Guard against an invalid SourceLocation, or we may assert in one
2991 // of the following calls.
2992 if (SLoc.isInvalid())
2993 return clang_getNullCursor();
2994
Douglas Gregor40749ee2010-11-03 00:35:38 +00002995 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00002996 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
2997 CXXUnit->getASTContext().getLangOptions());
2998
Douglas Gregor33e9abd2010-01-22 19:49:59 +00002999 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3000 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003001 // FIXME: Would be great to have a "hint" cursor, then walk from that
3002 // hint cursor upward until we find a cursor whose source range encloses
3003 // the region of interest, rather than starting from the translation unit.
3004 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003005 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003006 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003007 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003008 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003009
3010 if (Logging) {
3011 CXFile SearchFile;
3012 unsigned SearchLine, SearchColumn;
3013 CXFile ResultFile;
3014 unsigned ResultLine, ResultColumn;
3015 CXString SearchFileName, ResultFileName, KindSpelling;
3016 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3017
3018 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3019 0);
3020 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3021 &ResultColumn, 0);
3022 SearchFileName = clang_getFileName(SearchFile);
3023 ResultFileName = clang_getFileName(ResultFile);
3024 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3025 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3026 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3027 clang_getCString(KindSpelling),
3028 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3029 clang_disposeString(SearchFileName);
3030 clang_disposeString(ResultFileName);
3031 clang_disposeString(KindSpelling);
3032 }
3033
Ted Kremeneke68fff62010-02-17 00:41:32 +00003034 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003035}
3036
Ted Kremenek73885552009-11-17 19:28:59 +00003037CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003038 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003039}
3040
3041unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003042 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003043}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003044
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003045unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003046 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3047}
3048
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003049unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003050 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3051}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003052
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003053unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003054 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3055}
3056
Douglas Gregor97b98722010-01-19 23:20:36 +00003057unsigned clang_isExpression(enum CXCursorKind K) {
3058 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3059}
3060
3061unsigned clang_isStatement(enum CXCursorKind K) {
3062 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3063}
3064
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003065unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3066 return K == CXCursor_TranslationUnit;
3067}
3068
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003069unsigned clang_isPreprocessing(enum CXCursorKind K) {
3070 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3071}
3072
Ted Kremenekad6eff62010-03-08 21:17:29 +00003073unsigned clang_isUnexposed(enum CXCursorKind K) {
3074 switch (K) {
3075 case CXCursor_UnexposedDecl:
3076 case CXCursor_UnexposedExpr:
3077 case CXCursor_UnexposedStmt:
3078 case CXCursor_UnexposedAttr:
3079 return true;
3080 default:
3081 return false;
3082 }
3083}
3084
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003085CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003086 return C.kind;
3087}
3088
Douglas Gregor98258af2010-01-18 22:46:11 +00003089CXSourceLocation clang_getCursorLocation(CXCursor C) {
3090 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003091 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003092 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003093 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3094 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003095 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003096 }
3097
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003098 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003099 std::pair<ObjCProtocolDecl *, SourceLocation> P
3100 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003101 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003102 }
3103
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003104 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003105 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3106 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003107 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003108 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003109
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003110 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003111 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003112 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003113 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003114
3115 case CXCursor_TemplateRef: {
3116 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3117 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3118 }
3119
Douglas Gregor69319002010-08-31 23:48:11 +00003120 case CXCursor_NamespaceRef: {
3121 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3122 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3123 }
3124
Douglas Gregora67e03f2010-09-09 21:42:20 +00003125 case CXCursor_MemberRef: {
3126 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3127 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3128 }
3129
Ted Kremenek3064ef92010-08-27 21:34:58 +00003130 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003131 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3132 if (!BaseSpec)
3133 return clang_getNullLocation();
3134
3135 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3136 return cxloc::translateSourceLocation(getCursorContext(C),
3137 TSInfo->getTypeLoc().getBeginLoc());
3138
3139 return cxloc::translateSourceLocation(getCursorContext(C),
3140 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003141 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003142
Douglas Gregor36897b02010-09-10 00:22:18 +00003143 case CXCursor_LabelRef: {
3144 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3145 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3146 }
3147
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003148 case CXCursor_OverloadedDeclRef:
3149 return cxloc::translateSourceLocation(getCursorContext(C),
3150 getCursorOverloadedDeclRef(C).second);
3151
Douglas Gregorf46034a2010-01-18 23:41:10 +00003152 default:
3153 // FIXME: Need a way to enumerate all non-reference cases.
3154 llvm_unreachable("Missed a reference kind");
3155 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003156 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003157
3158 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003159 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003160 getLocationFromExpr(getCursorExpr(C)));
3161
Douglas Gregor36897b02010-09-10 00:22:18 +00003162 if (clang_isStatement(C.kind))
3163 return cxloc::translateSourceLocation(getCursorContext(C),
3164 getCursorStmt(C)->getLocStart());
3165
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003166 if (C.kind == CXCursor_PreprocessingDirective) {
3167 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3168 return cxloc::translateSourceLocation(getCursorContext(C), L);
3169 }
Douglas Gregor48072312010-03-18 15:23:44 +00003170
3171 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003172 SourceLocation L
3173 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003174 return cxloc::translateSourceLocation(getCursorContext(C), L);
3175 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003176
3177 if (C.kind == CXCursor_MacroDefinition) {
3178 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3179 return cxloc::translateSourceLocation(getCursorContext(C), L);
3180 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003181
3182 if (C.kind == CXCursor_InclusionDirective) {
3183 SourceLocation L
3184 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3185 return cxloc::translateSourceLocation(getCursorContext(C), L);
3186 }
3187
Ted Kremenek9a700d22010-05-12 06:16:13 +00003188 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003189 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003190
Douglas Gregorf46034a2010-01-18 23:41:10 +00003191 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003192 SourceLocation Loc = D->getLocation();
3193 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3194 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003195 // FIXME: Multiple variables declared in a single declaration
3196 // currently lack the information needed to correctly determine their
3197 // ranges when accounting for the type-specifier. We use context
3198 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3199 // and if so, whether it is the first decl.
3200 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3201 if (!cxcursor::isFirstInDeclGroup(C))
3202 Loc = VD->getLocation();
3203 }
3204
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003205 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003206}
Douglas Gregora7bde202010-01-19 00:34:46 +00003207
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003208} // end extern "C"
3209
3210static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003211 if (clang_isReference(C.kind)) {
3212 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003213 case CXCursor_ObjCSuperClassRef:
3214 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003215
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003216 case CXCursor_ObjCProtocolRef:
3217 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003218
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003219 case CXCursor_ObjCClassRef:
3220 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003221
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003222 case CXCursor_TypeRef:
3223 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003224
3225 case CXCursor_TemplateRef:
3226 return getCursorTemplateRef(C).second;
3227
Douglas Gregor69319002010-08-31 23:48:11 +00003228 case CXCursor_NamespaceRef:
3229 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003230
3231 case CXCursor_MemberRef:
3232 return getCursorMemberRef(C).second;
3233
Ted Kremenek3064ef92010-08-27 21:34:58 +00003234 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003235 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003236
Douglas Gregor36897b02010-09-10 00:22:18 +00003237 case CXCursor_LabelRef:
3238 return getCursorLabelRef(C).second;
3239
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003240 case CXCursor_OverloadedDeclRef:
3241 return getCursorOverloadedDeclRef(C).second;
3242
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003243 default:
3244 // FIXME: Need a way to enumerate all non-reference cases.
3245 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003246 }
3247 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003248
3249 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003250 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003251
3252 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003253 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003254
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003255 if (C.kind == CXCursor_PreprocessingDirective)
3256 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003257
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003258 if (C.kind == CXCursor_MacroInstantiation)
3259 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003260
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003261 if (C.kind == CXCursor_MacroDefinition)
3262 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003263
3264 if (C.kind == CXCursor_InclusionDirective)
3265 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3266
Ted Kremenek007a7c92010-11-01 23:26:51 +00003267 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3268 Decl *D = cxcursor::getCursorDecl(C);
3269 SourceRange R = D->getSourceRange();
3270 // FIXME: Multiple variables declared in a single declaration
3271 // currently lack the information needed to correctly determine their
3272 // ranges when accounting for the type-specifier. We use context
3273 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3274 // and if so, whether it is the first decl.
3275 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3276 if (!cxcursor::isFirstInDeclGroup(C))
3277 R.setBegin(VD->getLocation());
3278 }
3279 return R;
3280 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003281 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003282
3283extern "C" {
3284
3285CXSourceRange clang_getCursorExtent(CXCursor C) {
3286 SourceRange R = getRawCursorExtent(C);
3287 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003288 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003289
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003290 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003291}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003292
3293CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003294 if (clang_isInvalid(C.kind))
3295 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003296
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003297 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003298 if (clang_isDeclaration(C.kind)) {
3299 Decl *D = getCursorDecl(C);
3300 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3301 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3302 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3303 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3304 if (ObjCForwardProtocolDecl *Protocols
3305 = dyn_cast<ObjCForwardProtocolDecl>(D))
3306 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3307
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003308 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003309 }
3310
Douglas Gregor97b98722010-01-19 23:20:36 +00003311 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003312 Expr *E = getCursorExpr(C);
3313 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003314 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003315 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003316
3317 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3318 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3319
Douglas Gregor97b98722010-01-19 23:20:36 +00003320 return clang_getNullCursor();
3321 }
3322
Douglas Gregor36897b02010-09-10 00:22:18 +00003323 if (clang_isStatement(C.kind)) {
3324 Stmt *S = getCursorStmt(C);
3325 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3326 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3327 getCursorASTUnit(C));
3328
3329 return clang_getNullCursor();
3330 }
3331
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003332 if (C.kind == CXCursor_MacroInstantiation) {
3333 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3334 return MakeMacroDefinitionCursor(Def, CXXUnit);
3335 }
3336
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003337 if (!clang_isReference(C.kind))
3338 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003339
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003340 switch (C.kind) {
3341 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003342 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003343
3344 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003345 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003346
3347 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003348 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003349
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003350 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003351 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003352
3353 case CXCursor_TemplateRef:
3354 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3355
Douglas Gregor69319002010-08-31 23:48:11 +00003356 case CXCursor_NamespaceRef:
3357 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3358
Douglas Gregora67e03f2010-09-09 21:42:20 +00003359 case CXCursor_MemberRef:
3360 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3361
Ted Kremenek3064ef92010-08-27 21:34:58 +00003362 case CXCursor_CXXBaseSpecifier: {
3363 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3364 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3365 CXXUnit));
3366 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003367
Douglas Gregor36897b02010-09-10 00:22:18 +00003368 case CXCursor_LabelRef:
3369 // FIXME: We end up faking the "parent" declaration here because we
3370 // don't want to make CXCursor larger.
3371 return MakeCXCursor(getCursorLabelRef(C).first,
3372 CXXUnit->getASTContext().getTranslationUnitDecl(),
3373 CXXUnit);
3374
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003375 case CXCursor_OverloadedDeclRef:
3376 return C;
3377
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003378 default:
3379 // We would prefer to enumerate all non-reference cursor kinds here.
3380 llvm_unreachable("Unhandled reference cursor kind");
3381 break;
3382 }
3383 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003384
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003385 return clang_getNullCursor();
3386}
3387
Douglas Gregorb6998662010-01-19 19:34:47 +00003388CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003389 if (clang_isInvalid(C.kind))
3390 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003391
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003392 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003393
Douglas Gregorb6998662010-01-19 19:34:47 +00003394 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003395 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003396 C = clang_getCursorReferenced(C);
3397 WasReference = true;
3398 }
3399
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003400 if (C.kind == CXCursor_MacroInstantiation)
3401 return clang_getCursorReferenced(C);
3402
Douglas Gregorb6998662010-01-19 19:34:47 +00003403 if (!clang_isDeclaration(C.kind))
3404 return clang_getNullCursor();
3405
3406 Decl *D = getCursorDecl(C);
3407 if (!D)
3408 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003409
Douglas Gregorb6998662010-01-19 19:34:47 +00003410 switch (D->getKind()) {
3411 // Declaration kinds that don't really separate the notions of
3412 // declaration and definition.
3413 case Decl::Namespace:
3414 case Decl::Typedef:
3415 case Decl::TemplateTypeParm:
3416 case Decl::EnumConstant:
3417 case Decl::Field:
3418 case Decl::ObjCIvar:
3419 case Decl::ObjCAtDefsField:
3420 case Decl::ImplicitParam:
3421 case Decl::ParmVar:
3422 case Decl::NonTypeTemplateParm:
3423 case Decl::TemplateTemplateParm:
3424 case Decl::ObjCCategoryImpl:
3425 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003426 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003427 case Decl::LinkageSpec:
3428 case Decl::ObjCPropertyImpl:
3429 case Decl::FileScopeAsm:
3430 case Decl::StaticAssert:
3431 case Decl::Block:
3432 return C;
3433
3434 // Declaration kinds that don't make any sense here, but are
3435 // nonetheless harmless.
3436 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003437 break;
3438
3439 // Declaration kinds for which the definition is not resolvable.
3440 case Decl::UnresolvedUsingTypename:
3441 case Decl::UnresolvedUsingValue:
3442 break;
3443
3444 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003445 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3446 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003447
3448 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003449 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003450
3451 case Decl::Enum:
3452 case Decl::Record:
3453 case Decl::CXXRecord:
3454 case Decl::ClassTemplateSpecialization:
3455 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003456 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003457 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003458 return clang_getNullCursor();
3459
3460 case Decl::Function:
3461 case Decl::CXXMethod:
3462 case Decl::CXXConstructor:
3463 case Decl::CXXDestructor:
3464 case Decl::CXXConversion: {
3465 const FunctionDecl *Def = 0;
3466 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003467 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003468 return clang_getNullCursor();
3469 }
3470
3471 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003472 // Ask the variable if it has a definition.
3473 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3474 return MakeCXCursor(Def, CXXUnit);
3475 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003476 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003477
Douglas Gregorb6998662010-01-19 19:34:47 +00003478 case Decl::FunctionTemplate: {
3479 const FunctionDecl *Def = 0;
3480 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003481 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003482 return clang_getNullCursor();
3483 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003484
Douglas Gregorb6998662010-01-19 19:34:47 +00003485 case Decl::ClassTemplate: {
3486 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003487 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003488 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003489 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003490 return clang_getNullCursor();
3491 }
3492
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003493 case Decl::Using:
3494 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3495 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003496
3497 case Decl::UsingShadow:
3498 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003499 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003500 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003501
3502 case Decl::ObjCMethod: {
3503 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3504 if (Method->isThisDeclarationADefinition())
3505 return C;
3506
3507 // Dig out the method definition in the associated
3508 // @implementation, if we have it.
3509 // FIXME: The ASTs should make finding the definition easier.
3510 if (ObjCInterfaceDecl *Class
3511 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3512 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3513 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3514 Method->isInstanceMethod()))
3515 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003516 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003517
3518 return clang_getNullCursor();
3519 }
3520
3521 case Decl::ObjCCategory:
3522 if (ObjCCategoryImplDecl *Impl
3523 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003524 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003525 return clang_getNullCursor();
3526
3527 case Decl::ObjCProtocol:
3528 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3529 return C;
3530 return clang_getNullCursor();
3531
3532 case Decl::ObjCInterface:
3533 // There are two notions of a "definition" for an Objective-C
3534 // class: the interface and its implementation. When we resolved a
3535 // reference to an Objective-C class, produce the @interface as
3536 // the definition; when we were provided with the interface,
3537 // produce the @implementation as the definition.
3538 if (WasReference) {
3539 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3540 return C;
3541 } else if (ObjCImplementationDecl *Impl
3542 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003543 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003544 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003545
Douglas Gregorb6998662010-01-19 19:34:47 +00003546 case Decl::ObjCProperty:
3547 // FIXME: We don't really know where to find the
3548 // ObjCPropertyImplDecls that implement this property.
3549 return clang_getNullCursor();
3550
3551 case Decl::ObjCCompatibleAlias:
3552 if (ObjCInterfaceDecl *Class
3553 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3554 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003555 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003556
Douglas Gregorb6998662010-01-19 19:34:47 +00003557 return clang_getNullCursor();
3558
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003559 case Decl::ObjCForwardProtocol:
3560 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3561 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003562
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003563 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003564 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003565 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003566
3567 case Decl::Friend:
3568 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003569 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003570 return clang_getNullCursor();
3571
3572 case Decl::FriendTemplate:
3573 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003574 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003575 return clang_getNullCursor();
3576 }
3577
3578 return clang_getNullCursor();
3579}
3580
3581unsigned clang_isCursorDefinition(CXCursor C) {
3582 if (!clang_isDeclaration(C.kind))
3583 return 0;
3584
3585 return clang_getCursorDefinition(C) == C;
3586}
3587
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003588unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003589 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003590 return 0;
3591
3592 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3593 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3594 return E->getNumDecls();
3595
3596 if (OverloadedTemplateStorage *S
3597 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3598 return S->size();
3599
3600 Decl *D = Storage.get<Decl*>();
3601 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3602 return Using->getNumShadowDecls();
3603 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3604 return Classes->size();
3605 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3606 return Protocols->protocol_size();
3607
3608 return 0;
3609}
3610
3611CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003612 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003613 return clang_getNullCursor();
3614
3615 if (index >= clang_getNumOverloadedDecls(cursor))
3616 return clang_getNullCursor();
3617
3618 ASTUnit *Unit = getCursorASTUnit(cursor);
3619 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3620 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3621 return MakeCXCursor(E->decls_begin()[index], Unit);
3622
3623 if (OverloadedTemplateStorage *S
3624 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3625 return MakeCXCursor(S->begin()[index], Unit);
3626
3627 Decl *D = Storage.get<Decl*>();
3628 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3629 // FIXME: This is, unfortunately, linear time.
3630 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3631 std::advance(Pos, index);
3632 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3633 }
3634
3635 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3636 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3637
3638 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3639 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3640
3641 return clang_getNullCursor();
3642}
3643
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003644void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003645 const char **startBuf,
3646 const char **endBuf,
3647 unsigned *startLine,
3648 unsigned *startColumn,
3649 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003650 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003651 assert(getCursorDecl(C) && "CXCursor has null decl");
3652 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003653 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3654 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003655
Steve Naroff4ade6d62009-09-23 17:52:52 +00003656 SourceManager &SM = FD->getASTContext().getSourceManager();
3657 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3658 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3659 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3660 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3661 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3662 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3663}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003664
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003665void clang_enableStackTraces(void) {
3666 llvm::sys::PrintStackTraceOnErrorSignal();
3667}
3668
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003669void clang_executeOnThread(void (*fn)(void*), void *user_data,
3670 unsigned stack_size) {
3671 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3672}
3673
Ted Kremenekfb480492010-01-13 21:46:36 +00003674} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003675
Ted Kremenekfb480492010-01-13 21:46:36 +00003676//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003677// Token-based Operations.
3678//===----------------------------------------------------------------------===//
3679
3680/* CXToken layout:
3681 * int_data[0]: a CXTokenKind
3682 * int_data[1]: starting token location
3683 * int_data[2]: token length
3684 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003685 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003686 * otherwise unused.
3687 */
3688extern "C" {
3689
3690CXTokenKind clang_getTokenKind(CXToken CXTok) {
3691 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3692}
3693
3694CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3695 switch (clang_getTokenKind(CXTok)) {
3696 case CXToken_Identifier:
3697 case CXToken_Keyword:
3698 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003699 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3700 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003701
3702 case CXToken_Literal: {
3703 // We have stashed the starting pointer in the ptr_data field. Use it.
3704 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003705 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003706 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003707
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003708 case CXToken_Punctuation:
3709 case CXToken_Comment:
3710 break;
3711 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003712
3713 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003714 // deconstructing the source location.
3715 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3716 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003717 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003718
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003719 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3720 std::pair<FileID, unsigned> LocInfo
3721 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003722 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003723 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003724 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3725 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003726 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003727
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003728 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003729}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003730
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003731CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3732 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3733 if (!CXXUnit)
3734 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003735
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003736 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3737 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3738}
3739
3740CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3741 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003742 if (!CXXUnit)
3743 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003744
3745 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003746 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3747}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003748
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003749void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3750 CXToken **Tokens, unsigned *NumTokens) {
3751 if (Tokens)
3752 *Tokens = 0;
3753 if (NumTokens)
3754 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003755
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003756 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3757 if (!CXXUnit || !Tokens || !NumTokens)
3758 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003759
Douglas Gregorbdf60622010-03-05 21:16:25 +00003760 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3761
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003762 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003763 if (R.isInvalid())
3764 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003765
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003766 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3767 std::pair<FileID, unsigned> BeginLocInfo
3768 = SourceMgr.getDecomposedLoc(R.getBegin());
3769 std::pair<FileID, unsigned> EndLocInfo
3770 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003771
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003772 // Cannot tokenize across files.
3773 if (BeginLocInfo.first != EndLocInfo.first)
3774 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003775
3776 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003777 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003778 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003779 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003780 if (Invalid)
3781 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003782
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003783 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3784 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003785 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003786 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003787
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003788 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003789 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003790 llvm::SmallVector<CXToken, 32> CXTokens;
3791 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003792 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003793 do {
3794 // Lex the next token
3795 Lex.LexFromRawLexer(Tok);
3796 if (Tok.is(tok::eof))
3797 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003798
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003799 // Initialize the CXToken.
3800 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003801
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003802 // - Common fields
3803 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3804 CXTok.int_data[2] = Tok.getLength();
3805 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003806
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003807 // - Kind-specific fields
3808 if (Tok.isLiteral()) {
3809 CXTok.int_data[0] = CXToken_Literal;
3810 CXTok.ptr_data = (void *)Tok.getLiteralData();
3811 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003812 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003813 std::pair<FileID, unsigned> LocInfo
3814 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003815 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003816 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003817 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3818 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003819 return;
3820
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003821 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003822 IdentifierInfo *II
3823 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003824
David Chisnall096428b2010-10-13 21:44:48 +00003825 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003826 CXTok.int_data[0] = CXToken_Keyword;
3827 }
3828 else {
3829 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3830 CXToken_Identifier
3831 : CXToken_Keyword;
3832 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003833 CXTok.ptr_data = II;
3834 } else if (Tok.is(tok::comment)) {
3835 CXTok.int_data[0] = CXToken_Comment;
3836 CXTok.ptr_data = 0;
3837 } else {
3838 CXTok.int_data[0] = CXToken_Punctuation;
3839 CXTok.ptr_data = 0;
3840 }
3841 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003842 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003843 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003844
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003845 if (CXTokens.empty())
3846 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003847
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003848 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3849 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3850 *NumTokens = CXTokens.size();
3851}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003852
Ted Kremenek6db61092010-05-05 00:55:15 +00003853void clang_disposeTokens(CXTranslationUnit TU,
3854 CXToken *Tokens, unsigned NumTokens) {
3855 free(Tokens);
3856}
3857
3858} // end: extern "C"
3859
3860//===----------------------------------------------------------------------===//
3861// Token annotation APIs.
3862//===----------------------------------------------------------------------===//
3863
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003864typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003865static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3866 CXCursor parent,
3867 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003868namespace {
3869class AnnotateTokensWorker {
3870 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003871 CXToken *Tokens;
3872 CXCursor *Cursors;
3873 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003874 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003875 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003876 CursorVisitor AnnotateVis;
3877 SourceManager &SrcMgr;
3878
3879 bool MoreTokens() const { return TokIdx < NumTokens; }
3880 unsigned NextToken() const { return TokIdx; }
3881 void AdvanceToken() { ++TokIdx; }
3882 SourceLocation GetTokenLoc(unsigned tokI) {
3883 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3884 }
3885
Ted Kremenek6db61092010-05-05 00:55:15 +00003886public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003887 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003888 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3889 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003890 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003891 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003892 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3893 Decl::MaxPCHLevel, RegionOfInterest),
3894 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003895
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003896 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003897 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003898 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003899};
3900}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003901
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003902void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3903 // Walk the AST within the region of interest, annotating tokens
3904 // along the way.
3905 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003906
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003907 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3908 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003909 if (Pos != Annotated.end() &&
3910 (clang_isInvalid(Cursors[I].kind) ||
3911 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003912 Cursors[I] = Pos->second;
3913 }
3914
3915 // Finish up annotating any tokens left.
3916 if (!MoreTokens())
3917 return;
3918
3919 const CXCursor &C = clang_getNullCursor();
3920 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3921 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3922 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003923 }
3924}
3925
Ted Kremenek6db61092010-05-05 00:55:15 +00003926enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00003927AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003928 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00003929 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00003930 if (cursorRange.isInvalid())
3931 return CXChildVisit_Recurse;
3932
Douglas Gregor4419b672010-10-21 06:10:04 +00003933 if (clang_isPreprocessing(cursor.kind)) {
3934 // For macro instantiations, just note where the beginning of the macro
3935 // instantiation occurs.
3936 if (cursor.kind == CXCursor_MacroInstantiation) {
3937 Annotated[Loc.int_data] = cursor;
3938 return CXChildVisit_Recurse;
3939 }
3940
Douglas Gregor4419b672010-10-21 06:10:04 +00003941 // Items in the preprocessing record are kept separate from items in
3942 // declarations, so we keep a separate token index.
3943 unsigned SavedTokIdx = TokIdx;
3944 TokIdx = PreprocessingTokIdx;
3945
3946 // Skip tokens up until we catch up to the beginning of the preprocessing
3947 // entry.
3948 while (MoreTokens()) {
3949 const unsigned I = NextToken();
3950 SourceLocation TokLoc = GetTokenLoc(I);
3951 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3952 case RangeBefore:
3953 AdvanceToken();
3954 continue;
3955 case RangeAfter:
3956 case RangeOverlap:
3957 break;
3958 }
3959 break;
3960 }
3961
3962 // Look at all of the tokens within this range.
3963 while (MoreTokens()) {
3964 const unsigned I = NextToken();
3965 SourceLocation TokLoc = GetTokenLoc(I);
3966 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3967 case RangeBefore:
3968 assert(0 && "Infeasible");
3969 case RangeAfter:
3970 break;
3971 case RangeOverlap:
3972 Cursors[I] = cursor;
3973 AdvanceToken();
3974 continue;
3975 }
3976 break;
3977 }
3978
3979 // Save the preprocessing token index; restore the non-preprocessing
3980 // token index.
3981 PreprocessingTokIdx = TokIdx;
3982 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003983 return CXChildVisit_Recurse;
3984 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003985
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003986 if (cursorRange.isInvalid())
3987 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00003988
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003989 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
3990
Ted Kremeneka333c662010-05-12 05:29:33 +00003991 // Adjust the annotated range based specific declarations.
3992 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
3993 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00003994 Decl *D = cxcursor::getCursorDecl(cursor);
3995 // Don't visit synthesized ObjC methods, since they have no syntatic
3996 // representation in the source.
3997 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
3998 if (MD->isSynthesized())
3999 return CXChildVisit_Continue;
4000 }
4001 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004002 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4003 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004004 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004005 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004006 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004007 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004008 }
4009 }
4010 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004011
Ted Kremenek3f404602010-08-14 01:14:06 +00004012 // If the location of the cursor occurs within a macro instantiation, record
4013 // the spelling location of the cursor in our annotation map. We can then
4014 // paper over the token labelings during a post-processing step to try and
4015 // get cursor mappings for tokens that are the *arguments* of a macro
4016 // instantiation.
4017 if (L.isMacroID()) {
4018 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4019 // Only invalidate the old annotation if it isn't part of a preprocessing
4020 // directive. Here we assume that the default construction of CXCursor
4021 // results in CXCursor.kind being an initialized value (i.e., 0). If
4022 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004023
Ted Kremenek3f404602010-08-14 01:14:06 +00004024 CXCursor &oldC = Annotated[rawEncoding];
4025 if (!clang_isPreprocessing(oldC.kind))
4026 oldC = cursor;
4027 }
4028
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004029 const enum CXCursorKind K = clang_getCursorKind(parent);
4030 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004031 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4032 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004033
4034 while (MoreTokens()) {
4035 const unsigned I = NextToken();
4036 SourceLocation TokLoc = GetTokenLoc(I);
4037 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4038 case RangeBefore:
4039 Cursors[I] = updateC;
4040 AdvanceToken();
4041 continue;
4042 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004043 case RangeOverlap:
4044 break;
4045 }
4046 break;
4047 }
4048
4049 // Visit children to get their cursor information.
4050 const unsigned BeforeChildren = NextToken();
4051 VisitChildren(cursor);
4052 const unsigned AfterChildren = NextToken();
4053
4054 // Adjust 'Last' to the last token within the extent of the cursor.
4055 while (MoreTokens()) {
4056 const unsigned I = NextToken();
4057 SourceLocation TokLoc = GetTokenLoc(I);
4058 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4059 case RangeBefore:
4060 assert(0 && "Infeasible");
4061 case RangeAfter:
4062 break;
4063 case RangeOverlap:
4064 Cursors[I] = updateC;
4065 AdvanceToken();
4066 continue;
4067 }
4068 break;
4069 }
4070 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004071
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004072 // Scan the tokens that are at the beginning of the cursor, but are not
4073 // capture by the child cursors.
4074
4075 // For AST elements within macros, rely on a post-annotate pass to
4076 // to correctly annotate the tokens with cursors. Otherwise we can
4077 // get confusing results of having tokens that map to cursors that really
4078 // are expanded by an instantiation.
4079 if (L.isMacroID())
4080 cursor = clang_getNullCursor();
4081
4082 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4083 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4084 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004085
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004086 Cursors[I] = cursor;
4087 }
4088 // Scan the tokens that are at the end of the cursor, but are not captured
4089 // but the child cursors.
4090 for (unsigned I = AfterChildren; I != Last; ++I)
4091 Cursors[I] = cursor;
4092
4093 TokIdx = Last;
4094 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004095}
4096
Ted Kremenek6db61092010-05-05 00:55:15 +00004097static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4098 CXCursor parent,
4099 CXClientData client_data) {
4100 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4101}
4102
4103extern "C" {
4104
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004105void clang_annotateTokens(CXTranslationUnit TU,
4106 CXToken *Tokens, unsigned NumTokens,
4107 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004108
4109 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004110 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004111
Douglas Gregor4419b672010-10-21 06:10:04 +00004112 // Any token we don't specifically annotate will have a NULL cursor.
4113 CXCursor C = clang_getNullCursor();
4114 for (unsigned I = 0; I != NumTokens; ++I)
4115 Cursors[I] = C;
4116
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004117 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004118 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004119 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004120
Douglas Gregorbdf60622010-03-05 21:16:25 +00004121 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004122
Douglas Gregor0396f462010-03-19 05:22:59 +00004123 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004124 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004125 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4126 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004127 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4128 clang_getTokenLocation(TU,
4129 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004130
Douglas Gregor0396f462010-03-19 05:22:59 +00004131 // A mapping from the source locations found when re-lexing or traversing the
4132 // region of interest to the corresponding cursors.
4133 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004134
4135 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004136 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004137 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4138 std::pair<FileID, unsigned> BeginLocInfo
4139 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4140 std::pair<FileID, unsigned> EndLocInfo
4141 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004142
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004143 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004144 bool Invalid = false;
4145 if (BeginLocInfo.first == EndLocInfo.first &&
4146 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4147 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004148 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4149 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004150 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004151 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004152 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004153
4154 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004155 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004156 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004157 Token Tok;
4158 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004159
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004160 reprocess:
4161 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4162 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004163 // don't see it while preprocessing these tokens later, but keep track
4164 // of all of the token locations inside this preprocessing directive so
4165 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004166 //
4167 // FIXME: Some simple tests here could identify macro definitions and
4168 // #undefs, to provide specific cursor kinds for those.
4169 std::vector<SourceLocation> Locations;
4170 do {
4171 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004172 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004173 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004174
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004175 using namespace cxcursor;
4176 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004177 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4178 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004179 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004180 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4181 Annotated[Locations[I].getRawEncoding()] = Cursor;
4182 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004183
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004184 if (Tok.isAtStartOfLine())
4185 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004186
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004187 continue;
4188 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004189
Douglas Gregor48072312010-03-18 15:23:44 +00004190 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004191 break;
4192 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004193 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004194
Douglas Gregor0396f462010-03-19 05:22:59 +00004195 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004196 // a specific cursor.
4197 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4198 CXXUnit, RegionOfInterest);
4199 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004200}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004201} // end: extern "C"
4202
4203//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004204// Operations for querying linkage of a cursor.
4205//===----------------------------------------------------------------------===//
4206
4207extern "C" {
4208CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004209 if (!clang_isDeclaration(cursor.kind))
4210 return CXLinkage_Invalid;
4211
Ted Kremenek16b42592010-03-03 06:36:57 +00004212 Decl *D = cxcursor::getCursorDecl(cursor);
4213 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4214 switch (ND->getLinkage()) {
4215 case NoLinkage: return CXLinkage_NoLinkage;
4216 case InternalLinkage: return CXLinkage_Internal;
4217 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4218 case ExternalLinkage: return CXLinkage_External;
4219 };
4220
4221 return CXLinkage_Invalid;
4222}
4223} // end: extern "C"
4224
4225//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004226// Operations for querying language of a cursor.
4227//===----------------------------------------------------------------------===//
4228
4229static CXLanguageKind getDeclLanguage(const Decl *D) {
4230 switch (D->getKind()) {
4231 default:
4232 break;
4233 case Decl::ImplicitParam:
4234 case Decl::ObjCAtDefsField:
4235 case Decl::ObjCCategory:
4236 case Decl::ObjCCategoryImpl:
4237 case Decl::ObjCClass:
4238 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004239 case Decl::ObjCForwardProtocol:
4240 case Decl::ObjCImplementation:
4241 case Decl::ObjCInterface:
4242 case Decl::ObjCIvar:
4243 case Decl::ObjCMethod:
4244 case Decl::ObjCProperty:
4245 case Decl::ObjCPropertyImpl:
4246 case Decl::ObjCProtocol:
4247 return CXLanguage_ObjC;
4248 case Decl::CXXConstructor:
4249 case Decl::CXXConversion:
4250 case Decl::CXXDestructor:
4251 case Decl::CXXMethod:
4252 case Decl::CXXRecord:
4253 case Decl::ClassTemplate:
4254 case Decl::ClassTemplatePartialSpecialization:
4255 case Decl::ClassTemplateSpecialization:
4256 case Decl::Friend:
4257 case Decl::FriendTemplate:
4258 case Decl::FunctionTemplate:
4259 case Decl::LinkageSpec:
4260 case Decl::Namespace:
4261 case Decl::NamespaceAlias:
4262 case Decl::NonTypeTemplateParm:
4263 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004264 case Decl::TemplateTemplateParm:
4265 case Decl::TemplateTypeParm:
4266 case Decl::UnresolvedUsingTypename:
4267 case Decl::UnresolvedUsingValue:
4268 case Decl::Using:
4269 case Decl::UsingDirective:
4270 case Decl::UsingShadow:
4271 return CXLanguage_CPlusPlus;
4272 }
4273
4274 return CXLanguage_C;
4275}
4276
4277extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004278
4279enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4280 if (clang_isDeclaration(cursor.kind))
4281 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4282 if (D->hasAttr<UnavailableAttr>() ||
4283 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4284 return CXAvailability_Available;
4285
4286 if (D->hasAttr<DeprecatedAttr>())
4287 return CXAvailability_Deprecated;
4288 }
4289
4290 return CXAvailability_Available;
4291}
4292
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004293CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4294 if (clang_isDeclaration(cursor.kind))
4295 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4296
4297 return CXLanguage_Invalid;
4298}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004299
4300CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4301 if (clang_isDeclaration(cursor.kind)) {
4302 if (Decl *D = getCursorDecl(cursor)) {
4303 DeclContext *DC = D->getDeclContext();
4304 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4305 }
4306 }
4307
4308 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4309 if (Decl *D = getCursorDecl(cursor))
4310 return MakeCXCursor(D, getCursorASTUnit(cursor));
4311 }
4312
4313 return clang_getNullCursor();
4314}
4315
4316CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4317 if (clang_isDeclaration(cursor.kind)) {
4318 if (Decl *D = getCursorDecl(cursor)) {
4319 DeclContext *DC = D->getLexicalDeclContext();
4320 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4321 }
4322 }
4323
4324 // FIXME: Note that we can't easily compute the lexical context of a
4325 // statement or expression, so we return nothing.
4326 return clang_getNullCursor();
4327}
4328
Douglas Gregor9f592342010-10-01 20:25:15 +00004329static void CollectOverriddenMethods(DeclContext *Ctx,
4330 ObjCMethodDecl *Method,
4331 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4332 if (!Ctx)
4333 return;
4334
4335 // If we have a class or category implementation, jump straight to the
4336 // interface.
4337 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4338 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4339
4340 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4341 if (!Container)
4342 return;
4343
4344 // Check whether we have a matching method at this level.
4345 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4346 Method->isInstanceMethod()))
4347 if (Method != Overridden) {
4348 // We found an override at this level; there is no need to look
4349 // into other protocols or categories.
4350 Methods.push_back(Overridden);
4351 return;
4352 }
4353
4354 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4355 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4356 PEnd = Protocol->protocol_end();
4357 P != PEnd; ++P)
4358 CollectOverriddenMethods(*P, Method, Methods);
4359 }
4360
4361 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4362 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4363 PEnd = Category->protocol_end();
4364 P != PEnd; ++P)
4365 CollectOverriddenMethods(*P, Method, Methods);
4366 }
4367
4368 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4369 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4370 PEnd = Interface->protocol_end();
4371 P != PEnd; ++P)
4372 CollectOverriddenMethods(*P, Method, Methods);
4373
4374 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4375 Category; Category = Category->getNextClassCategory())
4376 CollectOverriddenMethods(Category, Method, Methods);
4377
4378 // We only look into the superclass if we haven't found anything yet.
4379 if (Methods.empty())
4380 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4381 return CollectOverriddenMethods(Super, Method, Methods);
4382 }
4383}
4384
4385void clang_getOverriddenCursors(CXCursor cursor,
4386 CXCursor **overridden,
4387 unsigned *num_overridden) {
4388 if (overridden)
4389 *overridden = 0;
4390 if (num_overridden)
4391 *num_overridden = 0;
4392 if (!overridden || !num_overridden)
4393 return;
4394
4395 if (!clang_isDeclaration(cursor.kind))
4396 return;
4397
4398 Decl *D = getCursorDecl(cursor);
4399 if (!D)
4400 return;
4401
4402 // Handle C++ member functions.
4403 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4404 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4405 *num_overridden = CXXMethod->size_overridden_methods();
4406 if (!*num_overridden)
4407 return;
4408
4409 *overridden = new CXCursor [*num_overridden];
4410 unsigned I = 0;
4411 for (CXXMethodDecl::method_iterator
4412 M = CXXMethod->begin_overridden_methods(),
4413 MEnd = CXXMethod->end_overridden_methods();
4414 M != MEnd; (void)++M, ++I)
4415 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4416 return;
4417 }
4418
4419 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4420 if (!Method)
4421 return;
4422
4423 // Handle Objective-C methods.
4424 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4425 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4426
4427 if (Methods.empty())
4428 return;
4429
4430 *num_overridden = Methods.size();
4431 *overridden = new CXCursor [Methods.size()];
4432 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4433 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4434}
4435
4436void clang_disposeOverriddenCursors(CXCursor *overridden) {
4437 delete [] overridden;
4438}
4439
Douglas Gregorecdcb882010-10-20 22:00:55 +00004440CXFile clang_getIncludedFile(CXCursor cursor) {
4441 if (cursor.kind != CXCursor_InclusionDirective)
4442 return 0;
4443
4444 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4445 return (void *)ID->getFile();
4446}
4447
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004448} // end: extern "C"
4449
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004450
4451//===----------------------------------------------------------------------===//
4452// C++ AST instrospection.
4453//===----------------------------------------------------------------------===//
4454
4455extern "C" {
4456unsigned clang_CXXMethod_isStatic(CXCursor C) {
4457 if (!clang_isDeclaration(C.kind))
4458 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004459
4460 CXXMethodDecl *Method = 0;
4461 Decl *D = cxcursor::getCursorDecl(C);
4462 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4463 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4464 else
4465 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4466 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004467}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004468
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004469} // end: extern "C"
4470
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004471//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004472// Attribute introspection.
4473//===----------------------------------------------------------------------===//
4474
4475extern "C" {
4476CXType clang_getIBOutletCollectionType(CXCursor C) {
4477 if (C.kind != CXCursor_IBOutletCollectionAttr)
4478 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4479
4480 IBOutletCollectionAttr *A =
4481 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4482
4483 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4484}
4485} // end: extern "C"
4486
4487//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004488// CXString Operations.
4489//===----------------------------------------------------------------------===//
4490
4491extern "C" {
4492const char *clang_getCString(CXString string) {
4493 return string.Spelling;
4494}
4495
4496void clang_disposeString(CXString string) {
4497 if (string.MustFreeString && string.Spelling)
4498 free((void*)string.Spelling);
4499}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004500
Ted Kremenekfb480492010-01-13 21:46:36 +00004501} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004502
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004503namespace clang { namespace cxstring {
4504CXString createCXString(const char *String, bool DupString){
4505 CXString Str;
4506 if (DupString) {
4507 Str.Spelling = strdup(String);
4508 Str.MustFreeString = 1;
4509 } else {
4510 Str.Spelling = String;
4511 Str.MustFreeString = 0;
4512 }
4513 return Str;
4514}
4515
4516CXString createCXString(llvm::StringRef String, bool DupString) {
4517 CXString Result;
4518 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4519 char *Spelling = (char *)malloc(String.size() + 1);
4520 memmove(Spelling, String.data(), String.size());
4521 Spelling[String.size()] = 0;
4522 Result.Spelling = Spelling;
4523 Result.MustFreeString = 1;
4524 } else {
4525 Result.Spelling = String.data();
4526 Result.MustFreeString = 0;
4527 }
4528 return Result;
4529}
4530}}
4531
Ted Kremenek04bb7162010-01-22 22:44:15 +00004532//===----------------------------------------------------------------------===//
4533// Misc. utility functions.
4534//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004535
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004536/// Default to using an 8 MB stack size on "safety" threads.
4537static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004538
4539namespace clang {
4540
4541bool RunSafely(llvm::CrashRecoveryContext &CRC,
4542 void (*Fn)(void*), void *UserData) {
4543 if (unsigned Size = GetSafetyThreadStackSize())
4544 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4545 return CRC.RunSafely(Fn, UserData);
4546}
4547
4548unsigned GetSafetyThreadStackSize() {
4549 return SafetyStackThreadSize;
4550}
4551
4552void SetSafetyThreadStackSize(unsigned Value) {
4553 SafetyStackThreadSize = Value;
4554}
4555
4556}
4557
Ted Kremenek04bb7162010-01-22 22:44:15 +00004558extern "C" {
4559
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004560CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004561 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004562}
4563
4564} // end: extern "C"