blob: 30e903449fd61711a7395d5c04c0210eff0390c7 [file] [log] [blame]
Ted Kremenekd2fa5662009-08-26 22:36:44 +00001//===- CIndex.cpp - Clang-C Source Indexing Library -----------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00007//
Ted Kremenekd2fa5662009-08-26 22:36:44 +00008//===----------------------------------------------------------------------===//
9//
Ted Kremenekab188932010-01-05 19:32:54 +000010// This file implements the main API hooks in the Clang-C Source Indexing
11// library.
Ted Kremenekd2fa5662009-08-26 22:36:44 +000012//
13//===----------------------------------------------------------------------===//
14
Ted Kremenekab188932010-01-05 19:32:54 +000015#include "CIndexer.h"
Ted Kremenek16c440a2010-01-15 20:35:54 +000016#include "CXCursor.h"
Ted Kremenek95f33552010-08-26 01:42:22 +000017#include "CXType.h"
Ted Kremeneka297de22010-01-25 22:34:44 +000018#include "CXSourceLocation.h"
Douglas Gregor5352ac02010-01-28 00:27:43 +000019#include "CIndexDiagnostic.h"
Ted Kremenekab188932010-01-05 19:32:54 +000020
Ted Kremenek04bb7162010-01-22 22:44:15 +000021#include "clang/Basic/Version.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000022
Steve Naroff50398192009-08-28 15:28:48 +000023#include "clang/AST/DeclVisitor.h"
Steve Narofffb570422009-09-22 19:25:29 +000024#include "clang/AST/StmtVisitor.h"
Douglas Gregor7d0d40e2010-01-21 16:28:34 +000025#include "clang/AST/TypeLocVisitor.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000026#include "clang/Basic/Diagnostic.h"
27#include "clang/Frontend/ASTUnit.h"
28#include "clang/Frontend/CompilerInstance.h"
Douglas Gregor936ea3b2010-01-28 00:56:43 +000029#include "clang/Frontend/FrontendDiagnostic.h"
Ted Kremenekd8210652010-01-06 23:43:31 +000030#include "clang/Lex/Lexer.h"
Benjamin Kramerb846deb2010-04-12 19:45:50 +000031#include "clang/Lex/PreprocessingRecord.h"
Douglas Gregor33e9abd2010-01-22 19:49:59 +000032#include "clang/Lex/Preprocessor.h"
Douglas Gregora67e03f2010-09-09 21:42:20 +000033#include "llvm/ADT/STLExtras.h"
Ted Kremenekd8c370c2010-11-02 23:10:24 +000034#include "llvm/ADT/Optional.h"
35#include "clang/Analysis/Support/SaveAndRestore.h"
Daniel Dunbarc7df4f32010-08-18 18:43:14 +000036#include "llvm/Support/CrashRecoveryContext.h"
Daniel Dunbar48615ff2010-10-08 19:30:33 +000037#include "llvm/Support/PrettyStackTrace.h"
Douglas Gregor02465752009-10-16 21:24:31 +000038#include "llvm/Support/MemoryBuffer.h"
Douglas Gregor358559d2010-10-02 22:49:11 +000039#include "llvm/Support/raw_ostream.h"
Douglas Gregor7a07fcb2010-08-09 21:00:09 +000040#include "llvm/Support/Timer.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000041#include "llvm/System/Mutex.h"
Benjamin Kramer0829a832009-10-18 11:19:36 +000042#include "llvm/System/Program.h"
Douglas Gregor0a812cf2010-02-18 23:07:20 +000043#include "llvm/System/Signals.h"
Douglas Gregor8c8d5412010-09-24 21:18:36 +000044#include "llvm/System/Threading.h"
Ted Kremenekfc062212009-10-19 21:44:57 +000045
Benjamin Kramerc2a98162010-03-13 21:22:49 +000046// Needed to define L_TMPNAM on some systems.
47#include <cstdio>
48
Steve Naroff50398192009-08-28 15:28:48 +000049using namespace clang;
Ted Kremenek16c440a2010-01-15 20:35:54 +000050using namespace clang::cxcursor;
Ted Kremenekee4db4f2010-02-17 00:41:08 +000051using namespace clang::cxstring;
Steve Naroff50398192009-08-28 15:28:48 +000052
Douglas Gregor33e9abd2010-01-22 19:49:59 +000053/// \brief The result of comparing two source ranges.
54enum RangeComparisonResult {
55 /// \brief Either the ranges overlap or one of the ranges is invalid.
56 RangeOverlap,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000057
Douglas Gregor33e9abd2010-01-22 19:49:59 +000058 /// \brief The first range ends before the second range starts.
59 RangeBefore,
Ted Kremenekf0e23e82010-02-17 00:41:40 +000060
Douglas Gregor33e9abd2010-01-22 19:49:59 +000061 /// \brief The first range starts after the second range ends.
62 RangeAfter
63};
64
Ted Kremenekf0e23e82010-02-17 00:41:40 +000065/// \brief Compare two source ranges to determine their relative position in
Douglas Gregor33e9abd2010-01-22 19:49:59 +000066/// the translation unit.
Ted Kremenekf0e23e82010-02-17 00:41:40 +000067static RangeComparisonResult RangeCompare(SourceManager &SM,
68 SourceRange R1,
Douglas Gregor33e9abd2010-01-22 19:49:59 +000069 SourceRange R2) {
70 assert(R1.isValid() && "First range is invalid?");
71 assert(R2.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000072 if (R1.getEnd() != R2.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000073 SM.isBeforeInTranslationUnit(R1.getEnd(), R2.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000074 return RangeBefore;
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000075 if (R2.getEnd() != R1.getBegin() &&
Daniel Dunbard52864b2010-02-14 10:02:57 +000076 SM.isBeforeInTranslationUnit(R2.getEnd(), R1.getBegin()))
Douglas Gregor33e9abd2010-01-22 19:49:59 +000077 return RangeAfter;
78 return RangeOverlap;
79}
80
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000081/// \brief Determine if a source location falls within, before, or after a
82/// a given source range.
83static RangeComparisonResult LocationCompare(SourceManager &SM,
84 SourceLocation L, SourceRange R) {
85 assert(R.isValid() && "First range is invalid?");
86 assert(L.isValid() && "Second range is invalid?");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +000087 if (L == R.getBegin() || L == R.getEnd())
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000088 return RangeOverlap;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +000089 if (SM.isBeforeInTranslationUnit(L, R.getBegin()))
90 return RangeBefore;
91 if (SM.isBeforeInTranslationUnit(R.getEnd(), L))
92 return RangeAfter;
93 return RangeOverlap;
94}
95
Daniel Dunbar76dd3c22010-02-14 01:47:29 +000096/// \brief Translate a Clang source range into a CIndex source range.
97///
98/// Clang internally represents ranges where the end location points to the
99/// start of the token at the end. However, for external clients it is more
100/// useful to have a CXSourceRange be a proper half-open interval. This routine
101/// does the appropriate translation.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000102CXSourceRange cxloc::translateSourceRange(const SourceManager &SM,
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000103 const LangOptions &LangOpts,
Chris Lattner0a76aae2010-06-18 22:45:06 +0000104 const CharSourceRange &R) {
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000105 // We want the last character in this location, so we will adjust the
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000106 // location accordingly.
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000107 SourceLocation EndLoc = R.getEnd();
Douglas Gregora9b06d42010-11-09 06:24:54 +0000108 if (EndLoc.isValid() && EndLoc.isMacroID())
109 EndLoc = SM.getSpellingLoc(EndLoc);
Chris Lattner0a76aae2010-06-18 22:45:06 +0000110 if (R.isTokenRange() && !EndLoc.isInvalid() && EndLoc.isFileID()) {
Douglas Gregor6a5a23f2010-03-19 21:51:54 +0000111 unsigned Length = Lexer::MeasureTokenLength(EndLoc, SM, LangOpts);
Daniel Dunbar76dd3c22010-02-14 01:47:29 +0000112 EndLoc = EndLoc.getFileLocWithOffset(Length);
113 }
114
115 CXSourceRange Result = { { (void *)&SM, (void *)&LangOpts },
116 R.getBegin().getRawEncoding(),
117 EndLoc.getRawEncoding() };
118 return Result;
119}
Douglas Gregor1db19de2010-01-19 21:36:55 +0000120
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000121//===----------------------------------------------------------------------===//
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000122// Cursor visitor.
Ted Kremenek8a8da7d2010-01-06 03:42:32 +0000123//===----------------------------------------------------------------------===//
124
Steve Naroff89922f82009-08-31 00:59:03 +0000125namespace {
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000126
Douglas Gregorb1373d02010-01-20 20:59:29 +0000127// Cursor visitor.
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000128class CursorVisitor : public DeclVisitor<CursorVisitor, bool>,
Douglas Gregora59e3902010-01-21 23:27:09 +0000129 public TypeLocVisitor<CursorVisitor, bool>,
130 public StmtVisitor<CursorVisitor, bool>
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000131{
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000132 /// \brief The translation unit we are traversing.
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000133 ASTUnit *TU;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000134
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000135 /// \brief The parent cursor whose children we are traversing.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000136 CXCursor Parent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000137
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000138 /// \brief The declaration that serves at the parent of any statement or
139 /// expression nodes.
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000140 Decl *StmtParent;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000141
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000142 /// \brief The visitor function.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000143 CXCursorVisitor Visitor;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000144
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000145 /// \brief The opaque client data, to be passed along to the visitor.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000146 CXClientData ClientData;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000147
Douglas Gregor7d1d49d2009-10-16 20:01:17 +0000148 // MaxPCHLevel - the maximum PCH level of declarations that we will pass on
149 // to the visitor. Declarations with a PCH level greater than this value will
150 // be suppressed.
151 unsigned MaxPCHLevel;
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000152
153 /// \brief When valid, a source range to which the cursor should restrict
154 /// its search.
155 SourceRange RegionOfInterest;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000156
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000157 // FIXME: Eventually remove. This part of a hack to support proper
158 // iteration over all Decls contained lexically within an ObjC container.
159 DeclContext::decl_iterator *DI_current;
160 DeclContext::decl_iterator DE_current;
161
Douglas Gregorb1373d02010-01-20 20:59:29 +0000162 using DeclVisitor<CursorVisitor, bool>::Visit;
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000163 using TypeLocVisitor<CursorVisitor, bool>::Visit;
Douglas Gregora59e3902010-01-21 23:27:09 +0000164 using StmtVisitor<CursorVisitor, bool>::Visit;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000165
166 /// \brief Determine whether this particular source range comes before, comes
167 /// after, or overlaps the region of interest.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000168 ///
Daniel Dunbard52864b2010-02-14 10:02:57 +0000169 /// \param R a half-open source range retrieved from the abstract syntax tree.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000170 RangeComparisonResult CompareRegionOfInterest(SourceRange R);
171
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000172 class SetParentRAII {
173 CXCursor &Parent;
174 Decl *&StmtParent;
175 CXCursor OldParent;
176
177 public:
178 SetParentRAII(CXCursor &Parent, Decl *&StmtParent, CXCursor NewParent)
179 : Parent(Parent), StmtParent(StmtParent), OldParent(Parent)
180 {
181 Parent = NewParent;
182 if (clang_isDeclaration(Parent.kind))
183 StmtParent = getCursorDecl(Parent);
184 }
185
186 ~SetParentRAII() {
187 Parent = OldParent;
188 if (clang_isDeclaration(Parent.kind))
189 StmtParent = getCursorDecl(Parent);
190 }
191 };
192
Steve Naroff89922f82009-08-31 00:59:03 +0000193public:
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000194 CursorVisitor(ASTUnit *TU, CXCursorVisitor Visitor, CXClientData ClientData,
195 unsigned MaxPCHLevel,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000196 SourceRange RegionOfInterest = SourceRange())
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000197 : TU(TU), Visitor(Visitor), ClientData(ClientData),
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000198 MaxPCHLevel(MaxPCHLevel), RegionOfInterest(RegionOfInterest),
199 DI_current(0)
Douglas Gregorb1373d02010-01-20 20:59:29 +0000200 {
201 Parent.kind = CXCursor_NoDeclFound;
202 Parent.data[0] = 0;
203 Parent.data[1] = 0;
204 Parent.data[2] = 0;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000205 StmtParent = 0;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000206 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000207
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000208 bool Visit(CXCursor Cursor, bool CheckedRegionOfInterest = false);
Douglas Gregor788f5a12010-03-20 00:41:21 +0000209
210 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
211 getPreprocessedEntities();
212
Douglas Gregorb1373d02010-01-20 20:59:29 +0000213 bool VisitChildren(CXCursor Parent);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000214
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000215 // Declaration visitors
Ted Kremenek09dfa372010-02-18 05:46:33 +0000216 bool VisitAttributes(Decl *D);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000217 bool VisitBlockDecl(BlockDecl *B);
Ted Kremenek3064ef92010-08-27 21:34:58 +0000218 bool VisitCXXRecordDecl(CXXRecordDecl *D);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000219 llvm::Optional<bool> shouldVisitCursor(CXCursor C);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000220 bool VisitDeclContext(DeclContext *DC);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000221 bool VisitTranslationUnitDecl(TranslationUnitDecl *D);
222 bool VisitTypedefDecl(TypedefDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000223 bool VisitTagDecl(TagDecl *D);
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000224 bool VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D);
Douglas Gregor74dbe642010-08-31 19:31:58 +0000225 bool VisitClassTemplatePartialSpecializationDecl(
226 ClassTemplatePartialSpecializationDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000227 bool VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000228 bool VisitEnumConstantDecl(EnumConstantDecl *D);
229 bool VisitDeclaratorDecl(DeclaratorDecl *DD);
230 bool VisitFunctionDecl(FunctionDecl *ND);
231 bool VisitFieldDecl(FieldDecl *D);
Ted Kremenek4540c9c2010-02-18 18:47:08 +0000232 bool VisitVarDecl(VarDecl *);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000233 bool VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000234 bool VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
Douglas Gregor39d6f072010-08-31 19:02:00 +0000235 bool VisitClassTemplateDecl(ClassTemplateDecl *D);
Douglas Gregor84b51d72010-09-01 20:16:53 +0000236 bool VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000237 bool VisitObjCMethodDecl(ObjCMethodDecl *ND);
238 bool VisitObjCContainerDecl(ObjCContainerDecl *D);
239 bool VisitObjCCategoryDecl(ObjCCategoryDecl *ND);
240 bool VisitObjCProtocolDecl(ObjCProtocolDecl *PID);
Ted Kremenek23173d72010-05-18 21:09:07 +0000241 bool VisitObjCPropertyDecl(ObjCPropertyDecl *PD);
Ted Kremenek79758f62010-02-18 22:36:18 +0000242 bool VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
243 bool VisitObjCImplDecl(ObjCImplDecl *D);
244 bool VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
245 bool VisitObjCImplementationDecl(ObjCImplementationDecl *D);
Ted Kremenek79758f62010-02-18 22:36:18 +0000246 // FIXME: ObjCCompatibleAliasDecl requires aliased-class locations.
247 bool VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
248 bool VisitObjCClassDecl(ObjCClassDecl *D);
Ted Kremeneka0536d82010-05-07 01:04:29 +0000249 bool VisitLinkageSpecDecl(LinkageSpecDecl *D);
Ted Kremenek8f06e0e2010-05-06 23:38:21 +0000250 bool VisitNamespaceDecl(NamespaceDecl *D);
Douglas Gregor69319002010-08-31 23:48:11 +0000251 bool VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000252 bool VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
Douglas Gregor7e242562010-09-01 19:52:22 +0000253 bool VisitUsingDecl(UsingDecl *D);
254 bool VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
255 bool VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
Douglas Gregor0a35bce2010-09-01 03:07:18 +0000256
Douglas Gregor01829d32010-08-31 14:41:23 +0000257 // Name visitor
258 bool VisitDeclarationNameInfo(DeclarationNameInfo Name);
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000259 bool VisitNestedNameSpecifier(NestedNameSpecifier *NNS, SourceRange Range);
Douglas Gregor01829d32010-08-31 14:41:23 +0000260
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000261 // Template visitors
262 bool VisitTemplateParameters(const TemplateParameterList *Params);
Douglas Gregor0b36e612010-08-31 20:37:03 +0000263 bool VisitTemplateName(TemplateName Name, SourceLocation Loc);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000264 bool VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL);
265
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000266 // Type visitors
Douglas Gregor01829d32010-08-31 14:41:23 +0000267 bool VisitQualifiedTypeLoc(QualifiedTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000268 bool VisitBuiltinTypeLoc(BuiltinTypeLoc TL);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000269 bool VisitTypedefTypeLoc(TypedefTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000270 bool VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL);
271 bool VisitTagTypeLoc(TagTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000272 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000273 bool VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL);
John McCallc12c5bb2010-05-15 11:32:37 +0000274 bool VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000275 bool VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL);
276 bool VisitPointerTypeLoc(PointerTypeLoc TL);
277 bool VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL);
278 bool VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL);
279 bool VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL);
280 bool VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL);
Douglas Gregor01829d32010-08-31 14:41:23 +0000281 bool VisitFunctionTypeLoc(FunctionTypeLoc TL, bool SkipResultType = false);
Douglas Gregorf20dfbc2010-01-21 17:29:07 +0000282 bool VisitArrayTypeLoc(ArrayTypeLoc TL);
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000283 bool VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL);
Douglas Gregor2332c112010-01-21 20:48:56 +0000284 // FIXME: Implement visitors here when the unimplemented TypeLocs get
285 // implemented
286 bool VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL);
287 bool VisitTypeOfTypeLoc(TypeOfTypeLoc TL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000288
Douglas Gregora59e3902010-01-21 23:27:09 +0000289 // Statement visitors
290 bool VisitStmt(Stmt *S);
291 bool VisitDeclStmt(DeclStmt *S);
Douglas Gregor36897b02010-09-10 00:22:18 +0000292 bool VisitGotoStmt(GotoStmt *S);
Douglas Gregorf5bab412010-01-22 01:00:11 +0000293 bool VisitIfStmt(IfStmt *S);
294 bool VisitSwitchStmt(SwitchStmt *S);
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000295 bool VisitCaseStmt(CaseStmt *S);
Douglas Gregor263b47b2010-01-25 16:12:32 +0000296 bool VisitWhileStmt(WhileStmt *S);
297 bool VisitForStmt(ForStmt *S);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000298
Douglas Gregor336fd812010-01-23 00:40:08 +0000299 // Expression visitors
Douglas Gregor8947a752010-09-02 20:35:02 +0000300 bool VisitDeclRefExpr(DeclRefExpr *E);
Douglas Gregor6cd24e22010-07-29 00:26:18 +0000301 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000302 bool VisitBlockExpr(BlockExpr *B);
Ted Kremenek04c450c2010-11-08 21:14:15 +0000303 bool VisitBinaryOperator(BinaryOperator *B);
Douglas Gregor336fd812010-01-23 00:40:08 +0000304 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000305 bool VisitExplicitCastExpr(ExplicitCastExpr *E);
Douglas Gregorc2350e52010-03-08 16:40:19 +0000306 bool VisitObjCMessageExpr(ObjCMessageExpr *E);
Douglas Gregor81d34662010-04-20 15:39:42 +0000307 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000308 bool VisitOffsetOfExpr(OffsetOfExpr *E);
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000309 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
Douglas Gregorfbb4c982010-09-02 21:07:44 +0000310 bool VisitMemberExpr(MemberExpr *E);
Douglas Gregor36897b02010-09-10 00:22:18 +0000311 bool VisitAddrLabelExpr(AddrLabelExpr *E);
Douglas Gregor648220e2010-08-10 15:02:34 +0000312 bool VisitTypesCompatibleExpr(TypesCompatibleExpr *E);
313 bool VisitVAArgExpr(VAArgExpr *E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +0000314 bool VisitInitListExpr(InitListExpr *E);
315 bool VisitDesignatedInitExpr(DesignatedInitExpr *E);
Douglas Gregor94802292010-09-02 21:20:16 +0000316 bool VisitCXXTypeidExpr(CXXTypeidExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000317 bool VisitCXXUuidofExpr(CXXUuidofExpr *E);
Douglas Gregorda135b12010-09-02 21:38:13 +0000318 bool VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { return false; }
Douglas Gregorab6677e2010-09-08 00:15:04 +0000319 bool VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
320 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Douglas Gregor1bb2a932010-09-07 21:49:58 +0000321 bool VisitCXXNewExpr(CXXNewExpr *E);
Douglas Gregor6f7198f2010-09-02 22:09:03 +0000322 bool VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
Douglas Gregor3d37c0a2010-09-09 16:14:44 +0000323 bool VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E);
Douglas Gregor1f7b5902010-09-02 22:29:21 +0000324 bool VisitOverloadExpr(OverloadExpr *E);
Douglas Gregorbfebed22010-09-03 17:24:10 +0000325 bool VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
Douglas Gregorab6677e2010-09-08 00:15:04 +0000326 bool VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
Douglas Gregor25d63622010-09-03 17:35:34 +0000327 bool VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
Douglas Gregoraaa80b22010-09-03 18:01:25 +0000328 bool VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
Steve Naroff89922f82009-08-31 00:59:03 +0000329};
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000330
Ted Kremenekab188932010-01-05 19:32:54 +0000331} // end anonymous namespace
Benjamin Kramer5e4bc592009-10-18 16:11:04 +0000332
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000333static SourceRange getRawCursorExtent(CXCursor C);
334
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000335RangeComparisonResult CursorVisitor::CompareRegionOfInterest(SourceRange R) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000336 return RangeCompare(TU->getSourceManager(), R, RegionOfInterest);
337}
338
Douglas Gregorb1373d02010-01-20 20:59:29 +0000339/// \brief Visit the given cursor and, if requested by the visitor,
340/// its children.
341///
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000342/// \param Cursor the cursor to visit.
343///
344/// \param CheckRegionOfInterest if true, then the caller already checked that
345/// this cursor is within the region of interest.
346///
Douglas Gregorb1373d02010-01-20 20:59:29 +0000347/// \returns true if the visitation should be aborted, false if it
348/// should continue.
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000349bool CursorVisitor::Visit(CXCursor Cursor, bool CheckedRegionOfInterest) {
Douglas Gregorb1373d02010-01-20 20:59:29 +0000350 if (clang_isInvalid(Cursor.kind))
351 return false;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000352
Douglas Gregorb1373d02010-01-20 20:59:29 +0000353 if (clang_isDeclaration(Cursor.kind)) {
354 Decl *D = getCursorDecl(Cursor);
355 assert(D && "Invalid declaration cursor");
356 if (D->getPCHLevel() > MaxPCHLevel)
357 return false;
358
359 if (D->isImplicit())
360 return false;
361 }
362
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000363 // If we have a range of interest, and this cursor doesn't intersect with it,
364 // we're done.
365 if (RegionOfInterest.isValid() && !CheckedRegionOfInterest) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +0000366 SourceRange Range = getRawCursorExtent(Cursor);
Daniel Dunbarf408f322010-02-14 08:32:05 +0000367 if (Range.isInvalid() || CompareRegionOfInterest(Range))
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000368 return false;
369 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000370
Douglas Gregorb1373d02010-01-20 20:59:29 +0000371 switch (Visitor(Cursor, Parent, ClientData)) {
372 case CXChildVisit_Break:
373 return true;
374
375 case CXChildVisit_Continue:
376 return false;
377
378 case CXChildVisit_Recurse:
379 return VisitChildren(Cursor);
380 }
381
Douglas Gregorfd643772010-01-25 16:45:46 +0000382 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000383}
384
Douglas Gregor788f5a12010-03-20 00:41:21 +0000385std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
386CursorVisitor::getPreprocessedEntities() {
387 PreprocessingRecord &PPRec
388 = *TU->getPreprocessor().getPreprocessingRecord();
389
390 bool OnlyLocalDecls
391 = !TU->isMainFileAST() && TU->getOnlyLocalDecls();
392
393 // There is no region of interest; we have to walk everything.
394 if (RegionOfInterest.isInvalid())
395 return std::make_pair(PPRec.begin(OnlyLocalDecls),
396 PPRec.end(OnlyLocalDecls));
397
398 // Find the file in which the region of interest lands.
399 SourceManager &SM = TU->getSourceManager();
400 std::pair<FileID, unsigned> Begin
401 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getBegin());
402 std::pair<FileID, unsigned> End
403 = SM.getDecomposedInstantiationLoc(RegionOfInterest.getEnd());
404
405 // The region of interest spans files; we have to walk everything.
406 if (Begin.first != End.first)
407 return std::make_pair(PPRec.begin(OnlyLocalDecls),
408 PPRec.end(OnlyLocalDecls));
409
410 ASTUnit::PreprocessedEntitiesByFileMap &ByFileMap
411 = TU->getPreprocessedEntitiesByFile();
412 if (ByFileMap.empty()) {
413 // Build the mapping from files to sets of preprocessed entities.
414 for (PreprocessingRecord::iterator E = PPRec.begin(OnlyLocalDecls),
415 EEnd = PPRec.end(OnlyLocalDecls);
416 E != EEnd; ++E) {
417 std::pair<FileID, unsigned> P
418 = SM.getDecomposedInstantiationLoc((*E)->getSourceRange().getBegin());
419 ByFileMap[P.first].push_back(*E);
420 }
421 }
422
423 return std::make_pair(ByFileMap[Begin.first].begin(),
424 ByFileMap[Begin.first].end());
425}
426
Douglas Gregorb1373d02010-01-20 20:59:29 +0000427/// \brief Visit the children of the given cursor.
428///
429/// \returns true if the visitation should be aborted, false if it
430/// should continue.
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000431bool CursorVisitor::VisitChildren(CXCursor Cursor) {
Douglas Gregora59e3902010-01-21 23:27:09 +0000432 if (clang_isReference(Cursor.kind)) {
433 // By definition, references have no children.
434 return false;
435 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000436
437 // Set the Parent field to Cursor, then back to its old value once we're
Douglas Gregorb1373d02010-01-20 20:59:29 +0000438 // done.
Ted Kremenek0f91f6a2010-05-13 00:25:00 +0000439 SetParentRAII SetParent(Parent, StmtParent, Cursor);
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000440
Douglas Gregorb1373d02010-01-20 20:59:29 +0000441 if (clang_isDeclaration(Cursor.kind)) {
442 Decl *D = getCursorDecl(Cursor);
443 assert(D && "Invalid declaration cursor");
Ted Kremenek539311e2010-02-18 18:47:01 +0000444 return VisitAttributes(D) || Visit(D);
Douglas Gregorb1373d02010-01-20 20:59:29 +0000445 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000446
Douglas Gregora59e3902010-01-21 23:27:09 +0000447 if (clang_isStatement(Cursor.kind))
448 return Visit(getCursorStmt(Cursor));
449 if (clang_isExpression(Cursor.kind))
450 return Visit(getCursorExpr(Cursor));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000451
Douglas Gregorb1373d02010-01-20 20:59:29 +0000452 if (clang_isTranslationUnit(Cursor.kind)) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000453 ASTUnit *CXXUnit = getCursorASTUnit(Cursor);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000454 if (!CXXUnit->isMainFileAST() && CXXUnit->getOnlyLocalDecls() &&
455 RegionOfInterest.isInvalid()) {
Douglas Gregoreb8837b2010-08-03 19:06:41 +0000456 for (ASTUnit::top_level_iterator TL = CXXUnit->top_level_begin(),
457 TLEnd = CXXUnit->top_level_end();
458 TL != TLEnd; ++TL) {
459 if (Visit(MakeCXCursor(*TL, CXXUnit), true))
Douglas Gregor7b691f332010-01-20 21:13:59 +0000460 return true;
461 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000462 } else if (VisitDeclContext(
463 CXXUnit->getASTContext().getTranslationUnitDecl()))
464 return true;
Bob Wilson3178cb62010-03-19 03:57:57 +0000465
Douglas Gregor0396f462010-03-19 05:22:59 +0000466 // Walk the preprocessing record.
Daniel Dunbar8de30ff2010-03-20 01:11:56 +0000467 if (CXXUnit->getPreprocessor().getPreprocessingRecord()) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000468 // FIXME: Once we have the ability to deserialize a preprocessing record,
469 // do so.
Douglas Gregor788f5a12010-03-20 00:41:21 +0000470 PreprocessingRecord::iterator E, EEnd;
471 for (llvm::tie(E, EEnd) = getPreprocessedEntities(); E != EEnd; ++E) {
Douglas Gregor0396f462010-03-19 05:22:59 +0000472 if (MacroInstantiation *MI = dyn_cast<MacroInstantiation>(*E)) {
473 if (Visit(MakeMacroInstantiationCursor(MI, CXXUnit)))
474 return true;
Douglas Gregor788f5a12010-03-20 00:41:21 +0000475
Douglas Gregor0396f462010-03-19 05:22:59 +0000476 continue;
477 }
478
479 if (MacroDefinition *MD = dyn_cast<MacroDefinition>(*E)) {
480 if (Visit(MakeMacroDefinitionCursor(MD, CXXUnit)))
481 return true;
482
483 continue;
484 }
Douglas Gregorecdcb882010-10-20 22:00:55 +0000485
486 if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
487 if (Visit(MakeInclusionDirectiveCursor(ID, CXXUnit)))
488 return true;
489
490 continue;
491 }
Douglas Gregor0396f462010-03-19 05:22:59 +0000492 }
493 }
Douglas Gregor7b691f332010-01-20 21:13:59 +0000494 return false;
Douglas Gregorb1373d02010-01-20 20:59:29 +0000495 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000496
Douglas Gregorb1373d02010-01-20 20:59:29 +0000497 // Nothing to visit at the moment.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000498 return false;
499}
500
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000501bool CursorVisitor::VisitBlockDecl(BlockDecl *B) {
John McCallfc929202010-06-04 22:33:30 +0000502 if (Visit(B->getSignatureAsWritten()->getTypeLoc()))
503 return true;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000504
Ted Kremenek664cffd2010-07-22 11:30:19 +0000505 if (Stmt *Body = B->getBody())
506 return Visit(MakeCXCursor(Body, StmtParent, TU));
507
508 return false;
Ted Kremenek1ee6cad2010-04-11 21:47:37 +0000509}
510
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000511llvm::Optional<bool> CursorVisitor::shouldVisitCursor(CXCursor Cursor) {
512 if (RegionOfInterest.isValid()) {
513 SourceRange Range = getRawCursorExtent(Cursor);
514 if (Range.isInvalid())
515 return llvm::Optional<bool>();
Ted Kremenek09dfa372010-02-18 05:46:33 +0000516
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000517 switch (CompareRegionOfInterest(Range)) {
518 case RangeBefore:
519 // This declaration comes before the region of interest; skip it.
520 return llvm::Optional<bool>();
521
522 case RangeAfter:
523 // This declaration comes after the region of interest; we're done.
524 return false;
525
526 case RangeOverlap:
527 // This declaration overlaps the region of interest; visit it.
528 break;
529 }
530 }
531 return true;
532}
533
534bool CursorVisitor::VisitDeclContext(DeclContext *DC) {
535 DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
536
537 // FIXME: Eventually remove. This part of a hack to support proper
538 // iteration over all Decls contained lexically within an ObjC container.
539 SaveAndRestore<DeclContext::decl_iterator*> DI_saved(DI_current, &I);
540 SaveAndRestore<DeclContext::decl_iterator> DE_saved(DE_current, E);
541
542 for ( ; I != E; ++I) {
Ted Kremenek23173d72010-05-18 21:09:07 +0000543 Decl *D = *I;
544 if (D->getLexicalDeclContext() != DC)
545 continue;
Ted Kremenek23173d72010-05-18 21:09:07 +0000546 CXCursor Cursor = MakeCXCursor(D, TU);
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000547 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
548 if (!V.hasValue())
549 continue;
550 if (!V.getValue())
551 return false;
Daniel Dunbard52864b2010-02-14 10:02:57 +0000552 if (Visit(Cursor, true))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000553 return true;
554 }
Douglas Gregorb1373d02010-01-20 20:59:29 +0000555 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000556}
557
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000558bool CursorVisitor::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
559 llvm_unreachable("Translation units are visited directly by Visit()");
560 return false;
561}
562
563bool CursorVisitor::VisitTypedefDecl(TypedefDecl *D) {
564 if (TypeSourceInfo *TSInfo = D->getTypeSourceInfo())
565 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000566
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000567 return false;
568}
569
570bool CursorVisitor::VisitTagDecl(TagDecl *D) {
571 return VisitDeclContext(D);
572}
573
Douglas Gregor0ab1e9f2010-09-01 17:32:36 +0000574bool CursorVisitor::VisitClassTemplateSpecializationDecl(
575 ClassTemplateSpecializationDecl *D) {
576 bool ShouldVisitBody = false;
577 switch (D->getSpecializationKind()) {
578 case TSK_Undeclared:
579 case TSK_ImplicitInstantiation:
580 // Nothing to visit
581 return false;
582
583 case TSK_ExplicitInstantiationDeclaration:
584 case TSK_ExplicitInstantiationDefinition:
585 break;
586
587 case TSK_ExplicitSpecialization:
588 ShouldVisitBody = true;
589 break;
590 }
591
592 // Visit the template arguments used in the specialization.
593 if (TypeSourceInfo *SpecType = D->getTypeAsWritten()) {
594 TypeLoc TL = SpecType->getTypeLoc();
595 if (TemplateSpecializationTypeLoc *TSTLoc
596 = dyn_cast<TemplateSpecializationTypeLoc>(&TL)) {
597 for (unsigned I = 0, N = TSTLoc->getNumArgs(); I != N; ++I)
598 if (VisitTemplateArgumentLoc(TSTLoc->getArgLoc(I)))
599 return true;
600 }
601 }
602
603 if (ShouldVisitBody && VisitCXXRecordDecl(D))
604 return true;
605
606 return false;
607}
608
Douglas Gregor74dbe642010-08-31 19:31:58 +0000609bool CursorVisitor::VisitClassTemplatePartialSpecializationDecl(
610 ClassTemplatePartialSpecializationDecl *D) {
611 // FIXME: Visit the "outer" template parameter lists on the TagDecl
612 // before visiting these template parameters.
613 if (VisitTemplateParameters(D->getTemplateParameters()))
614 return true;
615
616 // Visit the partial specialization arguments.
617 const TemplateArgumentLoc *TemplateArgs = D->getTemplateArgsAsWritten();
618 for (unsigned I = 0, N = D->getNumTemplateArgsAsWritten(); I != N; ++I)
619 if (VisitTemplateArgumentLoc(TemplateArgs[I]))
620 return true;
621
622 return VisitCXXRecordDecl(D);
623}
624
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000625bool CursorVisitor::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
Douglas Gregor84b51d72010-09-01 20:16:53 +0000626 // Visit the default argument.
627 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
628 if (TypeSourceInfo *DefArg = D->getDefaultArgumentInfo())
629 if (Visit(DefArg->getTypeLoc()))
630 return true;
631
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000632 return false;
633}
634
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000635bool CursorVisitor::VisitEnumConstantDecl(EnumConstantDecl *D) {
636 if (Expr *Init = D->getInitExpr())
637 return Visit(MakeCXCursor(Init, StmtParent, TU));
638 return false;
639}
640
Douglas Gregor7d0d40e2010-01-21 16:28:34 +0000641bool CursorVisitor::VisitDeclaratorDecl(DeclaratorDecl *DD) {
642 if (TypeSourceInfo *TSInfo = DD->getTypeSourceInfo())
643 if (Visit(TSInfo->getTypeLoc()))
644 return true;
645
646 return false;
647}
648
Douglas Gregora67e03f2010-09-09 21:42:20 +0000649/// \brief Compare two base or member initializers based on their source order.
650static int CompareCXXBaseOrMemberInitializers(const void* Xp, const void *Yp) {
651 CXXBaseOrMemberInitializer const * const *X
652 = static_cast<CXXBaseOrMemberInitializer const * const *>(Xp);
653 CXXBaseOrMemberInitializer const * const *Y
654 = static_cast<CXXBaseOrMemberInitializer const * const *>(Yp);
655
656 if ((*X)->getSourceOrder() < (*Y)->getSourceOrder())
657 return -1;
658 else if ((*X)->getSourceOrder() > (*Y)->getSourceOrder())
659 return 1;
660 else
661 return 0;
662}
663
Douglas Gregorb1373d02010-01-20 20:59:29 +0000664bool CursorVisitor::VisitFunctionDecl(FunctionDecl *ND) {
Douglas Gregor01829d32010-08-31 14:41:23 +0000665 if (TypeSourceInfo *TSInfo = ND->getTypeSourceInfo()) {
666 // Visit the function declaration's syntactic components in the order
667 // written. This requires a bit of work.
668 TypeLoc TL = TSInfo->getTypeLoc();
669 FunctionTypeLoc *FTL = dyn_cast<FunctionTypeLoc>(&TL);
670
671 // If we have a function declared directly (without the use of a typedef),
672 // visit just the return type. Otherwise, just visit the function's type
673 // now.
674 if ((FTL && !isa<CXXConversionDecl>(ND) && Visit(FTL->getResultLoc())) ||
675 (!FTL && Visit(TL)))
676 return true;
677
Douglas Gregorc5ade2e2010-09-02 17:35:32 +0000678 // Visit the nested-name-specifier, if present.
679 if (NestedNameSpecifier *Qualifier = ND->getQualifier())
680 if (VisitNestedNameSpecifier(Qualifier, ND->getQualifierRange()))
681 return true;
Douglas Gregor01829d32010-08-31 14:41:23 +0000682
683 // Visit the declaration name.
684 if (VisitDeclarationNameInfo(ND->getNameInfo()))
685 return true;
686
687 // FIXME: Visit explicitly-specified template arguments!
688
689 // Visit the function parameters, if we have a function type.
690 if (FTL && VisitFunctionTypeLoc(*FTL, true))
691 return true;
692
693 // FIXME: Attributes?
694 }
695
Douglas Gregora67e03f2010-09-09 21:42:20 +0000696 if (ND->isThisDeclarationADefinition()) {
697 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(ND)) {
698 // Find the initializers that were written in the source.
699 llvm::SmallVector<CXXBaseOrMemberInitializer *, 4> WrittenInits;
700 for (CXXConstructorDecl::init_iterator I = Constructor->init_begin(),
701 IEnd = Constructor->init_end();
702 I != IEnd; ++I) {
703 if (!(*I)->isWritten())
704 continue;
705
706 WrittenInits.push_back(*I);
707 }
708
709 // Sort the initializers in source order
710 llvm::array_pod_sort(WrittenInits.begin(), WrittenInits.end(),
711 &CompareCXXBaseOrMemberInitializers);
712
713 // Visit the initializers in source order
714 for (unsigned I = 0, N = WrittenInits.size(); I != N; ++I) {
715 CXXBaseOrMemberInitializer *Init = WrittenInits[I];
716 if (Init->isMemberInitializer()) {
717 if (Visit(MakeCursorMemberRef(Init->getMember(),
718 Init->getMemberLocation(), TU)))
719 return true;
720 } else if (TypeSourceInfo *BaseInfo = Init->getBaseClassInfo()) {
721 if (Visit(BaseInfo->getTypeLoc()))
722 return true;
723 }
724
725 // Visit the initializer value.
726 if (Expr *Initializer = Init->getInit())
727 if (Visit(MakeCXCursor(Initializer, ND, TU)))
728 return true;
729 }
730 }
731
732 if (Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
733 return true;
734 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000735
Douglas Gregorb1373d02010-01-20 20:59:29 +0000736 return false;
737}
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000738
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000739bool CursorVisitor::VisitFieldDecl(FieldDecl *D) {
740 if (VisitDeclaratorDecl(D))
741 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000742
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000743 if (Expr *BitWidth = D->getBitWidth())
744 return Visit(MakeCXCursor(BitWidth, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000745
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000746 return false;
747}
748
749bool CursorVisitor::VisitVarDecl(VarDecl *D) {
750 if (VisitDeclaratorDecl(D))
751 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000752
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000753 if (Expr *Init = D->getInit())
754 return Visit(MakeCXCursor(Init, StmtParent, TU));
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000755
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000756 return false;
757}
758
Douglas Gregor84b51d72010-09-01 20:16:53 +0000759bool CursorVisitor::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
760 if (VisitDeclaratorDecl(D))
761 return true;
762
763 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited())
764 if (Expr *DefArg = D->getDefaultArgument())
765 return Visit(MakeCXCursor(DefArg, StmtParent, TU));
766
767 return false;
768}
769
Douglas Gregorfe72e9c2010-08-31 17:01:39 +0000770bool CursorVisitor::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
771 // FIXME: Visit the "outer" template parameter lists on the FunctionDecl
772 // before visiting these template parameters.
773 if (VisitTemplateParameters(D->getTemplateParameters()))
774 return true;
775
776 return VisitFunctionDecl(D->getTemplatedDecl());
777}
778
Douglas Gregor39d6f072010-08-31 19:02:00 +0000779bool CursorVisitor::VisitClassTemplateDecl(ClassTemplateDecl *D) {
780 // FIXME: Visit the "outer" template parameter lists on the TagDecl
781 // before visiting these template parameters.
782 if (VisitTemplateParameters(D->getTemplateParameters()))
783 return true;
784
785 return VisitCXXRecordDecl(D->getTemplatedDecl());
786}
787
Douglas Gregor84b51d72010-09-01 20:16:53 +0000788bool CursorVisitor::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
789 if (VisitTemplateParameters(D->getTemplateParameters()))
790 return true;
791
792 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited() &&
793 VisitTemplateArgumentLoc(D->getDefaultArgument()))
794 return true;
795
796 return false;
797}
798
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000799bool CursorVisitor::VisitObjCMethodDecl(ObjCMethodDecl *ND) {
Douglas Gregor4bc1cb62010-03-08 14:59:44 +0000800 if (TypeSourceInfo *TSInfo = ND->getResultTypeSourceInfo())
801 if (Visit(TSInfo->getTypeLoc()))
802 return true;
803
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000804 for (ObjCMethodDecl::param_iterator P = ND->param_begin(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000805 PEnd = ND->param_end();
806 P != PEnd; ++P) {
807 if (Visit(MakeCXCursor(*P, TU)))
808 return true;
809 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000810
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000811 if (ND->isThisDeclarationADefinition() &&
812 Visit(MakeCXCursor(ND->getBody(), StmtParent, TU)))
813 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000814
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000815 return false;
816}
817
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000818namespace {
819 struct ContainerDeclsSort {
820 SourceManager &SM;
821 ContainerDeclsSort(SourceManager &sm) : SM(sm) {}
822 bool operator()(Decl *A, Decl *B) {
823 SourceLocation L_A = A->getLocStart();
824 SourceLocation L_B = B->getLocStart();
825 assert(L_A.isValid() && L_B.isValid());
826 return SM.isBeforeInTranslationUnit(L_A, L_B);
827 }
828 };
829}
830
Douglas Gregora59e3902010-01-21 23:27:09 +0000831bool CursorVisitor::VisitObjCContainerDecl(ObjCContainerDecl *D) {
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000832 // FIXME: Eventually convert back to just 'VisitDeclContext()'. Essentially
833 // an @implementation can lexically contain Decls that are not properly
834 // nested in the AST. When we identify such cases, we need to retrofit
835 // this nesting here.
836 if (!DI_current)
837 return VisitDeclContext(D);
838
839 // Scan the Decls that immediately come after the container
840 // in the current DeclContext. If any fall within the
841 // container's lexical region, stash them into a vector
842 // for later processing.
843 llvm::SmallVector<Decl *, 24> DeclsInContainer;
844 SourceLocation EndLoc = D->getSourceRange().getEnd();
845 SourceManager &SM = TU->getSourceManager();
846 if (EndLoc.isValid()) {
847 DeclContext::decl_iterator next = *DI_current;
848 while (++next != DE_current) {
849 Decl *D_next = *next;
850 if (!D_next)
851 break;
852 SourceLocation L = D_next->getLocStart();
853 if (!L.isValid())
854 break;
855 if (SM.isBeforeInTranslationUnit(L, EndLoc)) {
856 *DI_current = next;
857 DeclsInContainer.push_back(D_next);
858 continue;
859 }
860 break;
861 }
862 }
863
864 // The common case.
865 if (DeclsInContainer.empty())
866 return VisitDeclContext(D);
867
868 // Get all the Decls in the DeclContext, and sort them with the
869 // additional ones we've collected. Then visit them.
870 for (DeclContext::decl_iterator I = D->decls_begin(), E = D->decls_end();
871 I!=E; ++I) {
872 Decl *subDecl = *I;
Ted Kremenek0582c892010-11-02 23:17:51 +0000873 if (!subDecl || subDecl->getLexicalDeclContext() != D ||
874 subDecl->getLocStart().isInvalid())
Ted Kremenekd8c370c2010-11-02 23:10:24 +0000875 continue;
876 DeclsInContainer.push_back(subDecl);
877 }
878
879 // Now sort the Decls so that they appear in lexical order.
880 std::sort(DeclsInContainer.begin(), DeclsInContainer.end(),
881 ContainerDeclsSort(SM));
882
883 // Now visit the decls.
884 for (llvm::SmallVectorImpl<Decl*>::iterator I = DeclsInContainer.begin(),
885 E = DeclsInContainer.end(); I != E; ++I) {
886 CXCursor Cursor = MakeCXCursor(*I, TU);
887 const llvm::Optional<bool> &V = shouldVisitCursor(Cursor);
888 if (!V.hasValue())
889 continue;
890 if (!V.getValue())
891 return false;
892 if (Visit(Cursor, true))
893 return true;
894 }
895 return false;
Douglas Gregora59e3902010-01-21 23:27:09 +0000896}
897
Douglas Gregorb1373d02010-01-20 20:59:29 +0000898bool CursorVisitor::VisitObjCCategoryDecl(ObjCCategoryDecl *ND) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000899 if (Visit(MakeCursorObjCClassRef(ND->getClassInterface(), ND->getLocation(),
900 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000901 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000902
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000903 ObjCCategoryDecl::protocol_loc_iterator PL = ND->protocol_loc_begin();
904 for (ObjCCategoryDecl::protocol_iterator I = ND->protocol_begin(),
905 E = ND->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000906 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000907 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000908
Douglas Gregora59e3902010-01-21 23:27:09 +0000909 return VisitObjCContainerDecl(ND);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000910}
911
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000912bool CursorVisitor::VisitObjCProtocolDecl(ObjCProtocolDecl *PID) {
913 ObjCProtocolDecl::protocol_loc_iterator PL = PID->protocol_loc_begin();
914 for (ObjCProtocolDecl::protocol_iterator I = PID->protocol_begin(),
915 E = PID->protocol_end(); I != E; ++I, ++PL)
916 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
917 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000918
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000919 return VisitObjCContainerDecl(PID);
920}
921
Ted Kremenek23173d72010-05-18 21:09:07 +0000922bool CursorVisitor::VisitObjCPropertyDecl(ObjCPropertyDecl *PD) {
Douglas Gregor83cb9422010-09-09 17:09:21 +0000923 if (PD->getTypeSourceInfo() && Visit(PD->getTypeSourceInfo()->getTypeLoc()))
John McCallfc929202010-06-04 22:33:30 +0000924 return true;
925
Ted Kremenek23173d72010-05-18 21:09:07 +0000926 // FIXME: This implements a workaround with @property declarations also being
927 // installed in the DeclContext for the @interface. Eventually this code
928 // should be removed.
929 ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(PD->getDeclContext());
930 if (!CDecl || !CDecl->IsClassExtension())
931 return false;
932
933 ObjCInterfaceDecl *ID = CDecl->getClassInterface();
934 if (!ID)
935 return false;
936
937 IdentifierInfo *PropertyId = PD->getIdentifier();
938 ObjCPropertyDecl *prevDecl =
939 ObjCPropertyDecl::findPropertyDecl(cast<DeclContext>(ID), PropertyId);
940
941 if (!prevDecl)
942 return false;
943
944 // Visit synthesized methods since they will be skipped when visiting
945 // the @interface.
946 if (ObjCMethodDecl *MD = prevDecl->getGetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000947 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000948 if (Visit(MakeCXCursor(MD, TU)))
949 return true;
950
951 if (ObjCMethodDecl *MD = prevDecl->getSetterMethodDecl())
Ted Kremeneka054fb42010-09-21 20:52:59 +0000952 if (MD->isSynthesized() && MD->getLexicalDeclContext() == CDecl)
Ted Kremenek23173d72010-05-18 21:09:07 +0000953 if (Visit(MakeCXCursor(MD, TU)))
954 return true;
955
956 return false;
957}
958
Douglas Gregorb1373d02010-01-20 20:59:29 +0000959bool CursorVisitor::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000960 // Issue callbacks for super class.
Douglas Gregorb1373d02010-01-20 20:59:29 +0000961 if (D->getSuperClass() &&
962 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000963 D->getSuperClassLoc(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000964 TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000965 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000966
Douglas Gregor78db0cd2010-01-16 15:44:18 +0000967 ObjCInterfaceDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
968 for (ObjCInterfaceDecl::protocol_iterator I = D->protocol_begin(),
969 E = D->protocol_end(); I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +0000970 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +0000971 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000972
Douglas Gregora59e3902010-01-21 23:27:09 +0000973 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000974}
975
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000976bool CursorVisitor::VisitObjCImplDecl(ObjCImplDecl *D) {
977 return VisitObjCContainerDecl(D);
Ted Kremenekdd6bcc52010-01-13 00:22:49 +0000978}
979
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000980bool CursorVisitor::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
Ted Kremenekebfa3392010-03-19 20:39:03 +0000981 // 'ID' could be null when dealing with invalid code.
982 if (ObjCInterfaceDecl *ID = D->getClassInterface())
983 if (Visit(MakeCursorObjCClassRef(ID, D->getLocation(), TU)))
984 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000985
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000986 return VisitObjCImplDecl(D);
987}
988
989bool CursorVisitor::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
990#if 0
991 // Issue callbacks for super class.
992 // FIXME: No source location information!
993 if (D->getSuperClass() &&
994 Visit(MakeCursorObjCSuperClassRef(D->getSuperClass(),
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000995 D->getSuperClassLoc(),
Douglas Gregor1ef2fc12010-01-22 00:50:27 +0000996 TU)))
997 return true;
998#endif
Ted Kremenekf0e23e82010-02-17 00:41:40 +0000999
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001000 return VisitObjCImplDecl(D);
1001}
1002
1003bool CursorVisitor::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
1004 ObjCForwardProtocolDecl::protocol_loc_iterator PL = D->protocol_loc_begin();
1005 for (ObjCForwardProtocolDecl::protocol_iterator I = D->protocol_begin(),
1006 E = D->protocol_end();
1007 I != E; ++I, ++PL)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00001008 if (Visit(MakeCursorObjCProtocolRef(*I, *PL, TU)))
Douglas Gregorb1373d02010-01-20 20:59:29 +00001009 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001010
1011 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001012}
1013
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001014bool CursorVisitor::VisitObjCClassDecl(ObjCClassDecl *D) {
1015 for (ObjCClassDecl::iterator C = D->begin(), CEnd = D->end(); C != CEnd; ++C)
1016 if (Visit(MakeCursorObjCClassRef(C->getInterface(), C->getLocation(), TU)))
1017 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001018
Douglas Gregor1ef2fc12010-01-22 00:50:27 +00001019 return false;
Ted Kremenekdd6bcc52010-01-13 00:22:49 +00001020}
1021
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00001022bool CursorVisitor::VisitNamespaceDecl(NamespaceDecl *D) {
1023 return VisitDeclContext(D);
1024}
1025
Douglas Gregor69319002010-08-31 23:48:11 +00001026bool CursorVisitor::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001027 // Visit nested-name-specifier.
1028 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1029 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1030 return true;
Douglas Gregor69319002010-08-31 23:48:11 +00001031
1032 return Visit(MakeCursorNamespaceRef(D->getAliasedNamespace(),
1033 D->getTargetNameLoc(), TU));
1034}
1035
Douglas Gregor7e242562010-09-01 19:52:22 +00001036bool CursorVisitor::VisitUsingDecl(UsingDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001037 // Visit nested-name-specifier.
1038 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameDecl())
1039 if (VisitNestedNameSpecifier(Qualifier, D->getNestedNameRange()))
1040 return true;
Douglas Gregor7e242562010-09-01 19:52:22 +00001041
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001042 if (Visit(MakeCursorOverloadedDeclRef(D, D->getLocation(), TU)))
1043 return true;
1044
Douglas Gregor7e242562010-09-01 19:52:22 +00001045 return VisitDeclarationNameInfo(D->getNameInfo());
1046}
1047
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001048bool CursorVisitor::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001049 // Visit nested-name-specifier.
1050 if (NestedNameSpecifier *Qualifier = D->getQualifier())
1051 if (VisitNestedNameSpecifier(Qualifier, D->getQualifierRange()))
1052 return true;
Douglas Gregor0a35bce2010-09-01 03:07:18 +00001053
1054 return Visit(MakeCursorNamespaceRef(D->getNominatedNamespaceAsWritten(),
1055 D->getIdentLocation(), TU));
1056}
1057
Douglas Gregor7e242562010-09-01 19:52:22 +00001058bool CursorVisitor::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001059 // Visit nested-name-specifier.
1060 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1061 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1062 return true;
1063
Douglas Gregor7e242562010-09-01 19:52:22 +00001064 return VisitDeclarationNameInfo(D->getNameInfo());
1065}
1066
1067bool CursorVisitor::VisitUnresolvedUsingTypenameDecl(
1068 UnresolvedUsingTypenameDecl *D) {
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001069 // Visit nested-name-specifier.
1070 if (NestedNameSpecifier *Qualifier = D->getTargetNestedNameSpecifier())
1071 if (VisitNestedNameSpecifier(Qualifier, D->getTargetNestedNameRange()))
1072 return true;
1073
Douglas Gregor7e242562010-09-01 19:52:22 +00001074 return false;
1075}
1076
Douglas Gregor01829d32010-08-31 14:41:23 +00001077bool CursorVisitor::VisitDeclarationNameInfo(DeclarationNameInfo Name) {
1078 switch (Name.getName().getNameKind()) {
1079 case clang::DeclarationName::Identifier:
1080 case clang::DeclarationName::CXXLiteralOperatorName:
1081 case clang::DeclarationName::CXXOperatorName:
1082 case clang::DeclarationName::CXXUsingDirective:
1083 return false;
1084
1085 case clang::DeclarationName::CXXConstructorName:
1086 case clang::DeclarationName::CXXDestructorName:
1087 case clang::DeclarationName::CXXConversionFunctionName:
1088 if (TypeSourceInfo *TSInfo = Name.getNamedTypeInfo())
1089 return Visit(TSInfo->getTypeLoc());
1090 return false;
1091
1092 case clang::DeclarationName::ObjCZeroArgSelector:
1093 case clang::DeclarationName::ObjCOneArgSelector:
1094 case clang::DeclarationName::ObjCMultiArgSelector:
1095 // FIXME: Per-identifier location info?
1096 return false;
1097 }
1098
1099 return false;
1100}
1101
Douglas Gregorc5ade2e2010-09-02 17:35:32 +00001102bool CursorVisitor::VisitNestedNameSpecifier(NestedNameSpecifier *NNS,
1103 SourceRange Range) {
1104 // FIXME: This whole routine is a hack to work around the lack of proper
1105 // source information in nested-name-specifiers (PR5791). Since we do have
1106 // a beginning source location, we can visit the first component of the
1107 // nested-name-specifier, if it's a single-token component.
1108 if (!NNS)
1109 return false;
1110
1111 // Get the first component in the nested-name-specifier.
1112 while (NestedNameSpecifier *Prefix = NNS->getPrefix())
1113 NNS = Prefix;
1114
1115 switch (NNS->getKind()) {
1116 case NestedNameSpecifier::Namespace:
1117 // FIXME: The token at this source location might actually have been a
1118 // namespace alias, but we don't model that. Lame!
1119 return Visit(MakeCursorNamespaceRef(NNS->getAsNamespace(), Range.getBegin(),
1120 TU));
1121
1122 case NestedNameSpecifier::TypeSpec: {
1123 // If the type has a form where we know that the beginning of the source
1124 // range matches up with a reference cursor. Visit the appropriate reference
1125 // cursor.
1126 Type *T = NNS->getAsType();
1127 if (const TypedefType *Typedef = dyn_cast<TypedefType>(T))
1128 return Visit(MakeCursorTypeRef(Typedef->getDecl(), Range.getBegin(), TU));
1129 if (const TagType *Tag = dyn_cast<TagType>(T))
1130 return Visit(MakeCursorTypeRef(Tag->getDecl(), Range.getBegin(), TU));
1131 if (const TemplateSpecializationType *TST
1132 = dyn_cast<TemplateSpecializationType>(T))
1133 return VisitTemplateName(TST->getTemplateName(), Range.getBegin());
1134 break;
1135 }
1136
1137 case NestedNameSpecifier::TypeSpecWithTemplate:
1138 case NestedNameSpecifier::Global:
1139 case NestedNameSpecifier::Identifier:
1140 break;
1141 }
1142
1143 return false;
1144}
1145
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001146bool CursorVisitor::VisitTemplateParameters(
1147 const TemplateParameterList *Params) {
1148 if (!Params)
1149 return false;
1150
1151 for (TemplateParameterList::const_iterator P = Params->begin(),
1152 PEnd = Params->end();
1153 P != PEnd; ++P) {
1154 if (Visit(MakeCXCursor(*P, TU)))
1155 return true;
1156 }
1157
1158 return false;
1159}
1160
Douglas Gregor0b36e612010-08-31 20:37:03 +00001161bool CursorVisitor::VisitTemplateName(TemplateName Name, SourceLocation Loc) {
1162 switch (Name.getKind()) {
1163 case TemplateName::Template:
1164 return Visit(MakeCursorTemplateRef(Name.getAsTemplateDecl(), Loc, TU));
1165
1166 case TemplateName::OverloadedTemplate:
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001167 // Visit the overloaded template set.
1168 if (Visit(MakeCursorOverloadedDeclRef(Name, Loc, TU)))
1169 return true;
1170
Douglas Gregor0b36e612010-08-31 20:37:03 +00001171 return false;
1172
1173 case TemplateName::DependentTemplate:
1174 // FIXME: Visit nested-name-specifier.
1175 return false;
1176
1177 case TemplateName::QualifiedTemplate:
1178 // FIXME: Visit nested-name-specifier.
1179 return Visit(MakeCursorTemplateRef(
1180 Name.getAsQualifiedTemplateName()->getDecl(),
1181 Loc, TU));
1182 }
1183
1184 return false;
1185}
1186
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001187bool CursorVisitor::VisitTemplateArgumentLoc(const TemplateArgumentLoc &TAL) {
1188 switch (TAL.getArgument().getKind()) {
1189 case TemplateArgument::Null:
1190 case TemplateArgument::Integral:
1191 return false;
1192
1193 case TemplateArgument::Pack:
1194 // FIXME: Implement when variadic templates come along.
1195 return false;
1196
1197 case TemplateArgument::Type:
1198 if (TypeSourceInfo *TSInfo = TAL.getTypeSourceInfo())
1199 return Visit(TSInfo->getTypeLoc());
1200 return false;
1201
1202 case TemplateArgument::Declaration:
1203 if (Expr *E = TAL.getSourceDeclExpression())
1204 return Visit(MakeCXCursor(E, StmtParent, TU));
1205 return false;
1206
1207 case TemplateArgument::Expression:
1208 if (Expr *E = TAL.getSourceExpression())
1209 return Visit(MakeCXCursor(E, StmtParent, TU));
1210 return false;
1211
1212 case TemplateArgument::Template:
Douglas Gregor0b36e612010-08-31 20:37:03 +00001213 return VisitTemplateName(TAL.getArgument().getAsTemplate(),
1214 TAL.getTemplateNameLoc());
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001215 }
1216
1217 return false;
1218}
1219
Ted Kremeneka0536d82010-05-07 01:04:29 +00001220bool CursorVisitor::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1221 return VisitDeclContext(D);
1222}
1223
Douglas Gregor01829d32010-08-31 14:41:23 +00001224bool CursorVisitor::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1225 return Visit(TL.getUnqualifiedLoc());
1226}
1227
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001228bool CursorVisitor::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
1229 ASTContext &Context = TU->getASTContext();
1230
1231 // Some builtin types (such as Objective-C's "id", "sel", and
1232 // "Class") have associated declarations. Create cursors for those.
1233 QualType VisitType;
1234 switch (TL.getType()->getAs<BuiltinType>()->getKind()) {
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001235 case BuiltinType::Void:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001236 case BuiltinType::Bool:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001237 case BuiltinType::Char_U:
1238 case BuiltinType::UChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001239 case BuiltinType::Char16:
1240 case BuiltinType::Char32:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001241 case BuiltinType::UShort:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001242 case BuiltinType::UInt:
1243 case BuiltinType::ULong:
1244 case BuiltinType::ULongLong:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001245 case BuiltinType::UInt128:
1246 case BuiltinType::Char_S:
1247 case BuiltinType::SChar:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001248 case BuiltinType::WChar:
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001249 case BuiltinType::Short:
1250 case BuiltinType::Int:
1251 case BuiltinType::Long:
1252 case BuiltinType::LongLong:
1253 case BuiltinType::Int128:
1254 case BuiltinType::Float:
1255 case BuiltinType::Double:
1256 case BuiltinType::LongDouble:
1257 case BuiltinType::NullPtr:
1258 case BuiltinType::Overload:
1259 case BuiltinType::Dependent:
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001260 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001261
1262 case BuiltinType::UndeducedAuto: // FIXME: Deserves a cursor?
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001263 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001264
Ted Kremenekc4174cc2010-02-18 18:52:18 +00001265 case BuiltinType::ObjCId:
1266 VisitType = Context.getObjCIdType();
1267 break;
Ted Kremenek6b3b5142010-02-18 22:32:43 +00001268
1269 case BuiltinType::ObjCClass:
1270 VisitType = Context.getObjCClassType();
1271 break;
1272
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001273 case BuiltinType::ObjCSel:
1274 VisitType = Context.getObjCSelType();
1275 break;
1276 }
1277
1278 if (!VisitType.isNull()) {
1279 if (const TypedefType *Typedef = VisitType->getAs<TypedefType>())
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001280 return Visit(MakeCursorTypeRef(Typedef->getDecl(), TL.getBuiltinLoc(),
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001281 TU));
1282 }
1283
1284 return false;
1285}
1286
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00001287bool CursorVisitor::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1288 return Visit(MakeCursorTypeRef(TL.getTypedefDecl(), TL.getNameLoc(), TU));
1289}
1290
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001291bool CursorVisitor::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
1292 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1293}
1294
1295bool CursorVisitor::VisitTagTypeLoc(TagTypeLoc TL) {
1296 return Visit(MakeCursorTypeRef(TL.getDecl(), TL.getNameLoc(), TU));
1297}
1298
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001299bool CursorVisitor::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001300 // FIXME: We can't visit the template type parameter, because there's
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001301 // no context information with which we can match up the depth/index in the
1302 // type to the appropriate
1303 return false;
1304}
1305
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001306bool CursorVisitor::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1307 if (Visit(MakeCursorObjCClassRef(TL.getIFaceDecl(), TL.getNameLoc(), TU)))
1308 return true;
1309
John McCallc12c5bb2010-05-15 11:32:37 +00001310 return false;
1311}
1312
1313bool CursorVisitor::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
1314 if (TL.hasBaseTypeAsWritten() && Visit(TL.getBaseLoc()))
1315 return true;
1316
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001317 for (unsigned I = 0, N = TL.getNumProtocols(); I != N; ++I) {
1318 if (Visit(MakeCursorObjCProtocolRef(TL.getProtocol(I), TL.getProtocolLoc(I),
1319 TU)))
1320 return true;
1321 }
1322
1323 return false;
1324}
1325
1326bool CursorVisitor::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
John McCallc12c5bb2010-05-15 11:32:37 +00001327 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001328}
1329
1330bool CursorVisitor::VisitPointerTypeLoc(PointerTypeLoc TL) {
1331 return Visit(TL.getPointeeLoc());
1332}
1333
1334bool CursorVisitor::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1335 return Visit(TL.getPointeeLoc());
1336}
1337
1338bool CursorVisitor::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1339 return Visit(TL.getPointeeLoc());
1340}
1341
1342bool CursorVisitor::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001343 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001344}
1345
1346bool CursorVisitor::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001347 return Visit(TL.getPointeeLoc());
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001348}
1349
Douglas Gregor01829d32010-08-31 14:41:23 +00001350bool CursorVisitor::VisitFunctionTypeLoc(FunctionTypeLoc TL,
1351 bool SkipResultType) {
1352 if (!SkipResultType && Visit(TL.getResultLoc()))
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001353 return true;
1354
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001355 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
Ted Kremenek5dbacb42010-04-07 00:27:13 +00001356 if (Decl *D = TL.getArg(I))
1357 if (Visit(MakeCXCursor(D, TU)))
1358 return true;
Douglas Gregorf20dfbc2010-01-21 17:29:07 +00001359
1360 return false;
1361}
1362
1363bool CursorVisitor::VisitArrayTypeLoc(ArrayTypeLoc TL) {
1364 if (Visit(TL.getElementLoc()))
1365 return true;
1366
1367 if (Expr *Size = TL.getSizeExpr())
1368 return Visit(MakeCXCursor(Size, StmtParent, TU));
1369
1370 return false;
1371}
1372
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001373bool CursorVisitor::VisitTemplateSpecializationTypeLoc(
1374 TemplateSpecializationTypeLoc TL) {
Douglas Gregor0b36e612010-08-31 20:37:03 +00001375 // Visit the template name.
1376 if (VisitTemplateName(TL.getTypePtr()->getTemplateName(),
1377 TL.getTemplateNameLoc()))
1378 return true;
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00001379
1380 // Visit the template arguments.
1381 for (unsigned I = 0, N = TL.getNumArgs(); I != N; ++I)
1382 if (VisitTemplateArgumentLoc(TL.getArgLoc(I)))
1383 return true;
1384
1385 return false;
1386}
1387
Douglas Gregor2332c112010-01-21 20:48:56 +00001388bool CursorVisitor::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
1389 return Visit(MakeCXCursor(TL.getUnderlyingExpr(), StmtParent, TU));
1390}
1391
1392bool CursorVisitor::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
1393 if (TypeSourceInfo *TSInfo = TL.getUnderlyingTInfo())
1394 return Visit(TSInfo->getTypeLoc());
1395
1396 return false;
1397}
1398
Douglas Gregora59e3902010-01-21 23:27:09 +00001399bool CursorVisitor::VisitStmt(Stmt *S) {
1400 for (Stmt::child_iterator Child = S->child_begin(), ChildEnd = S->child_end();
1401 Child != ChildEnd; ++Child) {
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001402 if (Stmt *C = *Child)
1403 if (Visit(MakeCXCursor(C, StmtParent, TU)))
1404 return true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001405 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001406
Douglas Gregora59e3902010-01-21 23:27:09 +00001407 return false;
1408}
1409
Ted Kremenek0f91f6a2010-05-13 00:25:00 +00001410bool CursorVisitor::VisitCaseStmt(CaseStmt *S) {
1411 // Specially handle CaseStmts because they can be nested, e.g.:
1412 //
1413 // case 1:
1414 // case 2:
1415 //
1416 // In this case the second CaseStmt is the child of the first. Walking
1417 // these recursively can blow out the stack.
1418 CXCursor Cursor = MakeCXCursor(S, StmtParent, TU);
1419 while (true) {
1420 // Set the Parent field to Cursor, then back to its old value once we're
1421 // done.
1422 SetParentRAII SetParent(Parent, StmtParent, Cursor);
1423
1424 if (Stmt *LHS = S->getLHS())
1425 if (Visit(MakeCXCursor(LHS, StmtParent, TU)))
1426 return true;
1427 if (Stmt *RHS = S->getRHS())
1428 if (Visit(MakeCXCursor(RHS, StmtParent, TU)))
1429 return true;
1430 if (Stmt *SubStmt = S->getSubStmt()) {
1431 if (!isa<CaseStmt>(SubStmt))
1432 return Visit(MakeCXCursor(SubStmt, StmtParent, TU));
1433
1434 // Specially handle 'CaseStmt' so that we don't blow out the stack.
1435 CaseStmt *CS = cast<CaseStmt>(SubStmt);
1436 Cursor = MakeCXCursor(CS, StmtParent, TU);
1437 if (RegionOfInterest.isValid()) {
1438 SourceRange Range = CS->getSourceRange();
1439 if (Range.isInvalid() || CompareRegionOfInterest(Range))
1440 return false;
1441 }
1442
1443 switch (Visitor(Cursor, Parent, ClientData)) {
1444 case CXChildVisit_Break: return true;
1445 case CXChildVisit_Continue: return false;
1446 case CXChildVisit_Recurse:
1447 // Perform tail-recursion manually.
1448 S = CS;
1449 continue;
1450 }
1451 }
1452 return false;
1453 }
1454}
1455
Douglas Gregora59e3902010-01-21 23:27:09 +00001456bool CursorVisitor::VisitDeclStmt(DeclStmt *S) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001457 bool isFirst = true;
Douglas Gregora59e3902010-01-21 23:27:09 +00001458 for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
1459 D != DEnd; ++D) {
Ted Kremenek007a7c92010-11-01 23:26:51 +00001460 if (*D && Visit(MakeCXCursor(*D, TU, isFirst)))
Douglas Gregora59e3902010-01-21 23:27:09 +00001461 return true;
Ted Kremenek007a7c92010-11-01 23:26:51 +00001462 isFirst = false;
Douglas Gregora59e3902010-01-21 23:27:09 +00001463 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001464
Douglas Gregora59e3902010-01-21 23:27:09 +00001465 return false;
1466}
1467
Douglas Gregor36897b02010-09-10 00:22:18 +00001468bool CursorVisitor::VisitGotoStmt(GotoStmt *S) {
1469 return Visit(MakeCursorLabelRef(S->getLabel(), S->getLabelLoc(), TU));
1470}
1471
Douglas Gregorf5bab412010-01-22 01:00:11 +00001472bool CursorVisitor::VisitIfStmt(IfStmt *S) {
1473 if (VarDecl *Var = S->getConditionVariable()) {
1474 if (Visit(MakeCXCursor(Var, TU)))
1475 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001476 }
1477
Douglas Gregor263b47b2010-01-25 16:12:32 +00001478 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1479 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001480 if (S->getThen() && Visit(MakeCXCursor(S->getThen(), StmtParent, TU)))
1481 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001482 if (S->getElse() && Visit(MakeCXCursor(S->getElse(), StmtParent, TU)))
1483 return true;
1484
1485 return false;
1486}
1487
1488bool CursorVisitor::VisitSwitchStmt(SwitchStmt *S) {
1489 if (VarDecl *Var = S->getConditionVariable()) {
1490 if (Visit(MakeCXCursor(Var, TU)))
1491 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001492 }
1493
Douglas Gregor263b47b2010-01-25 16:12:32 +00001494 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1495 return true;
1496 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1497 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001498
Douglas Gregor263b47b2010-01-25 16:12:32 +00001499 return false;
1500}
1501
1502bool CursorVisitor::VisitWhileStmt(WhileStmt *S) {
1503 if (VarDecl *Var = S->getConditionVariable()) {
1504 if (Visit(MakeCXCursor(Var, TU)))
1505 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001506 }
1507
Douglas Gregor263b47b2010-01-25 16:12:32 +00001508 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1509 return true;
1510 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
Douglas Gregorf5bab412010-01-22 01:00:11 +00001511 return true;
1512
Douglas Gregor263b47b2010-01-25 16:12:32 +00001513 return false;
1514}
1515
1516bool CursorVisitor::VisitForStmt(ForStmt *S) {
1517 if (S->getInit() && Visit(MakeCXCursor(S->getInit(), StmtParent, TU)))
1518 return true;
1519 if (VarDecl *Var = S->getConditionVariable()) {
1520 if (Visit(MakeCXCursor(Var, TU)))
1521 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001522 }
1523
Douglas Gregor263b47b2010-01-25 16:12:32 +00001524 if (S->getCond() && Visit(MakeCXCursor(S->getCond(), StmtParent, TU)))
1525 return true;
1526 if (S->getInc() && Visit(MakeCXCursor(S->getInc(), StmtParent, TU)))
1527 return true;
Douglas Gregorf5bab412010-01-22 01:00:11 +00001528 if (S->getBody() && Visit(MakeCXCursor(S->getBody(), StmtParent, TU)))
1529 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001530
Douglas Gregorf5bab412010-01-22 01:00:11 +00001531 return false;
1532}
1533
Ted Kremenek04c450c2010-11-08 21:14:15 +00001534bool CursorVisitor::VisitBinaryOperator(BinaryOperator *B) {
1535 // We can blow the stack in some cases where we have deeply nested BinaryOperators,
1536 // often involving logical expressions, e.g.: '(x || y) || (y || z) || ...
1537 // To handle this, we visitation of BinaryOperators is data recursive instead of
1538 // directly recursive. This makes the algorithm more complicated, but handles
1539 // arbitrary depths. We should consider making the entire CursorVisitor data
1540 // recursive.
1541 typedef std::pair</* Current expression = */ Expr*, /* Parent = */ CXCursor>
1542 WorkListItem;
1543 typedef llvm::SmallVector<WorkListItem, 5> WorkList;
1544
1545 CXCursor Cursor = MakeCXCursor(B, StmtParent, TU);
1546 WorkList WL;
1547 WL.push_back(std::make_pair(B->getRHS(), Cursor));
1548 WL.push_back(std::make_pair(B->getLHS(), Cursor));
1549
1550 while (!WL.empty()) {
1551 // Dequeue the worklist item.
1552 WorkListItem LI = WL.back(); WL.pop_back(); Expr *Ex = LI.first;
1553
1554 // Set the Parent field, then back to its old value once we're done.
1555 SetParentRAII SetParent(Parent, StmtParent, LI.second);
1556
1557 // Update the current cursor.
1558 Cursor = MakeCXCursor(Ex, StmtParent, TU);
1559
1560 // For non-BinaryOperators, perform the default visitation.
1561 if (!isa<BinaryOperator>(Ex)) {
1562 if (Visit(Cursor)) {
1563 // Skip all other items in the worklist that also have
1564 // the same parent.
1565 while (!WL.empty()) {
1566 const WorkListItem &LIb = WL.back();
1567 if (LIb.second == LI.second)
1568 WL.pop_back();
1569 else
1570 break;
1571 }
1572 // If the worklist is now empty, we should immediately return
1573 // to the caller, since this is the base case.
1574 if (WL.empty())
1575 return true;
1576 }
1577 continue;
1578 }
1579 // For BinaryOperators, perform a custom visitation where we add the
1580 // children to a worklist.
1581 if (RegionOfInterest.isValid()) {
1582 SourceRange Range = getRawCursorExtent(Cursor);
1583 if (Range.isInvalid() || CompareRegionOfInterest(Range)) {
1584 // Proceed to the next item on the worklist.
1585 continue;
1586 }
1587 }
1588 switch (Visitor(Cursor, Parent, ClientData)) {
1589 case CXChildVisit_Break: {
1590 // Skip all other items in the worklist that also have
1591 // the same parent.
1592 while (!WL.empty()) {
1593 const WorkListItem &LIb = WL.back();
1594 if (LIb.second == LI.second)
1595 WL.pop_back();
1596 else
1597 break;
1598 }
1599 // If the worklist is now empty, we should immediately return
1600 // to the caller, since this is the base case.
1601 if (WL.empty())
1602 return true;
1603 break;
1604 }
1605 case CXChildVisit_Continue:
1606 break;
1607 case CXChildVisit_Recurse: {
1608 BinaryOperator *B = cast<BinaryOperator>(Ex);
1609 // FIXME: Note that we ignore parentheses, since these are often
1610 // unimportant during cursor visitation. If we care about these, we
1611 // can unroll the visitation one more level. Alternatively, we
1612 // can convert the entire visitor to be data recursive, eliminating
1613 // all edge cases.
1614 WL.push_back(std::make_pair(B->getRHS()->IgnoreParens(), Cursor));
1615 WL.push_back(std::make_pair(B->getLHS()->IgnoreParens(), Cursor));
1616 break;
1617 }
1618 }
1619 }
1620 return false;
1621}
1622
Douglas Gregor8947a752010-09-02 20:35:02 +00001623bool CursorVisitor::VisitDeclRefExpr(DeclRefExpr *E) {
1624 // Visit nested-name-specifier, if present.
1625 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1626 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1627 return true;
1628
1629 // Visit declaration name.
1630 if (VisitDeclarationNameInfo(E->getNameInfo()))
1631 return true;
1632
1633 // Visit explicitly-specified template arguments.
1634 if (E->hasExplicitTemplateArgs()) {
1635 ExplicitTemplateArgumentList &Args = E->getExplicitTemplateArgs();
1636 for (TemplateArgumentLoc *Arg = Args.getTemplateArgs(),
1637 *ArgEnd = Arg + Args.NumTemplateArgs;
1638 Arg != ArgEnd; ++Arg)
1639 if (VisitTemplateArgumentLoc(*Arg))
1640 return true;
1641 }
1642
1643 return false;
1644}
1645
Douglas Gregor6cd24e22010-07-29 00:26:18 +00001646bool CursorVisitor::VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
1647 if (Visit(MakeCXCursor(E->getArg(0), StmtParent, TU)))
1648 return true;
1649
1650 if (Visit(MakeCXCursor(E->getCallee(), StmtParent, TU)))
1651 return true;
1652
1653 for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
1654 if (Visit(MakeCXCursor(E->getArg(I), StmtParent, TU)))
1655 return true;
1656
1657 return false;
1658}
1659
Ted Kremenek3064ef92010-08-27 21:34:58 +00001660bool CursorVisitor::VisitCXXRecordDecl(CXXRecordDecl *D) {
1661 if (D->isDefinition()) {
1662 for (CXXRecordDecl::base_class_iterator I = D->bases_begin(),
1663 E = D->bases_end(); I != E; ++I) {
1664 if (Visit(cxcursor::MakeCursorCXXBaseSpecifier(I, TU)))
1665 return true;
1666 }
1667 }
1668
1669 return VisitTagDecl(D);
1670}
1671
1672
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00001673bool CursorVisitor::VisitBlockExpr(BlockExpr *B) {
1674 return Visit(B->getBlockDecl());
1675}
1676
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001677bool CursorVisitor::VisitOffsetOfExpr(OffsetOfExpr *E) {
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001678 // Visit the type into which we're computing an offset.
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001679 if (Visit(E->getTypeSourceInfo()->getTypeLoc()))
1680 return true;
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001681
1682 // Visit the components of the offsetof expression.
1683 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
1684 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
1685 const OffsetOfNode &Node = E->getComponent(I);
1686 switch (Node.getKind()) {
1687 case OffsetOfNode::Array:
1688 if (Visit(MakeCXCursor(E->getIndexExpr(Node.getArrayExprIndex()),
1689 StmtParent, TU)))
1690 return true;
1691 break;
1692
1693 case OffsetOfNode::Field:
1694 if (Visit(MakeCursorMemberRef(Node.getField(), Node.getRange().getEnd(),
1695 TU)))
1696 return true;
1697 break;
1698
1699 case OffsetOfNode::Identifier:
1700 case OffsetOfNode::Base:
1701 continue;
1702 }
1703 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001704
Douglas Gregor8ccef2d2010-09-09 23:10:46 +00001705 return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001706}
1707
Douglas Gregor336fd812010-01-23 00:40:08 +00001708bool CursorVisitor::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
1709 if (E->isArgumentType()) {
1710 if (TypeSourceInfo *TSInfo = E->getArgumentTypeInfo())
1711 return Visit(TSInfo->getTypeLoc());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001712
Douglas Gregor336fd812010-01-23 00:40:08 +00001713 return false;
1714 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001715
Douglas Gregor336fd812010-01-23 00:40:08 +00001716 return VisitExpr(E);
1717}
1718
Douglas Gregorfbb4c982010-09-02 21:07:44 +00001719bool CursorVisitor::VisitMemberExpr(MemberExpr *E) {
1720 // Visit the base expression.
1721 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1722 return true;
1723
1724 // Visit the nested-name-specifier
1725 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1726 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1727 return true;
1728
1729 // Visit the declaration name.
1730 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1731 return true;
1732
1733 // Visit the explicitly-specified template arguments, if any.
1734 if (E->hasExplicitTemplateArgs()) {
1735 for (const TemplateArgumentLoc *Arg = E->getTemplateArgs(),
1736 *ArgEnd = Arg + E->getNumTemplateArgs();
1737 Arg != ArgEnd;
1738 ++Arg) {
1739 if (VisitTemplateArgumentLoc(*Arg))
1740 return true;
1741 }
1742 }
1743
1744 return false;
1745}
1746
Douglas Gregor336fd812010-01-23 00:40:08 +00001747bool CursorVisitor::VisitExplicitCastExpr(ExplicitCastExpr *E) {
1748 if (TypeSourceInfo *TSInfo = E->getTypeInfoAsWritten())
1749 if (Visit(TSInfo->getTypeLoc()))
1750 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001751
Douglas Gregor336fd812010-01-23 00:40:08 +00001752 return VisitCastExpr(E);
1753}
1754
1755bool CursorVisitor::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
1756 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1757 if (Visit(TSInfo->getTypeLoc()))
1758 return true;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00001759
Douglas Gregor336fd812010-01-23 00:40:08 +00001760 return VisitExpr(E);
1761}
1762
Douglas Gregor36897b02010-09-10 00:22:18 +00001763bool CursorVisitor::VisitAddrLabelExpr(AddrLabelExpr *E) {
1764 return Visit(MakeCursorLabelRef(E->getLabel(), E->getLabelLoc(), TU));
1765}
1766
Douglas Gregor648220e2010-08-10 15:02:34 +00001767bool CursorVisitor::VisitTypesCompatibleExpr(TypesCompatibleExpr *E) {
1768 return Visit(E->getArgTInfo1()->getTypeLoc()) ||
1769 Visit(E->getArgTInfo2()->getTypeLoc());
1770}
1771
1772bool CursorVisitor::VisitVAArgExpr(VAArgExpr *E) {
1773 if (Visit(E->getWrittenTypeInfo()->getTypeLoc()))
1774 return true;
1775
1776 return Visit(MakeCXCursor(E->getSubExpr(), StmtParent, TU));
1777}
1778
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001779bool CursorVisitor::VisitInitListExpr(InitListExpr *E) {
1780 // We care about the syntactic form of the initializer list, only.
Douglas Gregor692577c2010-09-17 20:26:51 +00001781 if (InitListExpr *Syntactic = E->getSyntacticForm())
1782 return VisitExpr(Syntactic);
1783
1784 return VisitExpr(E);
Douglas Gregorfa2e26f2010-09-09 23:28:23 +00001785}
1786
1787bool CursorVisitor::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
1788 // Visit the designators.
1789 typedef DesignatedInitExpr::Designator Designator;
1790 for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
1791 DEnd = E->designators_end();
1792 D != DEnd; ++D) {
1793 if (D->isFieldDesignator()) {
1794 if (FieldDecl *Field = D->getField())
1795 if (Visit(MakeCursorMemberRef(Field, D->getFieldLoc(), TU)))
1796 return true;
1797
1798 continue;
1799 }
1800
1801 if (D->isArrayDesignator()) {
1802 if (Visit(MakeCXCursor(E->getArrayIndex(*D), StmtParent, TU)))
1803 return true;
1804
1805 continue;
1806 }
1807
1808 assert(D->isArrayRangeDesignator() && "Unknown designator kind");
1809 if (Visit(MakeCXCursor(E->getArrayRangeStart(*D), StmtParent, TU)) ||
1810 Visit(MakeCXCursor(E->getArrayRangeEnd(*D), StmtParent, TU)))
1811 return true;
1812 }
1813
1814 // Visit the initializer value itself.
1815 return Visit(MakeCXCursor(E->getInit(), StmtParent, TU));
1816}
1817
Douglas Gregor94802292010-09-02 21:20:16 +00001818bool CursorVisitor::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
1819 if (E->isTypeOperand()) {
1820 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1821 return Visit(TSInfo->getTypeLoc());
1822
1823 return false;
1824 }
1825
1826 return VisitExpr(E);
1827}
1828
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001829bool CursorVisitor::VisitCXXUuidofExpr(CXXUuidofExpr *E) {
1830 if (E->isTypeOperand()) {
1831 if (TypeSourceInfo *TSInfo = E->getTypeOperandSourceInfo())
1832 return Visit(TSInfo->getTypeLoc());
1833
1834 return false;
1835 }
1836
1837 return VisitExpr(E);
1838}
1839
Douglas Gregorab6677e2010-09-08 00:15:04 +00001840bool CursorVisitor::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
1841 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
Douglas Gregor40749ee2010-11-03 00:35:38 +00001842 if (Visit(TSInfo->getTypeLoc()))
1843 return true;
Douglas Gregorab6677e2010-09-08 00:15:04 +00001844
1845 return VisitExpr(E);
1846}
1847
1848bool CursorVisitor::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1849 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1850 return Visit(TSInfo->getTypeLoc());
1851
1852 return false;
1853}
1854
Douglas Gregor1bb2a932010-09-07 21:49:58 +00001855bool CursorVisitor::VisitCXXNewExpr(CXXNewExpr *E) {
1856 // Visit placement arguments.
1857 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1858 if (Visit(MakeCXCursor(E->getPlacementArg(I), StmtParent, TU)))
1859 return true;
1860
1861 // Visit the allocated type.
1862 if (TypeSourceInfo *TSInfo = E->getAllocatedTypeSourceInfo())
1863 if (Visit(TSInfo->getTypeLoc()))
1864 return true;
1865
1866 // Visit the array size, if any.
1867 if (E->isArray() && Visit(MakeCXCursor(E->getArraySize(), StmtParent, TU)))
1868 return true;
1869
1870 // Visit the initializer or constructor arguments.
1871 for (unsigned I = 0, N = E->getNumConstructorArgs(); I != N; ++I)
1872 if (Visit(MakeCXCursor(E->getConstructorArg(I), StmtParent, TU)))
1873 return true;
1874
1875 return false;
1876}
1877
Douglas Gregor6f7198f2010-09-02 22:09:03 +00001878bool CursorVisitor::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
1879 // Visit base expression.
1880 if (Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1881 return true;
1882
1883 // Visit the nested-name-specifier.
1884 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1885 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1886 return true;
1887
1888 // Visit the scope type that looks disturbingly like the nested-name-specifier
1889 // but isn't.
1890 if (TypeSourceInfo *TSInfo = E->getScopeTypeInfo())
1891 if (Visit(TSInfo->getTypeLoc()))
1892 return true;
1893
1894 // Visit the name of the type being destroyed.
1895 if (TypeSourceInfo *TSInfo = E->getDestroyedTypeInfo())
1896 if (Visit(TSInfo->getTypeLoc()))
1897 return true;
1898
1899 return false;
1900}
1901
Douglas Gregor3d37c0a2010-09-09 16:14:44 +00001902bool CursorVisitor::VisitUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
1903 return Visit(E->getQueriedTypeSourceInfo()->getTypeLoc());
1904}
1905
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001906bool CursorVisitor::VisitOverloadExpr(OverloadExpr *E) {
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001907 // Visit the nested-name-specifier.
1908 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1909 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1910 return true;
1911
1912 // Visit the declaration name.
1913 if (VisitDeclarationNameInfo(E->getNameInfo()))
1914 return true;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00001915
1916 // Visit the overloaded declaration reference.
1917 if (Visit(MakeCursorOverloadedDeclRef(E, TU)))
1918 return true;
1919
Douglas Gregor1f7b5902010-09-02 22:29:21 +00001920 // Visit the explicitly-specified template arguments.
1921 if (const ExplicitTemplateArgumentList *ArgList
1922 = E->getOptionalExplicitTemplateArgs()) {
1923 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1924 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1925 Arg != ArgEnd; ++Arg) {
1926 if (VisitTemplateArgumentLoc(*Arg))
1927 return true;
1928 }
1929 }
1930
Douglas Gregor8ab670e2010-09-02 22:19:24 +00001931 return false;
1932}
1933
Douglas Gregorbfebed22010-09-03 17:24:10 +00001934bool CursorVisitor::VisitDependentScopeDeclRefExpr(
1935 DependentScopeDeclRefExpr *E) {
1936 // Visit the nested-name-specifier.
1937 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1938 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1939 return true;
1940
1941 // Visit the declaration name.
1942 if (VisitDeclarationNameInfo(E->getNameInfo()))
1943 return true;
1944
1945 // Visit the explicitly-specified template arguments.
1946 if (const ExplicitTemplateArgumentList *ArgList
1947 = E->getOptionalExplicitTemplateArgs()) {
1948 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1949 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1950 Arg != ArgEnd; ++Arg) {
1951 if (VisitTemplateArgumentLoc(*Arg))
1952 return true;
1953 }
1954 }
1955
1956 return false;
1957}
1958
Douglas Gregorab6677e2010-09-08 00:15:04 +00001959bool CursorVisitor::VisitCXXUnresolvedConstructExpr(
1960 CXXUnresolvedConstructExpr *E) {
1961 if (TypeSourceInfo *TSInfo = E->getTypeSourceInfo())
1962 if (Visit(TSInfo->getTypeLoc()))
1963 return true;
1964
1965 return VisitExpr(E);
1966}
1967
Douglas Gregor25d63622010-09-03 17:35:34 +00001968bool CursorVisitor::VisitCXXDependentScopeMemberExpr(
1969 CXXDependentScopeMemberExpr *E) {
1970 // Visit the base expression, if there is one.
1971 if (!E->isImplicitAccess() &&
1972 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
1973 return true;
1974
1975 // Visit the nested-name-specifier.
1976 if (NestedNameSpecifier *Qualifier = E->getQualifier())
1977 if (VisitNestedNameSpecifier(Qualifier, E->getQualifierRange()))
1978 return true;
1979
1980 // Visit the declaration name.
1981 if (VisitDeclarationNameInfo(E->getMemberNameInfo()))
1982 return true;
1983
1984 // Visit the explicitly-specified template arguments.
1985 if (const ExplicitTemplateArgumentList *ArgList
1986 = E->getOptionalExplicitTemplateArgs()) {
1987 for (const TemplateArgumentLoc *Arg = ArgList->getTemplateArgs(),
1988 *ArgEnd = Arg + ArgList->NumTemplateArgs;
1989 Arg != ArgEnd; ++Arg) {
1990 if (VisitTemplateArgumentLoc(*Arg))
1991 return true;
1992 }
1993 }
1994
1995 return false;
1996}
1997
Douglas Gregoraaa80b22010-09-03 18:01:25 +00001998bool CursorVisitor::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
1999 // Visit the base expression, if there is one.
2000 if (!E->isImplicitAccess() &&
2001 Visit(MakeCXCursor(E->getBase(), StmtParent, TU)))
2002 return true;
2003
2004 return VisitOverloadExpr(E);
2005}
Douglas Gregor25d63622010-09-03 17:35:34 +00002006
Douglas Gregorc2350e52010-03-08 16:40:19 +00002007bool CursorVisitor::VisitObjCMessageExpr(ObjCMessageExpr *E) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002008 if (TypeSourceInfo *TSInfo = E->getClassReceiverTypeInfo())
2009 if (Visit(TSInfo->getTypeLoc()))
2010 return true;
Douglas Gregorc2350e52010-03-08 16:40:19 +00002011
2012 return VisitExpr(E);
2013}
2014
Douglas Gregor81d34662010-04-20 15:39:42 +00002015bool CursorVisitor::VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
2016 return Visit(E->getEncodedTypeSourceInfo()->getTypeLoc());
2017}
2018
2019
Ted Kremenek09dfa372010-02-18 05:46:33 +00002020bool CursorVisitor::VisitAttributes(Decl *D) {
Sean Huntcf807c42010-08-18 23:23:40 +00002021 for (AttrVec::const_iterator i = D->attr_begin(), e = D->attr_end();
2022 i != e; ++i)
2023 if (Visit(MakeCXCursor(*i, D, TU)))
Ted Kremenek09dfa372010-02-18 05:46:33 +00002024 return true;
2025
2026 return false;
2027}
2028
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002029static llvm::sys::Mutex EnableMultithreadingMutex;
2030static bool EnabledMultithreading;
2031
Benjamin Kramer5e4bc592009-10-18 16:11:04 +00002032extern "C" {
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002033CXIndex clang_createIndex(int excludeDeclarationsFromPCH,
2034 int displayDiagnostics) {
Daniel Dunbar48615ff2010-10-08 19:30:33 +00002035 // Disable pretty stack trace functionality, which will otherwise be a very
2036 // poor citizen of the world and set up all sorts of signal handlers.
2037 llvm::DisablePrettyStackTrace = true;
2038
Daniel Dunbarc7df4f32010-08-18 18:43:14 +00002039 // We use crash recovery to make some of our APIs more reliable, implicitly
2040 // enable it.
2041 llvm::CrashRecoveryContext::Enable();
2042
Douglas Gregor8c8d5412010-09-24 21:18:36 +00002043 // Enable support for multithreading in LLVM.
2044 {
2045 llvm::sys::ScopedLock L(EnableMultithreadingMutex);
2046 if (!EnabledMultithreading) {
2047 llvm::llvm_start_multithreaded();
2048 EnabledMultithreading = true;
2049 }
2050 }
2051
Douglas Gregora030b7c2010-01-22 20:35:53 +00002052 CIndexer *CIdxr = new CIndexer();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002053 if (excludeDeclarationsFromPCH)
2054 CIdxr->setOnlyLocalDecls();
Douglas Gregor0a812cf2010-02-18 23:07:20 +00002055 if (displayDiagnostics)
2056 CIdxr->setDisplayDiagnostics();
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002057 return CIdxr;
Steve Naroff600866c2009-08-27 19:51:58 +00002058}
2059
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002060void clang_disposeIndex(CXIndex CIdx) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002061 if (CIdx)
2062 delete static_cast<CIndexer *>(CIdx);
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002063}
2064
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002065CXTranslationUnit clang_createTranslationUnit(CXIndex CIdx,
Douglas Gregora88084b2010-02-18 18:08:43 +00002066 const char *ast_filename) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002067 if (!CIdx)
2068 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002069
Douglas Gregor7d1d49d2009-10-16 20:01:17 +00002070 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002071 FileSystemOptions FileSystemOpts;
2072 FileSystemOpts.WorkingDir = CXXIdx->getWorkingDirectory();
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002073
Douglas Gregor28019772010-04-05 23:52:57 +00002074 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002075 return ASTUnit::LoadFromASTFile(ast_filename, Diags, FileSystemOpts,
Douglas Gregora88084b2010-02-18 18:08:43 +00002076 CXXIdx->getOnlyLocalDecls(),
2077 0, 0, true);
Steve Naroff600866c2009-08-27 19:51:58 +00002078}
2079
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002080unsigned clang_defaultEditingTranslationUnitOptions() {
Douglas Gregor2a2c50b2010-09-27 05:49:58 +00002081 return CXTranslationUnit_PrecompiledPreamble |
Douglas Gregor99ba2022010-10-27 17:24:53 +00002082 CXTranslationUnit_CacheCompletionResults |
2083 CXTranslationUnit_CXXPrecompiledPreamble;
Douglas Gregorb1c031b2010-08-09 22:28:58 +00002084}
2085
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002086CXTranslationUnit
2087clang_createTranslationUnitFromSourceFile(CXIndex CIdx,
2088 const char *source_filename,
2089 int num_command_line_args,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002090 const char * const *command_line_args,
Douglas Gregor4db64a42010-01-23 00:14:00 +00002091 unsigned num_unsaved_files,
Douglas Gregora88084b2010-02-18 18:08:43 +00002092 struct CXUnsavedFile *unsaved_files) {
Douglas Gregor5a430212010-07-21 18:52:53 +00002093 return clang_parseTranslationUnit(CIdx, source_filename,
2094 command_line_args, num_command_line_args,
2095 unsaved_files, num_unsaved_files,
2096 CXTranslationUnit_DetailedPreprocessingRecord);
2097}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002098
2099struct ParseTranslationUnitInfo {
2100 CXIndex CIdx;
2101 const char *source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002102 const char *const *command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002103 int num_command_line_args;
2104 struct CXUnsavedFile *unsaved_files;
2105 unsigned num_unsaved_files;
2106 unsigned options;
2107 CXTranslationUnit result;
2108};
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002109static void clang_parseTranslationUnit_Impl(void *UserData) {
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002110 ParseTranslationUnitInfo *PTUI =
2111 static_cast<ParseTranslationUnitInfo*>(UserData);
2112 CXIndex CIdx = PTUI->CIdx;
2113 const char *source_filename = PTUI->source_filename;
Douglas Gregor2ef69442010-09-01 16:43:19 +00002114 const char * const *command_line_args = PTUI->command_line_args;
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002115 int num_command_line_args = PTUI->num_command_line_args;
2116 struct CXUnsavedFile *unsaved_files = PTUI->unsaved_files;
2117 unsigned num_unsaved_files = PTUI->num_unsaved_files;
2118 unsigned options = PTUI->options;
2119 PTUI->result = 0;
Douglas Gregor5a430212010-07-21 18:52:53 +00002120
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002121 if (!CIdx)
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002122 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002123
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002124 CIndexer *CXXIdx = static_cast<CIndexer *>(CIdx);
2125
Douglas Gregor44c181a2010-07-23 00:33:23 +00002126 bool PrecompilePreamble = options & CXTranslationUnit_PrecompiledPreamble;
Douglas Gregordf95a132010-08-09 20:45:32 +00002127 bool CompleteTranslationUnit
2128 = ((options & CXTranslationUnit_Incomplete) == 0);
Douglas Gregor87c08a52010-08-13 22:48:40 +00002129 bool CacheCodeCompetionResults
2130 = options & CXTranslationUnit_CacheCompletionResults;
Douglas Gregor99ba2022010-10-27 17:24:53 +00002131 bool CXXPrecompilePreamble
2132 = options & CXTranslationUnit_CXXPrecompiledPreamble;
2133 bool CXXChainedPCH
2134 = options & CXTranslationUnit_CXXChainedPCH;
Douglas Gregor87c08a52010-08-13 22:48:40 +00002135
Douglas Gregor5352ac02010-01-28 00:27:43 +00002136 // Configure the diagnostics.
2137 DiagnosticOptions DiagOpts;
Douglas Gregor28019772010-04-05 23:52:57 +00002138 llvm::IntrusiveRefCntPtr<Diagnostic> Diags;
2139 Diags = CompilerInstance::createDiagnostics(DiagOpts, 0, 0);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002140
Douglas Gregor4db64a42010-01-23 00:14:00 +00002141 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2142 for (unsigned I = 0; I != num_unsaved_files; ++I) {
Chris Lattnera0a270c2010-04-05 22:42:27 +00002143 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002144 const llvm::MemoryBuffer *Buffer
Chris Lattnera0a270c2010-04-05 22:42:27 +00002145 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregor4db64a42010-01-23 00:14:00 +00002146 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2147 Buffer));
2148 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002149
Douglas Gregorb10daed2010-10-11 16:52:23 +00002150 llvm::SmallVector<const char *, 16> Args;
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002151
Ted Kremenek139ba862009-10-22 00:03:57 +00002152 // The 'source_filename' argument is optional. If the caller does not
2153 // specify it then it is assumed that the source file is specified
2154 // in the actual argument list.
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002155 if (source_filename)
Douglas Gregorb10daed2010-10-11 16:52:23 +00002156 Args.push_back(source_filename);
Douglas Gregor52ddc5d2010-07-09 18:39:07 +00002157
2158 // Since the Clang C library is primarily used by batch tools dealing with
2159 // (often very broken) source code, where spell-checking can have a
2160 // significant negative impact on performance (particularly when
2161 // precompiled headers are involved), we disable it by default.
Douglas Gregorb10daed2010-10-11 16:52:23 +00002162 // Only do this if we haven't found a spell-checking-related argument.
2163 bool FoundSpellCheckingArgument = false;
2164 for (int I = 0; I != num_command_line_args; ++I) {
2165 if (strcmp(command_line_args[I], "-fno-spell-checking") == 0 ||
2166 strcmp(command_line_args[I], "-fspell-checking") == 0) {
2167 FoundSpellCheckingArgument = true;
2168 break;
Steve Naroffe56b4ba2009-10-20 14:46:24 +00002169 }
Douglas Gregorb10daed2010-10-11 16:52:23 +00002170 }
2171 if (!FoundSpellCheckingArgument)
2172 Args.push_back("-fno-spell-checking");
2173
2174 Args.insert(Args.end(), command_line_args,
2175 command_line_args + num_command_line_args);
Douglas Gregord93256e2010-01-28 06:00:51 +00002176
Douglas Gregor44c181a2010-07-23 00:33:23 +00002177 // Do we need the detailed preprocessing record?
2178 if (options & CXTranslationUnit_DetailedPreprocessingRecord) {
Douglas Gregorb10daed2010-10-11 16:52:23 +00002179 Args.push_back("-Xclang");
2180 Args.push_back("-detailed-preprocessing-record");
Douglas Gregor44c181a2010-07-23 00:33:23 +00002181 }
2182
Douglas Gregorb10daed2010-10-11 16:52:23 +00002183 unsigned NumErrors = Diags->getNumErrors();
Douglas Gregorb10daed2010-10-11 16:52:23 +00002184 llvm::OwningPtr<ASTUnit> Unit(
2185 ASTUnit::LoadFromCommandLine(Args.data(), Args.data() + Args.size(),
2186 Diags,
2187 CXXIdx->getClangResourcesPath(),
2188 CXXIdx->getOnlyLocalDecls(),
2189 RemappedFiles.data(),
2190 RemappedFiles.size(),
2191 /*CaptureDiagnostics=*/true,
2192 PrecompilePreamble,
2193 CompleteTranslationUnit,
Douglas Gregor99ba2022010-10-27 17:24:53 +00002194 CacheCodeCompetionResults,
2195 CXXPrecompilePreamble,
2196 CXXChainedPCH));
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002197
Douglas Gregorb10daed2010-10-11 16:52:23 +00002198 if (NumErrors != Diags->getNumErrors()) {
2199 // Make sure to check that 'Unit' is non-NULL.
2200 if (CXXIdx->getDisplayDiagnostics() && Unit.get()) {
2201 for (ASTUnit::stored_diag_iterator D = Unit->stored_diag_begin(),
2202 DEnd = Unit->stored_diag_end();
2203 D != DEnd; ++D) {
2204 CXStoredDiagnostic Diag(*D, Unit->getASTContext().getLangOptions());
2205 CXString Msg = clang_formatDiagnostic(&Diag,
2206 clang_defaultDiagnosticDisplayOptions());
2207 fprintf(stderr, "%s\n", clang_getCString(Msg));
2208 clang_disposeString(Msg);
2209 }
Douglas Gregor274f1902010-02-22 23:17:23 +00002210#ifdef LLVM_ON_WIN32
Douglas Gregorb10daed2010-10-11 16:52:23 +00002211 // On Windows, force a flush, since there may be multiple copies of
2212 // stderr and stdout in the file system, all with different buffers
2213 // but writing to the same device.
2214 fflush(stderr);
2215#endif
2216 }
Douglas Gregora88084b2010-02-18 18:08:43 +00002217 }
Douglas Gregord93256e2010-01-28 06:00:51 +00002218
Douglas Gregorb10daed2010-10-11 16:52:23 +00002219 PTUI->result = Unit.take();
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002220}
2221CXTranslationUnit clang_parseTranslationUnit(CXIndex CIdx,
2222 const char *source_filename,
Douglas Gregor2ef69442010-09-01 16:43:19 +00002223 const char * const *command_line_args,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002224 int num_command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002225 struct CXUnsavedFile *unsaved_files,
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002226 unsigned num_unsaved_files,
2227 unsigned options) {
2228 ParseTranslationUnitInfo PTUI = { CIdx, source_filename, command_line_args,
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002229 num_command_line_args, unsaved_files,
2230 num_unsaved_files, options, 0 };
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002231 llvm::CrashRecoveryContext CRC;
2232
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002233 if (!RunSafely(CRC, clang_parseTranslationUnit_Impl, &PTUI)) {
Daniel Dunbar60a45432010-08-23 22:35:34 +00002234 fprintf(stderr, "libclang: crash detected during parsing: {\n");
2235 fprintf(stderr, " 'source_filename' : '%s'\n", source_filename);
2236 fprintf(stderr, " 'command_line_args' : [");
2237 for (int i = 0; i != num_command_line_args; ++i) {
2238 if (i)
2239 fprintf(stderr, ", ");
2240 fprintf(stderr, "'%s'", command_line_args[i]);
2241 }
2242 fprintf(stderr, "],\n");
2243 fprintf(stderr, " 'unsaved_files' : [");
2244 for (unsigned i = 0; i != num_unsaved_files; ++i) {
2245 if (i)
2246 fprintf(stderr, ", ");
2247 fprintf(stderr, "('%s', '...', %ld)", unsaved_files[i].Filename,
2248 unsaved_files[i].Length);
2249 }
2250 fprintf(stderr, "],\n");
2251 fprintf(stderr, " 'options' : %d,\n", options);
2252 fprintf(stderr, "}\n");
2253
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002254 return 0;
2255 }
2256
2257 return PTUI.result;
Steve Naroff5b7d8e22009-10-15 20:04:39 +00002258}
2259
Douglas Gregor19998442010-08-13 15:35:05 +00002260unsigned clang_defaultSaveOptions(CXTranslationUnit TU) {
2261 return CXSaveTranslationUnit_None;
2262}
2263
2264int clang_saveTranslationUnit(CXTranslationUnit TU, const char *FileName,
2265 unsigned options) {
Douglas Gregor7ae2faa2010-08-13 05:36:37 +00002266 if (!TU)
2267 return 1;
2268
2269 return static_cast<ASTUnit *>(TU)->Save(FileName);
2270}
Daniel Dunbar19ffd492010-08-18 18:43:17 +00002271
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002272void clang_disposeTranslationUnit(CXTranslationUnit CTUnit) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002273 if (CTUnit) {
2274 // If the translation unit has been marked as unsafe to free, just discard
2275 // it.
2276 if (static_cast<ASTUnit *>(CTUnit)->isUnsafeToFree())
2277 return;
2278
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002279 delete static_cast<ASTUnit *>(CTUnit);
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002280 }
Steve Naroff2bd6b9f2009-09-17 18:33:27 +00002281}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00002282
Douglas Gregore1e13bf2010-08-11 15:58:42 +00002283unsigned clang_defaultReparseOptions(CXTranslationUnit TU) {
2284 return CXReparse_None;
2285}
2286
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002287struct ReparseTranslationUnitInfo {
2288 CXTranslationUnit TU;
2289 unsigned num_unsaved_files;
2290 struct CXUnsavedFile *unsaved_files;
2291 unsigned options;
2292 int result;
2293};
Douglas Gregor593b0c12010-09-23 18:47:53 +00002294
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002295static void clang_reparseTranslationUnit_Impl(void *UserData) {
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002296 ReparseTranslationUnitInfo *RTUI =
2297 static_cast<ReparseTranslationUnitInfo*>(UserData);
2298 CXTranslationUnit TU = RTUI->TU;
2299 unsigned num_unsaved_files = RTUI->num_unsaved_files;
2300 struct CXUnsavedFile *unsaved_files = RTUI->unsaved_files;
2301 unsigned options = RTUI->options;
2302 (void) options;
2303 RTUI->result = 1;
2304
Douglas Gregorabc563f2010-07-19 21:46:24 +00002305 if (!TU)
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002306 return;
Douglas Gregor593b0c12010-09-23 18:47:53 +00002307
2308 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
2309 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002310
2311 llvm::SmallVector<ASTUnit::RemappedFile, 4> RemappedFiles;
2312 for (unsigned I = 0; I != num_unsaved_files; ++I) {
2313 llvm::StringRef Data(unsaved_files[I].Contents, unsaved_files[I].Length);
2314 const llvm::MemoryBuffer *Buffer
Douglas Gregor1abc6bc2010-08-04 16:47:14 +00002315 = llvm::MemoryBuffer::getMemBufferCopy(Data, unsaved_files[I].Filename);
Douglas Gregorabc563f2010-07-19 21:46:24 +00002316 RemappedFiles.push_back(std::make_pair(unsaved_files[I].Filename,
2317 Buffer));
2318 }
2319
Douglas Gregor593b0c12010-09-23 18:47:53 +00002320 if (!CXXUnit->Reparse(RemappedFiles.data(), RemappedFiles.size()))
2321 RTUI->result = 0;
Douglas Gregorabc563f2010-07-19 21:46:24 +00002322}
Douglas Gregor593b0c12010-09-23 18:47:53 +00002323
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002324int clang_reparseTranslationUnit(CXTranslationUnit TU,
2325 unsigned num_unsaved_files,
2326 struct CXUnsavedFile *unsaved_files,
2327 unsigned options) {
2328 ReparseTranslationUnitInfo RTUI = { TU, num_unsaved_files, unsaved_files,
2329 options, 0 };
2330 llvm::CrashRecoveryContext CRC;
2331
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00002332 if (!RunSafely(CRC, clang_reparseTranslationUnit_Impl, &RTUI)) {
Daniel Dunbarb1fd3452010-08-19 23:44:10 +00002333 fprintf(stderr, "libclang: crash detected during reparsing\n");
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002334 static_cast<ASTUnit *>(TU)->setUnsafeToFree(true);
2335 return 1;
2336 }
2337
Ted Kremenek1dfb26a2010-10-29 01:06:50 +00002338
Daniel Dunbarea94bbc2010-08-18 23:09:31 +00002339 return RTUI.result;
2340}
2341
Douglas Gregordf95a132010-08-09 20:45:32 +00002342
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002343CXString clang_getTranslationUnitSpelling(CXTranslationUnit CTUnit) {
Douglas Gregor2b37c9e2010-01-29 00:47:48 +00002344 if (!CTUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002345 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002346
Steve Naroff77accc12009-09-03 18:19:54 +00002347 ASTUnit *CXXUnit = static_cast<ASTUnit *>(CTUnit);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002348 return createCXString(CXXUnit->getOriginalSourceFileName(), true);
Steve Naroffaf08ddc2009-09-03 15:49:00 +00002349}
Daniel Dunbar1eb79b52009-08-28 16:30:07 +00002350
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002351CXCursor clang_getTranslationUnitCursor(CXTranslationUnit TU) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002352 CXCursor Result = { CXCursor_TranslationUnit, { 0, 0, TU } };
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002353 return Result;
2354}
2355
Ted Kremenekfb480492010-01-13 21:46:36 +00002356} // end: extern "C"
Steve Naroff600866c2009-08-27 19:51:58 +00002357
Ted Kremenekfb480492010-01-13 21:46:36 +00002358//===----------------------------------------------------------------------===//
Douglas Gregor1db19de2010-01-19 21:36:55 +00002359// CXSourceLocation and CXSourceRange Operations.
2360//===----------------------------------------------------------------------===//
2361
Douglas Gregorb9790342010-01-22 21:44:22 +00002362extern "C" {
2363CXSourceLocation clang_getNullLocation() {
Douglas Gregor5352ac02010-01-28 00:27:43 +00002364 CXSourceLocation Result = { { 0, 0 }, 0 };
Douglas Gregorb9790342010-01-22 21:44:22 +00002365 return Result;
2366}
2367
2368unsigned clang_equalLocations(CXSourceLocation loc1, CXSourceLocation loc2) {
Daniel Dunbar90a6b9e2010-01-30 23:58:27 +00002369 return (loc1.ptr_data[0] == loc2.ptr_data[0] &&
2370 loc1.ptr_data[1] == loc2.ptr_data[1] &&
2371 loc1.int_data == loc2.int_data);
Douglas Gregorb9790342010-01-22 21:44:22 +00002372}
2373
2374CXSourceLocation clang_getLocation(CXTranslationUnit tu,
2375 CXFile file,
2376 unsigned line,
2377 unsigned column) {
Douglas Gregor42748ec2010-04-30 19:45:53 +00002378 if (!tu || !file)
Douglas Gregorb9790342010-01-22 21:44:22 +00002379 return clang_getNullLocation();
Douglas Gregor42748ec2010-04-30 19:45:53 +00002380
Douglas Gregorb9790342010-01-22 21:44:22 +00002381 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2382 SourceLocation SLoc
2383 = CXXUnit->getSourceManager().getLocation(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002384 static_cast<const FileEntry *>(file),
Douglas Gregorb9790342010-01-22 21:44:22 +00002385 line, column);
David Chisnall83889a72010-10-15 17:07:39 +00002386 if (SLoc.isInvalid()) return clang_getNullLocation();
2387
2388 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
2389}
2390
2391CXSourceLocation clang_getLocationForOffset(CXTranslationUnit tu,
2392 CXFile file,
2393 unsigned offset) {
2394 if (!tu || !file)
2395 return clang_getNullLocation();
2396
2397 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
2398 SourceLocation Start
2399 = CXXUnit->getSourceManager().getLocation(
2400 static_cast<const FileEntry *>(file),
2401 1, 1);
2402 if (Start.isInvalid()) return clang_getNullLocation();
2403
2404 SourceLocation SLoc = Start.getFileLocWithOffset(offset);
2405
2406 if (SLoc.isInvalid()) return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002407
Ted Kremenek1a9a0bc2010-06-28 23:54:17 +00002408 return cxloc::translateSourceLocation(CXXUnit->getASTContext(), SLoc);
Douglas Gregorb9790342010-01-22 21:44:22 +00002409}
2410
Douglas Gregor5352ac02010-01-28 00:27:43 +00002411CXSourceRange clang_getNullRange() {
2412 CXSourceRange Result = { { 0, 0 }, 0, 0 };
2413 return Result;
2414}
Daniel Dunbard52864b2010-02-14 10:02:57 +00002415
Douglas Gregor5352ac02010-01-28 00:27:43 +00002416CXSourceRange clang_getRange(CXSourceLocation begin, CXSourceLocation end) {
2417 if (begin.ptr_data[0] != end.ptr_data[0] ||
2418 begin.ptr_data[1] != end.ptr_data[1])
2419 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002420
2421 CXSourceRange Result = { { begin.ptr_data[0], begin.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002422 begin.int_data, end.int_data };
Douglas Gregorb9790342010-01-22 21:44:22 +00002423 return Result;
2424}
2425
Douglas Gregor46766dc2010-01-26 19:19:08 +00002426void clang_getInstantiationLocation(CXSourceLocation location,
2427 CXFile *file,
2428 unsigned *line,
2429 unsigned *column,
2430 unsigned *offset) {
Douglas Gregor1db19de2010-01-19 21:36:55 +00002431 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2432
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002433 if (!location.ptr_data[0] || Loc.isInvalid()) {
Douglas Gregor46766dc2010-01-26 19:19:08 +00002434 if (file)
2435 *file = 0;
2436 if (line)
2437 *line = 0;
2438 if (column)
2439 *column = 0;
2440 if (offset)
2441 *offset = 0;
2442 return;
2443 }
2444
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002445 const SourceManager &SM =
2446 *static_cast<const SourceManager*>(location.ptr_data[0]);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002447 SourceLocation InstLoc = SM.getInstantiationLoc(Loc);
Douglas Gregor1db19de2010-01-19 21:36:55 +00002448
2449 if (file)
2450 *file = (void *)SM.getFileEntryForID(SM.getFileID(InstLoc));
2451 if (line)
2452 *line = SM.getInstantiationLineNumber(InstLoc);
2453 if (column)
2454 *column = SM.getInstantiationColumnNumber(InstLoc);
Douglas Gregore69517c2010-01-26 03:07:15 +00002455 if (offset)
Douglas Gregor46766dc2010-01-26 19:19:08 +00002456 *offset = SM.getDecomposedLoc(InstLoc).second;
Douglas Gregore69517c2010-01-26 03:07:15 +00002457}
2458
Douglas Gregora9b06d42010-11-09 06:24:54 +00002459void clang_getSpellingLocation(CXSourceLocation location,
2460 CXFile *file,
2461 unsigned *line,
2462 unsigned *column,
2463 unsigned *offset) {
2464 SourceLocation Loc = SourceLocation::getFromRawEncoding(location.int_data);
2465
2466 if (!location.ptr_data[0] || Loc.isInvalid()) {
2467 if (file)
2468 *file = 0;
2469 if (line)
2470 *line = 0;
2471 if (column)
2472 *column = 0;
2473 if (offset)
2474 *offset = 0;
2475 return;
2476 }
2477
2478 const SourceManager &SM =
2479 *static_cast<const SourceManager*>(location.ptr_data[0]);
2480 SourceLocation SpellLoc = Loc;
2481 if (SpellLoc.isMacroID()) {
2482 SourceLocation SimpleSpellingLoc = SM.getImmediateSpellingLoc(SpellLoc);
2483 if (SimpleSpellingLoc.isFileID() &&
2484 SM.getFileEntryForID(SM.getDecomposedLoc(SimpleSpellingLoc).first))
2485 SpellLoc = SimpleSpellingLoc;
2486 else
2487 SpellLoc = SM.getInstantiationLoc(SpellLoc);
2488 }
2489
2490 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellLoc);
2491 FileID FID = LocInfo.first;
2492 unsigned FileOffset = LocInfo.second;
2493
2494 if (file)
2495 *file = (void *)SM.getFileEntryForID(FID);
2496 if (line)
2497 *line = SM.getLineNumber(FID, FileOffset);
2498 if (column)
2499 *column = SM.getColumnNumber(FID, FileOffset);
2500 if (offset)
2501 *offset = FileOffset;
2502}
2503
Douglas Gregor1db19de2010-01-19 21:36:55 +00002504CXSourceLocation clang_getRangeStart(CXSourceRange range) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002505 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002506 range.begin_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002507 return Result;
2508}
2509
2510CXSourceLocation clang_getRangeEnd(CXSourceRange range) {
Daniel Dunbarbb4a61a2010-02-14 01:47:36 +00002511 CXSourceLocation Result = { { range.ptr_data[0], range.ptr_data[1] },
Douglas Gregor5352ac02010-01-28 00:27:43 +00002512 range.end_int_data };
Douglas Gregor1db19de2010-01-19 21:36:55 +00002513 return Result;
2514}
2515
Douglas Gregorb9790342010-01-22 21:44:22 +00002516} // end: extern "C"
2517
Douglas Gregor1db19de2010-01-19 21:36:55 +00002518//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00002519// CXFile Operations.
2520//===----------------------------------------------------------------------===//
2521
2522extern "C" {
Ted Kremenek74844072010-02-17 00:41:20 +00002523CXString clang_getFileName(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002524 if (!SFile)
Ted Kremenek74844072010-02-17 00:41:20 +00002525 return createCXString(NULL);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002526
Steve Naroff88145032009-10-27 14:35:18 +00002527 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
Ted Kremenek74844072010-02-17 00:41:20 +00002528 return createCXString(FEnt->getName());
Steve Naroff88145032009-10-27 14:35:18 +00002529}
2530
2531time_t clang_getFileTime(CXFile SFile) {
Douglas Gregor98258af2010-01-18 22:46:11 +00002532 if (!SFile)
2533 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002534
Steve Naroff88145032009-10-27 14:35:18 +00002535 FileEntry *FEnt = static_cast<FileEntry *>(SFile);
2536 return FEnt->getModificationTime();
Steve Naroffee9405e2009-09-25 21:45:39 +00002537}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002538
Douglas Gregorb9790342010-01-22 21:44:22 +00002539CXFile clang_getFile(CXTranslationUnit tu, const char *file_name) {
2540 if (!tu)
2541 return 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002542
Douglas Gregorb9790342010-01-22 21:44:22 +00002543 ASTUnit *CXXUnit = static_cast<ASTUnit *>(tu);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002544
Douglas Gregorb9790342010-01-22 21:44:22 +00002545 FileManager &FMgr = CXXUnit->getFileManager();
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +00002546 const FileEntry *File = FMgr.getFile(file_name, file_name+strlen(file_name),
2547 CXXUnit->getFileSystemOpts());
Douglas Gregorb9790342010-01-22 21:44:22 +00002548 return const_cast<FileEntry *>(File);
2549}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002550
Ted Kremenekfb480492010-01-13 21:46:36 +00002551} // end: extern "C"
Steve Naroffee9405e2009-09-25 21:45:39 +00002552
Ted Kremenekfb480492010-01-13 21:46:36 +00002553//===----------------------------------------------------------------------===//
2554// CXCursor Operations.
2555//===----------------------------------------------------------------------===//
2556
Ted Kremenekfb480492010-01-13 21:46:36 +00002557static Decl *getDeclFromExpr(Stmt *E) {
Douglas Gregordb1314e2010-10-01 21:11:22 +00002558 if (CastExpr *CE = dyn_cast<CastExpr>(E))
2559 return getDeclFromExpr(CE->getSubExpr());
2560
Ted Kremenekfb480492010-01-13 21:46:36 +00002561 if (DeclRefExpr *RefExpr = dyn_cast<DeclRefExpr>(E))
2562 return RefExpr->getDecl();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002563 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2564 return RefExpr->getDecl();
Ted Kremenekfb480492010-01-13 21:46:36 +00002565 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2566 return ME->getMemberDecl();
2567 if (ObjCIvarRefExpr *RE = dyn_cast<ObjCIvarRefExpr>(E))
2568 return RE->getDecl();
Douglas Gregordb1314e2010-10-01 21:11:22 +00002569 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(E))
2570 return PRE->getProperty();
2571
Ted Kremenekfb480492010-01-13 21:46:36 +00002572 if (CallExpr *CE = dyn_cast<CallExpr>(E))
2573 return getDeclFromExpr(CE->getCallee());
Douglas Gregor93798e22010-11-05 21:11:19 +00002574 if (CXXConstructExpr *CE = llvm::dyn_cast<CXXConstructExpr>(E))
2575 if (!CE->isElidable())
2576 return CE->getConstructor();
Ted Kremenekfb480492010-01-13 21:46:36 +00002577 if (ObjCMessageExpr *OME = dyn_cast<ObjCMessageExpr>(E))
2578 return OME->getMethodDecl();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002579
Douglas Gregordb1314e2010-10-01 21:11:22 +00002580 if (ObjCProtocolExpr *PE = dyn_cast<ObjCProtocolExpr>(E))
2581 return PE->getProtocol();
2582
Ted Kremenekfb480492010-01-13 21:46:36 +00002583 return 0;
2584}
2585
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002586static SourceLocation getLocationFromExpr(Expr *E) {
2587 if (ObjCMessageExpr *Msg = dyn_cast<ObjCMessageExpr>(E))
2588 return /*FIXME:*/Msg->getLeftLoc();
2589 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2590 return DRE->getLocation();
Douglas Gregor38f28c12010-10-22 22:24:08 +00002591 if (BlockDeclRefExpr *RefExpr = dyn_cast<BlockDeclRefExpr>(E))
2592 return RefExpr->getLocation();
Daniel Dunbarc29f4c32010-02-02 05:00:22 +00002593 if (MemberExpr *Member = dyn_cast<MemberExpr>(E))
2594 return Member->getMemberLoc();
2595 if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E))
2596 return Ivar->getLocation();
2597 return E->getLocStart();
2598}
2599
Ted Kremenekfb480492010-01-13 21:46:36 +00002600extern "C" {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002601
2602unsigned clang_visitChildren(CXCursor parent,
Douglas Gregorb1373d02010-01-20 20:59:29 +00002603 CXCursorVisitor visitor,
2604 CXClientData client_data) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002605 ASTUnit *CXXUnit = getCursorASTUnit(parent);
Douglas Gregorb1373d02010-01-20 20:59:29 +00002606
Douglas Gregoreb8837b2010-08-03 19:06:41 +00002607 CursorVisitor CursorVis(CXXUnit, visitor, client_data,
2608 CXXUnit->getMaxPCHLevel());
Douglas Gregorb1373d02010-01-20 20:59:29 +00002609 return CursorVis.VisitChildren(parent);
2610}
2611
David Chisnall3387c652010-11-03 14:12:26 +00002612#ifndef __has_feature
2613#define __has_feature(x) 0
2614#endif
2615#if __has_feature(blocks)
2616typedef enum CXChildVisitResult
2617 (^CXCursorVisitorBlock)(CXCursor cursor, CXCursor parent);
2618
2619static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2620 CXClientData client_data) {
2621 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2622 return block(cursor, parent);
2623}
2624#else
2625// If we are compiled with a compiler that doesn't have native blocks support,
2626// define and call the block manually, so the
2627typedef struct _CXChildVisitResult
2628{
2629 void *isa;
2630 int flags;
2631 int reserved;
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002632 enum CXChildVisitResult(*invoke)(struct _CXChildVisitResult*, CXCursor,
2633 CXCursor);
David Chisnall3387c652010-11-03 14:12:26 +00002634} *CXCursorVisitorBlock;
2635
2636static enum CXChildVisitResult visitWithBlock(CXCursor cursor, CXCursor parent,
2637 CXClientData client_data) {
2638 CXCursorVisitorBlock block = (CXCursorVisitorBlock)client_data;
2639 return block->invoke(block, cursor, parent);
2640}
2641#endif
2642
2643
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00002644unsigned clang_visitChildrenWithBlock(CXCursor parent,
2645 CXCursorVisitorBlock block) {
David Chisnall3387c652010-11-03 14:12:26 +00002646 return clang_visitChildren(parent, visitWithBlock, block);
2647}
2648
Douglas Gregor78205d42010-01-20 21:45:58 +00002649static CXString getDeclSpelling(Decl *D) {
2650 NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D);
2651 if (!ND)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002652 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002653
Douglas Gregor78205d42010-01-20 21:45:58 +00002654 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(ND))
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002655 return createCXString(OMD->getSelector().getAsString());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002656
Douglas Gregor78205d42010-01-20 21:45:58 +00002657 if (ObjCCategoryImplDecl *CIMP = dyn_cast<ObjCCategoryImplDecl>(ND))
2658 // No, this isn't the same as the code below. getIdentifier() is non-virtual
2659 // and returns different names. NamedDecl returns the class name and
2660 // ObjCCategoryImplDecl returns the category name.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002661 return createCXString(CIMP->getIdentifier()->getNameStart());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002662
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002663 if (isa<UsingDirectiveDecl>(D))
2664 return createCXString("");
2665
Ted Kremenek50aa6ac2010-05-19 21:51:10 +00002666 llvm::SmallString<1024> S;
2667 llvm::raw_svector_ostream os(S);
2668 ND->printName(os);
2669
2670 return createCXString(os.str());
Douglas Gregor78205d42010-01-20 21:45:58 +00002671}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00002672
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00002673CXString clang_getCursorSpelling(CXCursor C) {
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002674 if (clang_isTranslationUnit(C.kind))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00002675 return clang_getTranslationUnitSpelling(C.data[2]);
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00002676
Steve Narofff334b4e2009-09-02 18:26:48 +00002677 if (clang_isReference(C.kind)) {
2678 switch (C.kind) {
Daniel Dunbaracca7252009-11-30 20:42:49 +00002679 case CXCursor_ObjCSuperClassRef: {
Douglas Gregor2e331b92010-01-16 14:00:32 +00002680 ObjCInterfaceDecl *Super = getCursorObjCSuperClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002681 return createCXString(Super->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002682 }
2683 case CXCursor_ObjCClassRef: {
Douglas Gregor1adb0822010-01-16 17:14:40 +00002684 ObjCInterfaceDecl *Class = getCursorObjCClassRef(C).first;
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002685 return createCXString(Class->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002686 }
2687 case CXCursor_ObjCProtocolRef: {
Douglas Gregor78db0cd2010-01-16 15:44:18 +00002688 ObjCProtocolDecl *OID = getCursorObjCProtocolRef(C).first;
Douglas Gregorf46034a2010-01-18 23:41:10 +00002689 assert(OID && "getCursorSpelling(): Missing protocol decl");
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002690 return createCXString(OID->getIdentifier()->getNameStart());
Daniel Dunbaracca7252009-11-30 20:42:49 +00002691 }
Ted Kremenek3064ef92010-08-27 21:34:58 +00002692 case CXCursor_CXXBaseSpecifier: {
2693 CXXBaseSpecifier *B = getCursorCXXBaseSpecifier(C);
2694 return createCXString(B->getType().getAsString());
2695 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002696 case CXCursor_TypeRef: {
2697 TypeDecl *Type = getCursorTypeRef(C).first;
2698 assert(Type && "Missing type decl");
2699
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002700 return createCXString(getCursorContext(C).getTypeDeclType(Type).
2701 getAsString());
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002702 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00002703 case CXCursor_TemplateRef: {
2704 TemplateDecl *Template = getCursorTemplateRef(C).first;
Douglas Gregor69319002010-08-31 23:48:11 +00002705 assert(Template && "Missing template decl");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002706
2707 return createCXString(Template->getNameAsString());
2708 }
Douglas Gregor69319002010-08-31 23:48:11 +00002709
2710 case CXCursor_NamespaceRef: {
2711 NamedDecl *NS = getCursorNamespaceRef(C).first;
2712 assert(NS && "Missing namespace decl");
2713
2714 return createCXString(NS->getNameAsString());
2715 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00002716
Douglas Gregora67e03f2010-09-09 21:42:20 +00002717 case CXCursor_MemberRef: {
2718 FieldDecl *Field = getCursorMemberRef(C).first;
2719 assert(Field && "Missing member decl");
2720
2721 return createCXString(Field->getNameAsString());
2722 }
2723
Douglas Gregor36897b02010-09-10 00:22:18 +00002724 case CXCursor_LabelRef: {
2725 LabelStmt *Label = getCursorLabelRef(C).first;
2726 assert(Label && "Missing label");
2727
2728 return createCXString(Label->getID()->getName());
2729 }
2730
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002731 case CXCursor_OverloadedDeclRef: {
2732 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
2733 if (Decl *D = Storage.dyn_cast<Decl *>()) {
2734 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
2735 return createCXString(ND->getNameAsString());
2736 return createCXString("");
2737 }
2738 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
2739 return createCXString(E->getName().getAsString());
2740 OverloadedTemplateStorage *Ovl
2741 = Storage.get<OverloadedTemplateStorage*>();
2742 if (Ovl->size() == 0)
2743 return createCXString("");
2744 return createCXString((*Ovl->begin())->getNameAsString());
2745 }
2746
Daniel Dunbaracca7252009-11-30 20:42:49 +00002747 default:
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002748 return createCXString("<not implemented>");
Steve Narofff334b4e2009-09-02 18:26:48 +00002749 }
2750 }
Douglas Gregor97b98722010-01-19 23:20:36 +00002751
2752 if (clang_isExpression(C.kind)) {
2753 Decl *D = getDeclFromExpr(getCursorExpr(C));
2754 if (D)
Douglas Gregor78205d42010-01-20 21:45:58 +00002755 return getDeclSpelling(D);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002756 return createCXString("");
Douglas Gregor97b98722010-01-19 23:20:36 +00002757 }
2758
Douglas Gregor36897b02010-09-10 00:22:18 +00002759 if (clang_isStatement(C.kind)) {
2760 Stmt *S = getCursorStmt(C);
2761 if (LabelStmt *Label = dyn_cast_or_null<LabelStmt>(S))
2762 return createCXString(Label->getID()->getName());
2763
2764 return createCXString("");
2765 }
2766
Douglas Gregor4ae8f292010-03-18 17:52:52 +00002767 if (C.kind == CXCursor_MacroInstantiation)
2768 return createCXString(getCursorMacroInstantiation(C)->getName()
2769 ->getNameStart());
2770
Douglas Gregor572feb22010-03-18 18:04:21 +00002771 if (C.kind == CXCursor_MacroDefinition)
2772 return createCXString(getCursorMacroDefinition(C)->getName()
2773 ->getNameStart());
2774
Douglas Gregorecdcb882010-10-20 22:00:55 +00002775 if (C.kind == CXCursor_InclusionDirective)
2776 return createCXString(getCursorInclusionDirective(C)->getFileName());
2777
Douglas Gregor60cbfac2010-01-25 16:56:17 +00002778 if (clang_isDeclaration(C.kind))
2779 return getDeclSpelling(getCursorDecl(C));
Ted Kremeneke68fff62010-02-17 00:41:32 +00002780
Ted Kremenekee4db4f2010-02-17 00:41:08 +00002781 return createCXString("");
Steve Narofff334b4e2009-09-02 18:26:48 +00002782}
2783
Douglas Gregor358559d2010-10-02 22:49:11 +00002784CXString clang_getCursorDisplayName(CXCursor C) {
2785 if (!clang_isDeclaration(C.kind))
2786 return clang_getCursorSpelling(C);
2787
2788 Decl *D = getCursorDecl(C);
2789 if (!D)
2790 return createCXString("");
2791
2792 PrintingPolicy &Policy = getCursorContext(C).PrintingPolicy;
2793 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
2794 D = FunTmpl->getTemplatedDecl();
2795
2796 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
2797 llvm::SmallString<64> Str;
2798 llvm::raw_svector_ostream OS(Str);
2799 OS << Function->getNameAsString();
2800 if (Function->getPrimaryTemplate())
2801 OS << "<>";
2802 OS << "(";
2803 for (unsigned I = 0, N = Function->getNumParams(); I != N; ++I) {
2804 if (I)
2805 OS << ", ";
2806 OS << Function->getParamDecl(I)->getType().getAsString(Policy);
2807 }
2808
2809 if (Function->isVariadic()) {
2810 if (Function->getNumParams())
2811 OS << ", ";
2812 OS << "...";
2813 }
2814 OS << ")";
2815 return createCXString(OS.str());
2816 }
2817
2818 if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(D)) {
2819 llvm::SmallString<64> Str;
2820 llvm::raw_svector_ostream OS(Str);
2821 OS << ClassTemplate->getNameAsString();
2822 OS << "<";
2823 TemplateParameterList *Params = ClassTemplate->getTemplateParameters();
2824 for (unsigned I = 0, N = Params->size(); I != N; ++I) {
2825 if (I)
2826 OS << ", ";
2827
2828 NamedDecl *Param = Params->getParam(I);
2829 if (Param->getIdentifier()) {
2830 OS << Param->getIdentifier()->getName();
2831 continue;
2832 }
2833
2834 // There is no parameter name, which makes this tricky. Try to come up
2835 // with something useful that isn't too long.
2836 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Param))
2837 OS << (TTP->wasDeclaredWithTypename()? "typename" : "class");
2838 else if (NonTypeTemplateParmDecl *NTTP
2839 = dyn_cast<NonTypeTemplateParmDecl>(Param))
2840 OS << NTTP->getType().getAsString(Policy);
2841 else
2842 OS << "template<...> class";
2843 }
2844
2845 OS << ">";
2846 return createCXString(OS.str());
2847 }
2848
2849 if (ClassTemplateSpecializationDecl *ClassSpec
2850 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
2851 // If the type was explicitly written, use that.
2852 if (TypeSourceInfo *TSInfo = ClassSpec->getTypeAsWritten())
2853 return createCXString(TSInfo->getType().getAsString(Policy));
2854
2855 llvm::SmallString<64> Str;
2856 llvm::raw_svector_ostream OS(Str);
2857 OS << ClassSpec->getNameAsString();
2858 OS << TemplateSpecializationType::PrintTemplateArgumentList(
Douglas Gregor910f8002010-11-07 23:05:16 +00002859 ClassSpec->getTemplateArgs().data(),
2860 ClassSpec->getTemplateArgs().size(),
Douglas Gregor358559d2010-10-02 22:49:11 +00002861 Policy);
2862 return createCXString(OS.str());
2863 }
2864
2865 return clang_getCursorSpelling(C);
2866}
2867
Ted Kremeneke68fff62010-02-17 00:41:32 +00002868CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
Steve Naroff89922f82009-08-31 00:59:03 +00002869 switch (Kind) {
Ted Kremeneke68fff62010-02-17 00:41:32 +00002870 case CXCursor_FunctionDecl:
2871 return createCXString("FunctionDecl");
2872 case CXCursor_TypedefDecl:
2873 return createCXString("TypedefDecl");
2874 case CXCursor_EnumDecl:
2875 return createCXString("EnumDecl");
2876 case CXCursor_EnumConstantDecl:
2877 return createCXString("EnumConstantDecl");
2878 case CXCursor_StructDecl:
2879 return createCXString("StructDecl");
2880 case CXCursor_UnionDecl:
2881 return createCXString("UnionDecl");
2882 case CXCursor_ClassDecl:
2883 return createCXString("ClassDecl");
2884 case CXCursor_FieldDecl:
2885 return createCXString("FieldDecl");
2886 case CXCursor_VarDecl:
2887 return createCXString("VarDecl");
2888 case CXCursor_ParmDecl:
2889 return createCXString("ParmDecl");
2890 case CXCursor_ObjCInterfaceDecl:
2891 return createCXString("ObjCInterfaceDecl");
2892 case CXCursor_ObjCCategoryDecl:
2893 return createCXString("ObjCCategoryDecl");
2894 case CXCursor_ObjCProtocolDecl:
2895 return createCXString("ObjCProtocolDecl");
2896 case CXCursor_ObjCPropertyDecl:
2897 return createCXString("ObjCPropertyDecl");
2898 case CXCursor_ObjCIvarDecl:
2899 return createCXString("ObjCIvarDecl");
2900 case CXCursor_ObjCInstanceMethodDecl:
2901 return createCXString("ObjCInstanceMethodDecl");
2902 case CXCursor_ObjCClassMethodDecl:
2903 return createCXString("ObjCClassMethodDecl");
2904 case CXCursor_ObjCImplementationDecl:
2905 return createCXString("ObjCImplementationDecl");
2906 case CXCursor_ObjCCategoryImplDecl:
2907 return createCXString("ObjCCategoryImplDecl");
Ted Kremenek8bd5a692010-04-13 23:39:06 +00002908 case CXCursor_CXXMethod:
2909 return createCXString("CXXMethod");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002910 case CXCursor_UnexposedDecl:
2911 return createCXString("UnexposedDecl");
2912 case CXCursor_ObjCSuperClassRef:
2913 return createCXString("ObjCSuperClassRef");
2914 case CXCursor_ObjCProtocolRef:
2915 return createCXString("ObjCProtocolRef");
2916 case CXCursor_ObjCClassRef:
2917 return createCXString("ObjCClassRef");
2918 case CXCursor_TypeRef:
2919 return createCXString("TypeRef");
Douglas Gregor0b36e612010-08-31 20:37:03 +00002920 case CXCursor_TemplateRef:
2921 return createCXString("TemplateRef");
Douglas Gregor69319002010-08-31 23:48:11 +00002922 case CXCursor_NamespaceRef:
2923 return createCXString("NamespaceRef");
Douglas Gregora67e03f2010-09-09 21:42:20 +00002924 case CXCursor_MemberRef:
2925 return createCXString("MemberRef");
Douglas Gregor36897b02010-09-10 00:22:18 +00002926 case CXCursor_LabelRef:
2927 return createCXString("LabelRef");
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00002928 case CXCursor_OverloadedDeclRef:
2929 return createCXString("OverloadedDeclRef");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002930 case CXCursor_UnexposedExpr:
2931 return createCXString("UnexposedExpr");
Ted Kremenek1ee6cad2010-04-11 21:47:37 +00002932 case CXCursor_BlockExpr:
2933 return createCXString("BlockExpr");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002934 case CXCursor_DeclRefExpr:
2935 return createCXString("DeclRefExpr");
2936 case CXCursor_MemberRefExpr:
2937 return createCXString("MemberRefExpr");
2938 case CXCursor_CallExpr:
2939 return createCXString("CallExpr");
2940 case CXCursor_ObjCMessageExpr:
2941 return createCXString("ObjCMessageExpr");
2942 case CXCursor_UnexposedStmt:
2943 return createCXString("UnexposedStmt");
Douglas Gregor36897b02010-09-10 00:22:18 +00002944 case CXCursor_LabelStmt:
2945 return createCXString("LabelStmt");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002946 case CXCursor_InvalidFile:
2947 return createCXString("InvalidFile");
Ted Kremenek292db642010-03-19 20:39:05 +00002948 case CXCursor_InvalidCode:
2949 return createCXString("InvalidCode");
Ted Kremeneke68fff62010-02-17 00:41:32 +00002950 case CXCursor_NoDeclFound:
2951 return createCXString("NoDeclFound");
2952 case CXCursor_NotImplemented:
2953 return createCXString("NotImplemented");
2954 case CXCursor_TranslationUnit:
2955 return createCXString("TranslationUnit");
Ted Kremeneke77f4432010-02-18 03:09:07 +00002956 case CXCursor_UnexposedAttr:
2957 return createCXString("UnexposedAttr");
2958 case CXCursor_IBActionAttr:
2959 return createCXString("attribute(ibaction)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002960 case CXCursor_IBOutletAttr:
2961 return createCXString("attribute(iboutlet)");
Ted Kremenek857e9182010-05-19 17:38:06 +00002962 case CXCursor_IBOutletCollectionAttr:
2963 return createCXString("attribute(iboutletcollection)");
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00002964 case CXCursor_PreprocessingDirective:
2965 return createCXString("preprocessing directive");
Douglas Gregor572feb22010-03-18 18:04:21 +00002966 case CXCursor_MacroDefinition:
2967 return createCXString("macro definition");
Douglas Gregor48072312010-03-18 15:23:44 +00002968 case CXCursor_MacroInstantiation:
2969 return createCXString("macro instantiation");
Douglas Gregorecdcb882010-10-20 22:00:55 +00002970 case CXCursor_InclusionDirective:
2971 return createCXString("inclusion directive");
Ted Kremenek8f06e0e2010-05-06 23:38:21 +00002972 case CXCursor_Namespace:
2973 return createCXString("Namespace");
Ted Kremeneka0536d82010-05-07 01:04:29 +00002974 case CXCursor_LinkageSpec:
2975 return createCXString("LinkageSpec");
Ted Kremenek3064ef92010-08-27 21:34:58 +00002976 case CXCursor_CXXBaseSpecifier:
2977 return createCXString("C++ base class specifier");
Douglas Gregor01829d32010-08-31 14:41:23 +00002978 case CXCursor_Constructor:
2979 return createCXString("CXXConstructor");
2980 case CXCursor_Destructor:
2981 return createCXString("CXXDestructor");
2982 case CXCursor_ConversionFunction:
2983 return createCXString("CXXConversion");
Douglas Gregorfe72e9c2010-08-31 17:01:39 +00002984 case CXCursor_TemplateTypeParameter:
2985 return createCXString("TemplateTypeParameter");
2986 case CXCursor_NonTypeTemplateParameter:
2987 return createCXString("NonTypeTemplateParameter");
2988 case CXCursor_TemplateTemplateParameter:
2989 return createCXString("TemplateTemplateParameter");
2990 case CXCursor_FunctionTemplate:
2991 return createCXString("FunctionTemplate");
Douglas Gregor39d6f072010-08-31 19:02:00 +00002992 case CXCursor_ClassTemplate:
2993 return createCXString("ClassTemplate");
Douglas Gregor74dbe642010-08-31 19:31:58 +00002994 case CXCursor_ClassTemplatePartialSpecialization:
2995 return createCXString("ClassTemplatePartialSpecialization");
Douglas Gregor69319002010-08-31 23:48:11 +00002996 case CXCursor_NamespaceAlias:
2997 return createCXString("NamespaceAlias");
Douglas Gregor0a35bce2010-09-01 03:07:18 +00002998 case CXCursor_UsingDirective:
2999 return createCXString("UsingDirective");
Douglas Gregor7e242562010-09-01 19:52:22 +00003000 case CXCursor_UsingDeclaration:
3001 return createCXString("UsingDeclaration");
Steve Naroff89922f82009-08-31 00:59:03 +00003002 }
Ted Kremeneke68fff62010-02-17 00:41:32 +00003003
Ted Kremenekdeb06bd2010-01-16 02:02:09 +00003004 llvm_unreachable("Unhandled CXCursorKind");
Ted Kremeneke68fff62010-02-17 00:41:32 +00003005 return createCXString(NULL);
Steve Naroff600866c2009-08-27 19:51:58 +00003006}
Steve Naroff89922f82009-08-31 00:59:03 +00003007
Ted Kremeneke68fff62010-02-17 00:41:32 +00003008enum CXChildVisitResult GetCursorVisitor(CXCursor cursor,
3009 CXCursor parent,
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003010 CXClientData client_data) {
3011 CXCursor *BestCursor = static_cast<CXCursor *>(client_data);
Douglas Gregor93798e22010-11-05 21:11:19 +00003012
3013 // If our current best cursor is the construction of a temporary object,
3014 // don't replace that cursor with a type reference, because we want
3015 // clang_getCursor() to point at the constructor.
3016 if (clang_isExpression(BestCursor->kind) &&
3017 isa<CXXTemporaryObjectExpr>(getCursorExpr(*BestCursor)) &&
3018 cursor.kind == CXCursor_TypeRef)
3019 return CXChildVisit_Recurse;
3020
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003021 *BestCursor = cursor;
3022 return CXChildVisit_Recurse;
3023}
Ted Kremeneke68fff62010-02-17 00:41:32 +00003024
Douglas Gregorb9790342010-01-22 21:44:22 +00003025CXCursor clang_getCursor(CXTranslationUnit TU, CXSourceLocation Loc) {
3026 if (!TU)
Ted Kremenekf4629892010-01-14 01:51:23 +00003027 return clang_getNullCursor();
Ted Kremeneke68fff62010-02-17 00:41:32 +00003028
Douglas Gregorb9790342010-01-22 21:44:22 +00003029 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregorbdf60622010-03-05 21:16:25 +00003030 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3031
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003032 // Translate the given source location to make it point at the beginning of
3033 // the token under the cursor.
Ted Kremeneka297de22010-01-25 22:34:44 +00003034 SourceLocation SLoc = cxloc::translateSourceLocation(Loc);
Ted Kremeneka629ea42010-07-29 00:52:07 +00003035
3036 // Guard against an invalid SourceLocation, or we may assert in one
3037 // of the following calls.
3038 if (SLoc.isInvalid())
3039 return clang_getNullCursor();
3040
Douglas Gregor40749ee2010-11-03 00:35:38 +00003041 bool Logging = getenv("LIBCLANG_LOGGING");
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003042 SLoc = Lexer::GetBeginningOfToken(SLoc, CXXUnit->getSourceManager(),
3043 CXXUnit->getASTContext().getLangOptions());
3044
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003045 CXCursor Result = MakeCXCursorInvalid(CXCursor_NoDeclFound);
3046 if (SLoc.isValid()) {
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003047 // FIXME: Would be great to have a "hint" cursor, then walk from that
3048 // hint cursor upward until we find a cursor whose source range encloses
3049 // the region of interest, rather than starting from the translation unit.
3050 CXCursor Parent = clang_getTranslationUnitCursor(CXXUnit);
Ted Kremeneke68fff62010-02-17 00:41:32 +00003051 CursorVisitor CursorVis(CXXUnit, GetCursorVisitor, &Result,
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003052 Decl::MaxPCHLevel, SourceLocation(SLoc));
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003053 CursorVis.VisitChildren(Parent);
Steve Naroff77128dd2009-09-15 20:25:34 +00003054 }
Douglas Gregor40749ee2010-11-03 00:35:38 +00003055
3056 if (Logging) {
3057 CXFile SearchFile;
3058 unsigned SearchLine, SearchColumn;
3059 CXFile ResultFile;
3060 unsigned ResultLine, ResultColumn;
3061 CXString SearchFileName, ResultFileName, KindSpelling;
3062 CXSourceLocation ResultLoc = clang_getCursorLocation(Result);
3063
3064 clang_getInstantiationLocation(Loc, &SearchFile, &SearchLine, &SearchColumn,
3065 0);
3066 clang_getInstantiationLocation(ResultLoc, &ResultFile, &ResultLine,
3067 &ResultColumn, 0);
3068 SearchFileName = clang_getFileName(SearchFile);
3069 ResultFileName = clang_getFileName(ResultFile);
3070 KindSpelling = clang_getCursorKindSpelling(Result.kind);
3071 fprintf(stderr, "clang_getCursor(%s:%d:%d) = %s(%s:%d:%d)\n",
3072 clang_getCString(SearchFileName), SearchLine, SearchColumn,
3073 clang_getCString(KindSpelling),
3074 clang_getCString(ResultFileName), ResultLine, ResultColumn);
3075 clang_disposeString(SearchFileName);
3076 clang_disposeString(ResultFileName);
3077 clang_disposeString(KindSpelling);
3078 }
3079
Ted Kremeneke68fff62010-02-17 00:41:32 +00003080 return Result;
Steve Naroff600866c2009-08-27 19:51:58 +00003081}
3082
Ted Kremenek73885552009-11-17 19:28:59 +00003083CXCursor clang_getNullCursor(void) {
Douglas Gregor5bfb8c12010-01-20 23:34:41 +00003084 return MakeCXCursorInvalid(CXCursor_InvalidFile);
Ted Kremenek73885552009-11-17 19:28:59 +00003085}
3086
3087unsigned clang_equalCursors(CXCursor X, CXCursor Y) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003088 return X == Y;
Ted Kremenek73885552009-11-17 19:28:59 +00003089}
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003090
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003091unsigned clang_isInvalid(enum CXCursorKind K) {
Steve Naroff77128dd2009-09-15 20:25:34 +00003092 return K >= CXCursor_FirstInvalid && K <= CXCursor_LastInvalid;
3093}
3094
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003095unsigned clang_isDeclaration(enum CXCursorKind K) {
Steve Naroff89922f82009-08-31 00:59:03 +00003096 return K >= CXCursor_FirstDecl && K <= CXCursor_LastDecl;
3097}
Steve Naroff2d4d6292009-08-31 14:26:51 +00003098
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003099unsigned clang_isReference(enum CXCursorKind K) {
Steve Narofff334b4e2009-09-02 18:26:48 +00003100 return K >= CXCursor_FirstRef && K <= CXCursor_LastRef;
3101}
3102
Douglas Gregor97b98722010-01-19 23:20:36 +00003103unsigned clang_isExpression(enum CXCursorKind K) {
3104 return K >= CXCursor_FirstExpr && K <= CXCursor_LastExpr;
3105}
3106
3107unsigned clang_isStatement(enum CXCursorKind K) {
3108 return K >= CXCursor_FirstStmt && K <= CXCursor_LastStmt;
3109}
3110
Douglas Gregor7eaa8ae2010-01-20 00:23:15 +00003111unsigned clang_isTranslationUnit(enum CXCursorKind K) {
3112 return K == CXCursor_TranslationUnit;
3113}
3114
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003115unsigned clang_isPreprocessing(enum CXCursorKind K) {
3116 return K >= CXCursor_FirstPreprocessing && K <= CXCursor_LastPreprocessing;
3117}
3118
Ted Kremenekad6eff62010-03-08 21:17:29 +00003119unsigned clang_isUnexposed(enum CXCursorKind K) {
3120 switch (K) {
3121 case CXCursor_UnexposedDecl:
3122 case CXCursor_UnexposedExpr:
3123 case CXCursor_UnexposedStmt:
3124 case CXCursor_UnexposedAttr:
3125 return true;
3126 default:
3127 return false;
3128 }
3129}
3130
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003131CXCursorKind clang_getCursorKind(CXCursor C) {
Steve Naroff9efa7672009-09-04 15:44:05 +00003132 return C.kind;
3133}
3134
Douglas Gregor98258af2010-01-18 22:46:11 +00003135CXSourceLocation clang_getCursorLocation(CXCursor C) {
3136 if (clang_isReference(C.kind)) {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003137 switch (C.kind) {
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003138 case CXCursor_ObjCSuperClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003139 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3140 = getCursorObjCSuperClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003141 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003142 }
3143
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003144 case CXCursor_ObjCProtocolRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003145 std::pair<ObjCProtocolDecl *, SourceLocation> P
3146 = getCursorObjCProtocolRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003147 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003148 }
3149
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003150 case CXCursor_ObjCClassRef: {
Douglas Gregorf46034a2010-01-18 23:41:10 +00003151 std::pair<ObjCInterfaceDecl *, SourceLocation> P
3152 = getCursorObjCClassRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003153 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003154 }
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003155
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003156 case CXCursor_TypeRef: {
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003157 std::pair<TypeDecl *, SourceLocation> P = getCursorTypeRef(C);
Ted Kremeneka297de22010-01-25 22:34:44 +00003158 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003159 }
Douglas Gregor0b36e612010-08-31 20:37:03 +00003160
3161 case CXCursor_TemplateRef: {
3162 std::pair<TemplateDecl *, SourceLocation> P = getCursorTemplateRef(C);
3163 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3164 }
3165
Douglas Gregor69319002010-08-31 23:48:11 +00003166 case CXCursor_NamespaceRef: {
3167 std::pair<NamedDecl *, SourceLocation> P = getCursorNamespaceRef(C);
3168 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3169 }
3170
Douglas Gregora67e03f2010-09-09 21:42:20 +00003171 case CXCursor_MemberRef: {
3172 std::pair<FieldDecl *, SourceLocation> P = getCursorMemberRef(C);
3173 return cxloc::translateSourceLocation(P.first->getASTContext(), P.second);
3174 }
3175
Ted Kremenek3064ef92010-08-27 21:34:58 +00003176 case CXCursor_CXXBaseSpecifier: {
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003177 CXXBaseSpecifier *BaseSpec = getCursorCXXBaseSpecifier(C);
3178 if (!BaseSpec)
3179 return clang_getNullLocation();
3180
3181 if (TypeSourceInfo *TSInfo = BaseSpec->getTypeSourceInfo())
3182 return cxloc::translateSourceLocation(getCursorContext(C),
3183 TSInfo->getTypeLoc().getBeginLoc());
3184
3185 return cxloc::translateSourceLocation(getCursorContext(C),
3186 BaseSpec->getSourceRange().getBegin());
Ted Kremenek3064ef92010-08-27 21:34:58 +00003187 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003188
Douglas Gregor36897b02010-09-10 00:22:18 +00003189 case CXCursor_LabelRef: {
3190 std::pair<LabelStmt *, SourceLocation> P = getCursorLabelRef(C);
3191 return cxloc::translateSourceLocation(getCursorContext(C), P.second);
3192 }
3193
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003194 case CXCursor_OverloadedDeclRef:
3195 return cxloc::translateSourceLocation(getCursorContext(C),
3196 getCursorOverloadedDeclRef(C).second);
3197
Douglas Gregorf46034a2010-01-18 23:41:10 +00003198 default:
3199 // FIXME: Need a way to enumerate all non-reference cases.
3200 llvm_unreachable("Missed a reference kind");
3201 }
Douglas Gregor98258af2010-01-18 22:46:11 +00003202 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003203
3204 if (clang_isExpression(C.kind))
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003205 return cxloc::translateSourceLocation(getCursorContext(C),
Douglas Gregor97b98722010-01-19 23:20:36 +00003206 getLocationFromExpr(getCursorExpr(C)));
3207
Douglas Gregor36897b02010-09-10 00:22:18 +00003208 if (clang_isStatement(C.kind))
3209 return cxloc::translateSourceLocation(getCursorContext(C),
3210 getCursorStmt(C)->getLocStart());
3211
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00003212 if (C.kind == CXCursor_PreprocessingDirective) {
3213 SourceLocation L = cxcursor::getCursorPreprocessingDirective(C).getBegin();
3214 return cxloc::translateSourceLocation(getCursorContext(C), L);
3215 }
Douglas Gregor48072312010-03-18 15:23:44 +00003216
3217 if (C.kind == CXCursor_MacroInstantiation) {
Douglas Gregor4ae8f292010-03-18 17:52:52 +00003218 SourceLocation L
3219 = cxcursor::getCursorMacroInstantiation(C)->getSourceRange().getBegin();
Douglas Gregor48072312010-03-18 15:23:44 +00003220 return cxloc::translateSourceLocation(getCursorContext(C), L);
3221 }
Douglas Gregor572feb22010-03-18 18:04:21 +00003222
3223 if (C.kind == CXCursor_MacroDefinition) {
3224 SourceLocation L = cxcursor::getCursorMacroDefinition(C)->getLocation();
3225 return cxloc::translateSourceLocation(getCursorContext(C), L);
3226 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003227
3228 if (C.kind == CXCursor_InclusionDirective) {
3229 SourceLocation L
3230 = cxcursor::getCursorInclusionDirective(C)->getSourceRange().getBegin();
3231 return cxloc::translateSourceLocation(getCursorContext(C), L);
3232 }
3233
Ted Kremenek9a700d22010-05-12 06:16:13 +00003234 if (C.kind < CXCursor_FirstDecl || C.kind > CXCursor_LastDecl)
Douglas Gregor5352ac02010-01-28 00:27:43 +00003235 return clang_getNullLocation();
Douglas Gregor98258af2010-01-18 22:46:11 +00003236
Douglas Gregorf46034a2010-01-18 23:41:10 +00003237 Decl *D = getCursorDecl(C);
Douglas Gregorf46034a2010-01-18 23:41:10 +00003238 SourceLocation Loc = D->getLocation();
3239 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3240 Loc = Class->getClassLoc();
Ted Kremenek007a7c92010-11-01 23:26:51 +00003241 // FIXME: Multiple variables declared in a single declaration
3242 // currently lack the information needed to correctly determine their
3243 // ranges when accounting for the type-specifier. We use context
3244 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3245 // and if so, whether it is the first decl.
3246 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3247 if (!cxcursor::isFirstInDeclGroup(C))
3248 Loc = VD->getLocation();
3249 }
3250
Douglas Gregor2ca54fe2010-03-22 15:53:50 +00003251 return cxloc::translateSourceLocation(getCursorContext(C), Loc);
Douglas Gregor98258af2010-01-18 22:46:11 +00003252}
Douglas Gregora7bde202010-01-19 00:34:46 +00003253
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003254} // end extern "C"
3255
3256static SourceRange getRawCursorExtent(CXCursor C) {
Douglas Gregora7bde202010-01-19 00:34:46 +00003257 if (clang_isReference(C.kind)) {
3258 switch (C.kind) {
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003259 case CXCursor_ObjCSuperClassRef:
3260 return getCursorObjCSuperClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003261
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003262 case CXCursor_ObjCProtocolRef:
3263 return getCursorObjCProtocolRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003264
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003265 case CXCursor_ObjCClassRef:
3266 return getCursorObjCClassRef(C).second;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003267
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003268 case CXCursor_TypeRef:
3269 return getCursorTypeRef(C).second;
Douglas Gregor0b36e612010-08-31 20:37:03 +00003270
3271 case CXCursor_TemplateRef:
3272 return getCursorTemplateRef(C).second;
3273
Douglas Gregor69319002010-08-31 23:48:11 +00003274 case CXCursor_NamespaceRef:
3275 return getCursorNamespaceRef(C).second;
Douglas Gregora67e03f2010-09-09 21:42:20 +00003276
3277 case CXCursor_MemberRef:
3278 return getCursorMemberRef(C).second;
3279
Ted Kremenek3064ef92010-08-27 21:34:58 +00003280 case CXCursor_CXXBaseSpecifier:
Douglas Gregor1b0f7af2010-10-02 19:51:13 +00003281 return getCursorCXXBaseSpecifier(C)->getSourceRange();
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003282
Douglas Gregor36897b02010-09-10 00:22:18 +00003283 case CXCursor_LabelRef:
3284 return getCursorLabelRef(C).second;
3285
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003286 case CXCursor_OverloadedDeclRef:
3287 return getCursorOverloadedDeclRef(C).second;
3288
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003289 default:
3290 // FIXME: Need a way to enumerate all non-reference cases.
3291 llvm_unreachable("Missed a reference kind");
Douglas Gregora7bde202010-01-19 00:34:46 +00003292 }
3293 }
Douglas Gregor97b98722010-01-19 23:20:36 +00003294
3295 if (clang_isExpression(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003296 return getCursorExpr(C)->getSourceRange();
Douglas Gregor33e9abd2010-01-22 19:49:59 +00003297
3298 if (clang_isStatement(C.kind))
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003299 return getCursorStmt(C)->getSourceRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003300
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003301 if (C.kind == CXCursor_PreprocessingDirective)
3302 return cxcursor::getCursorPreprocessingDirective(C);
Douglas Gregor48072312010-03-18 15:23:44 +00003303
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003304 if (C.kind == CXCursor_MacroInstantiation)
3305 return cxcursor::getCursorMacroInstantiation(C)->getSourceRange();
Douglas Gregor572feb22010-03-18 18:04:21 +00003306
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003307 if (C.kind == CXCursor_MacroDefinition)
3308 return cxcursor::getCursorMacroDefinition(C)->getSourceRange();
Douglas Gregorecdcb882010-10-20 22:00:55 +00003309
3310 if (C.kind == CXCursor_InclusionDirective)
3311 return cxcursor::getCursorInclusionDirective(C)->getSourceRange();
3312
Ted Kremenek007a7c92010-11-01 23:26:51 +00003313 if (C.kind >= CXCursor_FirstDecl && C.kind <= CXCursor_LastDecl) {
3314 Decl *D = cxcursor::getCursorDecl(C);
3315 SourceRange R = D->getSourceRange();
3316 // FIXME: Multiple variables declared in a single declaration
3317 // currently lack the information needed to correctly determine their
3318 // ranges when accounting for the type-specifier. We use context
3319 // stored in the CXCursor to determine if the VarDecl is in a DeclGroup,
3320 // and if so, whether it is the first decl.
3321 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
3322 if (!cxcursor::isFirstInDeclGroup(C))
3323 R.setBegin(VD->getLocation());
3324 }
3325 return R;
3326 }
Douglas Gregorecdcb882010-10-20 22:00:55 +00003327 return SourceRange();}
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003328
3329extern "C" {
3330
3331CXSourceRange clang_getCursorExtent(CXCursor C) {
3332 SourceRange R = getRawCursorExtent(C);
3333 if (R.isInvalid())
Douglas Gregor5352ac02010-01-28 00:27:43 +00003334 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003335
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00003336 return cxloc::translateSourceRange(getCursorContext(C), R);
Douglas Gregora7bde202010-01-19 00:34:46 +00003337}
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003338
3339CXCursor clang_getCursorReferenced(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003340 if (clang_isInvalid(C.kind))
3341 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003342
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003343 ASTUnit *CXXUnit = getCursorASTUnit(C);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003344 if (clang_isDeclaration(C.kind)) {
3345 Decl *D = getCursorDecl(C);
3346 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
3347 return MakeCursorOverloadedDeclRef(Using, D->getLocation(), CXXUnit);
3348 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3349 return MakeCursorOverloadedDeclRef(Classes, D->getLocation(), CXXUnit);
3350 if (ObjCForwardProtocolDecl *Protocols
3351 = dyn_cast<ObjCForwardProtocolDecl>(D))
3352 return MakeCursorOverloadedDeclRef(Protocols, D->getLocation(), CXXUnit);
3353
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003354 return C;
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003355 }
3356
Douglas Gregor97b98722010-01-19 23:20:36 +00003357 if (clang_isExpression(C.kind)) {
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003358 Expr *E = getCursorExpr(C);
3359 Decl *D = getDeclFromExpr(E);
Douglas Gregor97b98722010-01-19 23:20:36 +00003360 if (D)
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003361 return MakeCXCursor(D, CXXUnit);
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003362
3363 if (OverloadExpr *Ovl = dyn_cast_or_null<OverloadExpr>(E))
3364 return MakeCursorOverloadedDeclRef(Ovl, CXXUnit);
3365
Douglas Gregor97b98722010-01-19 23:20:36 +00003366 return clang_getNullCursor();
3367 }
3368
Douglas Gregor36897b02010-09-10 00:22:18 +00003369 if (clang_isStatement(C.kind)) {
3370 Stmt *S = getCursorStmt(C);
3371 if (GotoStmt *Goto = dyn_cast_or_null<GotoStmt>(S))
3372 return MakeCXCursor(Goto->getLabel(), getCursorDecl(C),
3373 getCursorASTUnit(C));
3374
3375 return clang_getNullCursor();
3376 }
3377
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003378 if (C.kind == CXCursor_MacroInstantiation) {
3379 if (MacroDefinition *Def = getCursorMacroInstantiation(C)->getDefinition())
3380 return MakeMacroDefinitionCursor(Def, CXXUnit);
3381 }
3382
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003383 if (!clang_isReference(C.kind))
3384 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003385
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003386 switch (C.kind) {
3387 case CXCursor_ObjCSuperClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003388 return MakeCXCursor(getCursorObjCSuperClassRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003389
3390 case CXCursor_ObjCProtocolRef: {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003391 return MakeCXCursor(getCursorObjCProtocolRef(C).first, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003392
3393 case CXCursor_ObjCClassRef:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003394 return MakeCXCursor(getCursorObjCClassRef(C).first, CXXUnit);
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003395
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003396 case CXCursor_TypeRef:
Douglas Gregor7d0d40e2010-01-21 16:28:34 +00003397 return MakeCXCursor(getCursorTypeRef(C).first, CXXUnit);
Douglas Gregor0b36e612010-08-31 20:37:03 +00003398
3399 case CXCursor_TemplateRef:
3400 return MakeCXCursor(getCursorTemplateRef(C).first, CXXUnit);
3401
Douglas Gregor69319002010-08-31 23:48:11 +00003402 case CXCursor_NamespaceRef:
3403 return MakeCXCursor(getCursorNamespaceRef(C).first, CXXUnit);
3404
Douglas Gregora67e03f2010-09-09 21:42:20 +00003405 case CXCursor_MemberRef:
3406 return MakeCXCursor(getCursorMemberRef(C).first, CXXUnit);
3407
Ted Kremenek3064ef92010-08-27 21:34:58 +00003408 case CXCursor_CXXBaseSpecifier: {
3409 CXXBaseSpecifier *B = cxcursor::getCursorCXXBaseSpecifier(C);
3410 return clang_getTypeDeclaration(cxtype::MakeCXType(B->getType(),
3411 CXXUnit));
3412 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003413
Douglas Gregor36897b02010-09-10 00:22:18 +00003414 case CXCursor_LabelRef:
3415 // FIXME: We end up faking the "parent" declaration here because we
3416 // don't want to make CXCursor larger.
3417 return MakeCXCursor(getCursorLabelRef(C).first,
3418 CXXUnit->getASTContext().getTranslationUnitDecl(),
3419 CXXUnit);
3420
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003421 case CXCursor_OverloadedDeclRef:
3422 return C;
3423
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003424 default:
3425 // We would prefer to enumerate all non-reference cursor kinds here.
3426 llvm_unreachable("Unhandled reference cursor kind");
3427 break;
3428 }
3429 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003430
Douglas Gregorc5d1e932010-01-19 01:20:04 +00003431 return clang_getNullCursor();
3432}
3433
Douglas Gregorb6998662010-01-19 19:34:47 +00003434CXCursor clang_getCursorDefinition(CXCursor C) {
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003435 if (clang_isInvalid(C.kind))
3436 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003437
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003438 ASTUnit *CXXUnit = getCursorASTUnit(C);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003439
Douglas Gregorb6998662010-01-19 19:34:47 +00003440 bool WasReference = false;
Douglas Gregor97b98722010-01-19 23:20:36 +00003441 if (clang_isReference(C.kind) || clang_isExpression(C.kind)) {
Douglas Gregorb6998662010-01-19 19:34:47 +00003442 C = clang_getCursorReferenced(C);
3443 WasReference = true;
3444 }
3445
Douglas Gregorbf7efa22010-03-18 18:23:03 +00003446 if (C.kind == CXCursor_MacroInstantiation)
3447 return clang_getCursorReferenced(C);
3448
Douglas Gregorb6998662010-01-19 19:34:47 +00003449 if (!clang_isDeclaration(C.kind))
3450 return clang_getNullCursor();
3451
3452 Decl *D = getCursorDecl(C);
3453 if (!D)
3454 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003455
Douglas Gregorb6998662010-01-19 19:34:47 +00003456 switch (D->getKind()) {
3457 // Declaration kinds that don't really separate the notions of
3458 // declaration and definition.
3459 case Decl::Namespace:
3460 case Decl::Typedef:
3461 case Decl::TemplateTypeParm:
3462 case Decl::EnumConstant:
3463 case Decl::Field:
3464 case Decl::ObjCIvar:
3465 case Decl::ObjCAtDefsField:
3466 case Decl::ImplicitParam:
3467 case Decl::ParmVar:
3468 case Decl::NonTypeTemplateParm:
3469 case Decl::TemplateTemplateParm:
3470 case Decl::ObjCCategoryImpl:
3471 case Decl::ObjCImplementation:
Abramo Bagnara6206d532010-06-05 05:09:32 +00003472 case Decl::AccessSpec:
Douglas Gregorb6998662010-01-19 19:34:47 +00003473 case Decl::LinkageSpec:
3474 case Decl::ObjCPropertyImpl:
3475 case Decl::FileScopeAsm:
3476 case Decl::StaticAssert:
3477 case Decl::Block:
3478 return C;
3479
3480 // Declaration kinds that don't make any sense here, but are
3481 // nonetheless harmless.
3482 case Decl::TranslationUnit:
Douglas Gregorb6998662010-01-19 19:34:47 +00003483 break;
3484
3485 // Declaration kinds for which the definition is not resolvable.
3486 case Decl::UnresolvedUsingTypename:
3487 case Decl::UnresolvedUsingValue:
3488 break;
3489
3490 case Decl::UsingDirective:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003491 return MakeCXCursor(cast<UsingDirectiveDecl>(D)->getNominatedNamespace(),
3492 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003493
3494 case Decl::NamespaceAlias:
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003495 return MakeCXCursor(cast<NamespaceAliasDecl>(D)->getNamespace(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003496
3497 case Decl::Enum:
3498 case Decl::Record:
3499 case Decl::CXXRecord:
3500 case Decl::ClassTemplateSpecialization:
3501 case Decl::ClassTemplatePartialSpecialization:
Douglas Gregor952b0172010-02-11 01:04:33 +00003502 if (TagDecl *Def = cast<TagDecl>(D)->getDefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003503 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003504 return clang_getNullCursor();
3505
3506 case Decl::Function:
3507 case Decl::CXXMethod:
3508 case Decl::CXXConstructor:
3509 case Decl::CXXDestructor:
3510 case Decl::CXXConversion: {
3511 const FunctionDecl *Def = 0;
3512 if (cast<FunctionDecl>(D)->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003513 return MakeCXCursor(const_cast<FunctionDecl *>(Def), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003514 return clang_getNullCursor();
3515 }
3516
3517 case Decl::Var: {
Sebastian Redl31310a22010-02-01 20:16:42 +00003518 // Ask the variable if it has a definition.
3519 if (VarDecl *Def = cast<VarDecl>(D)->getDefinition())
3520 return MakeCXCursor(Def, CXXUnit);
3521 return clang_getNullCursor();
Douglas Gregorb6998662010-01-19 19:34:47 +00003522 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003523
Douglas Gregorb6998662010-01-19 19:34:47 +00003524 case Decl::FunctionTemplate: {
3525 const FunctionDecl *Def = 0;
3526 if (cast<FunctionTemplateDecl>(D)->getTemplatedDecl()->getBody(Def))
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003527 return MakeCXCursor(Def->getDescribedFunctionTemplate(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003528 return clang_getNullCursor();
3529 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003530
Douglas Gregorb6998662010-01-19 19:34:47 +00003531 case Decl::ClassTemplate: {
3532 if (RecordDecl *Def = cast<ClassTemplateDecl>(D)->getTemplatedDecl()
Douglas Gregor952b0172010-02-11 01:04:33 +00003533 ->getDefinition())
Douglas Gregor0b36e612010-08-31 20:37:03 +00003534 return MakeCXCursor(cast<CXXRecordDecl>(Def)->getDescribedClassTemplate(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003535 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003536 return clang_getNullCursor();
3537 }
3538
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003539 case Decl::Using:
3540 return MakeCursorOverloadedDeclRef(cast<UsingDecl>(D),
3541 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003542
3543 case Decl::UsingShadow:
3544 return clang_getCursorDefinition(
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003545 MakeCXCursor(cast<UsingShadowDecl>(D)->getTargetDecl(),
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003546 CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003547
3548 case Decl::ObjCMethod: {
3549 ObjCMethodDecl *Method = cast<ObjCMethodDecl>(D);
3550 if (Method->isThisDeclarationADefinition())
3551 return C;
3552
3553 // Dig out the method definition in the associated
3554 // @implementation, if we have it.
3555 // FIXME: The ASTs should make finding the definition easier.
3556 if (ObjCInterfaceDecl *Class
3557 = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext()))
3558 if (ObjCImplementationDecl *ClassImpl = Class->getImplementation())
3559 if (ObjCMethodDecl *Def = ClassImpl->getMethod(Method->getSelector(),
3560 Method->isInstanceMethod()))
3561 if (Def->isThisDeclarationADefinition())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003562 return MakeCXCursor(Def, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003563
3564 return clang_getNullCursor();
3565 }
3566
3567 case Decl::ObjCCategory:
3568 if (ObjCCategoryImplDecl *Impl
3569 = cast<ObjCCategoryDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003570 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003571 return clang_getNullCursor();
3572
3573 case Decl::ObjCProtocol:
3574 if (!cast<ObjCProtocolDecl>(D)->isForwardDecl())
3575 return C;
3576 return clang_getNullCursor();
3577
3578 case Decl::ObjCInterface:
3579 // There are two notions of a "definition" for an Objective-C
3580 // class: the interface and its implementation. When we resolved a
3581 // reference to an Objective-C class, produce the @interface as
3582 // the definition; when we were provided with the interface,
3583 // produce the @implementation as the definition.
3584 if (WasReference) {
3585 if (!cast<ObjCInterfaceDecl>(D)->isForwardDecl())
3586 return C;
3587 } else if (ObjCImplementationDecl *Impl
3588 = cast<ObjCInterfaceDecl>(D)->getImplementation())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003589 return MakeCXCursor(Impl, CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003590 return clang_getNullCursor();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003591
Douglas Gregorb6998662010-01-19 19:34:47 +00003592 case Decl::ObjCProperty:
3593 // FIXME: We don't really know where to find the
3594 // ObjCPropertyImplDecls that implement this property.
3595 return clang_getNullCursor();
3596
3597 case Decl::ObjCCompatibleAlias:
3598 if (ObjCInterfaceDecl *Class
3599 = cast<ObjCCompatibleAliasDecl>(D)->getClassInterface())
3600 if (!Class->isForwardDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003601 return MakeCXCursor(Class, CXXUnit);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003602
Douglas Gregorb6998662010-01-19 19:34:47 +00003603 return clang_getNullCursor();
3604
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003605 case Decl::ObjCForwardProtocol:
3606 return MakeCursorOverloadedDeclRef(cast<ObjCForwardProtocolDecl>(D),
3607 D->getLocation(), CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003608
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003609 case Decl::ObjCClass:
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00003610 return MakeCursorOverloadedDeclRef(cast<ObjCClassDecl>(D), D->getLocation(),
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003611 CXXUnit);
Douglas Gregorb6998662010-01-19 19:34:47 +00003612
3613 case Decl::Friend:
3614 if (NamedDecl *Friend = cast<FriendDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003615 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003616 return clang_getNullCursor();
3617
3618 case Decl::FriendTemplate:
3619 if (NamedDecl *Friend = cast<FriendTemplateDecl>(D)->getFriendDecl())
Douglas Gregorb2cd4872010-01-20 23:57:43 +00003620 return clang_getCursorDefinition(MakeCXCursor(Friend, CXXUnit));
Douglas Gregorb6998662010-01-19 19:34:47 +00003621 return clang_getNullCursor();
3622 }
3623
3624 return clang_getNullCursor();
3625}
3626
3627unsigned clang_isCursorDefinition(CXCursor C) {
3628 if (!clang_isDeclaration(C.kind))
3629 return 0;
3630
3631 return clang_getCursorDefinition(C) == C;
3632}
3633
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003634unsigned clang_getNumOverloadedDecls(CXCursor C) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003635 if (C.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003636 return 0;
3637
3638 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(C).first;
3639 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3640 return E->getNumDecls();
3641
3642 if (OverloadedTemplateStorage *S
3643 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3644 return S->size();
3645
3646 Decl *D = Storage.get<Decl*>();
3647 if (UsingDecl *Using = dyn_cast<UsingDecl>(D))
Argyrios Kyrtzidis826faa22010-11-10 05:40:41 +00003648 return Using->shadow_size();
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003649 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3650 return Classes->size();
3651 if (ObjCForwardProtocolDecl *Protocols =dyn_cast<ObjCForwardProtocolDecl>(D))
3652 return Protocols->protocol_size();
3653
3654 return 0;
3655}
3656
3657CXCursor clang_getOverloadedDecl(CXCursor cursor, unsigned index) {
Douglas Gregor7c432dd2010-09-16 13:54:00 +00003658 if (cursor.kind != CXCursor_OverloadedDeclRef)
Douglas Gregor1f60d9e2010-09-13 22:52:57 +00003659 return clang_getNullCursor();
3660
3661 if (index >= clang_getNumOverloadedDecls(cursor))
3662 return clang_getNullCursor();
3663
3664 ASTUnit *Unit = getCursorASTUnit(cursor);
3665 OverloadedDeclRefStorage Storage = getCursorOverloadedDeclRef(cursor).first;
3666 if (OverloadExpr *E = Storage.dyn_cast<OverloadExpr *>())
3667 return MakeCXCursor(E->decls_begin()[index], Unit);
3668
3669 if (OverloadedTemplateStorage *S
3670 = Storage.dyn_cast<OverloadedTemplateStorage*>())
3671 return MakeCXCursor(S->begin()[index], Unit);
3672
3673 Decl *D = Storage.get<Decl*>();
3674 if (UsingDecl *Using = dyn_cast<UsingDecl>(D)) {
3675 // FIXME: This is, unfortunately, linear time.
3676 UsingDecl::shadow_iterator Pos = Using->shadow_begin();
3677 std::advance(Pos, index);
3678 return MakeCXCursor(cast<UsingShadowDecl>(*Pos)->getTargetDecl(), Unit);
3679 }
3680
3681 if (ObjCClassDecl *Classes = dyn_cast<ObjCClassDecl>(D))
3682 return MakeCXCursor(Classes->begin()[index].getInterface(), Unit);
3683
3684 if (ObjCForwardProtocolDecl *Protocols = dyn_cast<ObjCForwardProtocolDecl>(D))
3685 return MakeCXCursor(Protocols->protocol_begin()[index], Unit);
3686
3687 return clang_getNullCursor();
3688}
3689
Daniel Dunbar0d7dd222009-11-30 20:42:43 +00003690void clang_getDefinitionSpellingAndExtent(CXCursor C,
Steve Naroff4ade6d62009-09-23 17:52:52 +00003691 const char **startBuf,
3692 const char **endBuf,
3693 unsigned *startLine,
3694 unsigned *startColumn,
3695 unsigned *endLine,
Daniel Dunbar9ebfa312009-12-01 03:14:51 +00003696 unsigned *endColumn) {
Douglas Gregor283cae32010-01-15 21:56:13 +00003697 assert(getCursorDecl(C) && "CXCursor has null decl");
3698 NamedDecl *ND = static_cast<NamedDecl *>(getCursorDecl(C));
Steve Naroff4ade6d62009-09-23 17:52:52 +00003699 FunctionDecl *FD = dyn_cast<FunctionDecl>(ND);
3700 CompoundStmt *Body = dyn_cast<CompoundStmt>(FD->getBody());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003701
Steve Naroff4ade6d62009-09-23 17:52:52 +00003702 SourceManager &SM = FD->getASTContext().getSourceManager();
3703 *startBuf = SM.getCharacterData(Body->getLBracLoc());
3704 *endBuf = SM.getCharacterData(Body->getRBracLoc());
3705 *startLine = SM.getSpellingLineNumber(Body->getLBracLoc());
3706 *startColumn = SM.getSpellingColumnNumber(Body->getLBracLoc());
3707 *endLine = SM.getSpellingLineNumber(Body->getRBracLoc());
3708 *endColumn = SM.getSpellingColumnNumber(Body->getRBracLoc());
3709}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003710
Douglas Gregor0a812cf2010-02-18 23:07:20 +00003711void clang_enableStackTraces(void) {
3712 llvm::sys::PrintStackTraceOnErrorSignal();
3713}
3714
Daniel Dunbar995aaf92010-11-04 01:26:29 +00003715void clang_executeOnThread(void (*fn)(void*), void *user_data,
3716 unsigned stack_size) {
3717 llvm::llvm_execute_on_thread(fn, user_data, stack_size);
3718}
3719
Ted Kremenekfb480492010-01-13 21:46:36 +00003720} // end: extern "C"
Steve Naroff4ade6d62009-09-23 17:52:52 +00003721
Ted Kremenekfb480492010-01-13 21:46:36 +00003722//===----------------------------------------------------------------------===//
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003723// Token-based Operations.
3724//===----------------------------------------------------------------------===//
3725
3726/* CXToken layout:
3727 * int_data[0]: a CXTokenKind
3728 * int_data[1]: starting token location
3729 * int_data[2]: token length
3730 * int_data[3]: reserved
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003731 * ptr_data: for identifiers and keywords, an IdentifierInfo*.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003732 * otherwise unused.
3733 */
3734extern "C" {
3735
3736CXTokenKind clang_getTokenKind(CXToken CXTok) {
3737 return static_cast<CXTokenKind>(CXTok.int_data[0]);
3738}
3739
3740CXString clang_getTokenSpelling(CXTranslationUnit TU, CXToken CXTok) {
3741 switch (clang_getTokenKind(CXTok)) {
3742 case CXToken_Identifier:
3743 case CXToken_Keyword:
3744 // We know we have an IdentifierInfo*, so use that.
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003745 return createCXString(static_cast<IdentifierInfo *>(CXTok.ptr_data)
3746 ->getNameStart());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003747
3748 case CXToken_Literal: {
3749 // We have stashed the starting pointer in the ptr_data field. Use it.
3750 const char *Text = static_cast<const char *>(CXTok.ptr_data);
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003751 return createCXString(llvm::StringRef(Text, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003752 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003753
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003754 case CXToken_Punctuation:
3755 case CXToken_Comment:
3756 break;
3757 }
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003758
3759 // We have to find the starting buffer pointer the hard way, by
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003760 // deconstructing the source location.
3761 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3762 if (!CXXUnit)
Ted Kremenekee4db4f2010-02-17 00:41:08 +00003763 return createCXString("");
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003764
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003765 SourceLocation Loc = SourceLocation::getFromRawEncoding(CXTok.int_data[1]);
3766 std::pair<FileID, unsigned> LocInfo
3767 = CXXUnit->getSourceManager().getDecomposedLoc(Loc);
Douglas Gregorf715ca12010-03-16 00:06:06 +00003768 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003769 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003770 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3771 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003772 return createCXString("");
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003773
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003774 return createCXString(Buffer.substr(LocInfo.second, CXTok.int_data[2]));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003775}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003776
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003777CXSourceLocation clang_getTokenLocation(CXTranslationUnit TU, CXToken CXTok) {
3778 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3779 if (!CXXUnit)
3780 return clang_getNullLocation();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003781
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003782 return cxloc::translateSourceLocation(CXXUnit->getASTContext(),
3783 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3784}
3785
3786CXSourceRange clang_getTokenExtent(CXTranslationUnit TU, CXToken CXTok) {
3787 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor5352ac02010-01-28 00:27:43 +00003788 if (!CXXUnit)
3789 return clang_getNullRange();
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003790
3791 return cxloc::translateSourceRange(CXXUnit->getASTContext(),
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003792 SourceLocation::getFromRawEncoding(CXTok.int_data[1]));
3793}
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003794
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003795void clang_tokenize(CXTranslationUnit TU, CXSourceRange Range,
3796 CXToken **Tokens, unsigned *NumTokens) {
3797 if (Tokens)
3798 *Tokens = 0;
3799 if (NumTokens)
3800 *NumTokens = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003801
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003802 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
3803 if (!CXXUnit || !Tokens || !NumTokens)
3804 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003805
Douglas Gregorbdf60622010-03-05 21:16:25 +00003806 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
3807
Daniel Dunbar85b988f2010-02-14 08:31:57 +00003808 SourceRange R = cxloc::translateCXSourceRange(Range);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003809 if (R.isInvalid())
3810 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003811
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003812 SourceManager &SourceMgr = CXXUnit->getSourceManager();
3813 std::pair<FileID, unsigned> BeginLocInfo
3814 = SourceMgr.getDecomposedLoc(R.getBegin());
3815 std::pair<FileID, unsigned> EndLocInfo
3816 = SourceMgr.getDecomposedLoc(R.getEnd());
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003817
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003818 // Cannot tokenize across files.
3819 if (BeginLocInfo.first != EndLocInfo.first)
3820 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003821
3822 // Create a lexer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003823 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003824 llvm::StringRef Buffer
Douglas Gregorf715ca12010-03-16 00:06:06 +00003825 = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid);
Douglas Gregor47a3fcd2010-03-16 20:26:15 +00003826 if (Invalid)
3827 return;
Douglas Gregoraea67db2010-03-15 22:54:52 +00003828
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003829 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
3830 CXXUnit->getASTContext().getLangOptions(),
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003831 Buffer.begin(), Buffer.data() + BeginLocInfo.second, Buffer.end());
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003832 Lex.SetCommentRetentionState(true);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003833
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003834 // Lex tokens until we hit the end of the range.
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003835 const char *EffectiveBufferEnd = Buffer.data() + EndLocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003836 llvm::SmallVector<CXToken, 32> CXTokens;
3837 Token Tok;
David Chisnall096428b2010-10-13 21:44:48 +00003838 bool previousWasAt = false;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003839 do {
3840 // Lex the next token
3841 Lex.LexFromRawLexer(Tok);
3842 if (Tok.is(tok::eof))
3843 break;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003844
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003845 // Initialize the CXToken.
3846 CXToken CXTok;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003847
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003848 // - Common fields
3849 CXTok.int_data[1] = Tok.getLocation().getRawEncoding();
3850 CXTok.int_data[2] = Tok.getLength();
3851 CXTok.int_data[3] = 0;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003852
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003853 // - Kind-specific fields
3854 if (Tok.isLiteral()) {
3855 CXTok.int_data[0] = CXToken_Literal;
3856 CXTok.ptr_data = (void *)Tok.getLiteralData();
3857 } else if (Tok.is(tok::identifier)) {
Douglas Gregoraea67db2010-03-15 22:54:52 +00003858 // Lookup the identifier to determine whether we have a keyword.
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003859 std::pair<FileID, unsigned> LocInfo
3860 = SourceMgr.getDecomposedLoc(Tok.getLocation());
Douglas Gregorf715ca12010-03-16 00:06:06 +00003861 bool Invalid = false;
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003862 llvm::StringRef Buf
Douglas Gregorf715ca12010-03-16 00:06:06 +00003863 = CXXUnit->getSourceManager().getBufferData(LocInfo.first, &Invalid);
3864 if (Invalid)
Douglas Gregoraea67db2010-03-15 22:54:52 +00003865 return;
3866
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +00003867 const char *StartPos = Buf.data() + LocInfo.second;
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003868 IdentifierInfo *II
3869 = CXXUnit->getPreprocessor().LookUpIdentifierInfo(Tok, StartPos);
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003870
David Chisnall096428b2010-10-13 21:44:48 +00003871 if ((II->getObjCKeywordID() != tok::objc_not_keyword) && previousWasAt) {
Ted Kremenekaa8a66d2010-05-05 00:55:20 +00003872 CXTok.int_data[0] = CXToken_Keyword;
3873 }
3874 else {
3875 CXTok.int_data[0] = II->getTokenID() == tok::identifier?
3876 CXToken_Identifier
3877 : CXToken_Keyword;
3878 }
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003879 CXTok.ptr_data = II;
3880 } else if (Tok.is(tok::comment)) {
3881 CXTok.int_data[0] = CXToken_Comment;
3882 CXTok.ptr_data = 0;
3883 } else {
3884 CXTok.int_data[0] = CXToken_Punctuation;
3885 CXTok.ptr_data = 0;
3886 }
3887 CXTokens.push_back(CXTok);
David Chisnall096428b2010-10-13 21:44:48 +00003888 previousWasAt = Tok.is(tok::at);
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003889 } while (Lex.getBufferLocation() <= EffectiveBufferEnd);
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003890
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003891 if (CXTokens.empty())
3892 return;
Ted Kremenekf0e23e82010-02-17 00:41:40 +00003893
Douglas Gregorfc8ea232010-01-26 17:06:03 +00003894 *Tokens = (CXToken *)malloc(sizeof(CXToken) * CXTokens.size());
3895 memmove(*Tokens, CXTokens.data(), sizeof(CXToken) * CXTokens.size());
3896 *NumTokens = CXTokens.size();
3897}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003898
Ted Kremenek6db61092010-05-05 00:55:15 +00003899void clang_disposeTokens(CXTranslationUnit TU,
3900 CXToken *Tokens, unsigned NumTokens) {
3901 free(Tokens);
3902}
3903
3904} // end: extern "C"
3905
3906//===----------------------------------------------------------------------===//
3907// Token annotation APIs.
3908//===----------------------------------------------------------------------===//
3909
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003910typedef llvm::DenseMap<unsigned, CXCursor> AnnotateTokensData;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003911static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
3912 CXCursor parent,
3913 CXClientData client_data);
Ted Kremenek6db61092010-05-05 00:55:15 +00003914namespace {
3915class AnnotateTokensWorker {
3916 AnnotateTokensData &Annotated;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003917 CXToken *Tokens;
3918 CXCursor *Cursors;
3919 unsigned NumTokens;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003920 unsigned TokIdx;
Douglas Gregor4419b672010-10-21 06:10:04 +00003921 unsigned PreprocessingTokIdx;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003922 CursorVisitor AnnotateVis;
3923 SourceManager &SrcMgr;
3924
3925 bool MoreTokens() const { return TokIdx < NumTokens; }
3926 unsigned NextToken() const { return TokIdx; }
3927 void AdvanceToken() { ++TokIdx; }
3928 SourceLocation GetTokenLoc(unsigned tokI) {
3929 return SourceLocation::getFromRawEncoding(Tokens[tokI].int_data[1]);
3930 }
3931
Ted Kremenek6db61092010-05-05 00:55:15 +00003932public:
Ted Kremenek11949cb2010-05-05 00:55:17 +00003933 AnnotateTokensWorker(AnnotateTokensData &annotated,
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003934 CXToken *tokens, CXCursor *cursors, unsigned numTokens,
3935 ASTUnit *CXXUnit, SourceRange RegionOfInterest)
Ted Kremenek11949cb2010-05-05 00:55:17 +00003936 : Annotated(annotated), Tokens(tokens), Cursors(cursors),
Douglas Gregor4419b672010-10-21 06:10:04 +00003937 NumTokens(numTokens), TokIdx(0), PreprocessingTokIdx(0),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003938 AnnotateVis(CXXUnit, AnnotateTokensVisitor, this,
3939 Decl::MaxPCHLevel, RegionOfInterest),
3940 SrcMgr(CXXUnit->getSourceManager()) {}
Ted Kremenek11949cb2010-05-05 00:55:17 +00003941
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003942 void VisitChildren(CXCursor C) { AnnotateVis.VisitChildren(C); }
Ted Kremenek6db61092010-05-05 00:55:15 +00003943 enum CXChildVisitResult Visit(CXCursor cursor, CXCursor parent);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003944 void AnnotateTokens(CXCursor parent);
Ted Kremenek6db61092010-05-05 00:55:15 +00003945};
3946}
Douglas Gregor0045e9f2010-01-26 18:31:56 +00003947
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003948void AnnotateTokensWorker::AnnotateTokens(CXCursor parent) {
3949 // Walk the AST within the region of interest, annotating tokens
3950 // along the way.
3951 VisitChildren(parent);
Ted Kremenek11949cb2010-05-05 00:55:17 +00003952
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003953 for (unsigned I = 0 ; I < TokIdx ; ++I) {
3954 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
Douglas Gregor4419b672010-10-21 06:10:04 +00003955 if (Pos != Annotated.end() &&
3956 (clang_isInvalid(Cursors[I].kind) ||
3957 Pos->second.kind != CXCursor_PreprocessingDirective))
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003958 Cursors[I] = Pos->second;
3959 }
3960
3961 // Finish up annotating any tokens left.
3962 if (!MoreTokens())
3963 return;
3964
3965 const CXCursor &C = clang_getNullCursor();
3966 for (unsigned I = TokIdx ; I < NumTokens ; ++I) {
3967 AnnotateTokensData::iterator Pos = Annotated.find(Tokens[I].int_data[1]);
3968 Cursors[I] = (Pos == Annotated.end()) ? C : Pos->second;
Ted Kremenek11949cb2010-05-05 00:55:17 +00003969 }
3970}
3971
Ted Kremenek6db61092010-05-05 00:55:15 +00003972enum CXChildVisitResult
Douglas Gregor4419b672010-10-21 06:10:04 +00003973AnnotateTokensWorker::Visit(CXCursor cursor, CXCursor parent) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00003974 CXSourceLocation Loc = clang_getCursorLocation(cursor);
Douglas Gregor4419b672010-10-21 06:10:04 +00003975 SourceRange cursorRange = getRawCursorExtent(cursor);
Douglas Gregor81d3c042010-11-01 20:13:04 +00003976 if (cursorRange.isInvalid())
3977 return CXChildVisit_Recurse;
3978
Douglas Gregor4419b672010-10-21 06:10:04 +00003979 if (clang_isPreprocessing(cursor.kind)) {
3980 // For macro instantiations, just note where the beginning of the macro
3981 // instantiation occurs.
3982 if (cursor.kind == CXCursor_MacroInstantiation) {
3983 Annotated[Loc.int_data] = cursor;
3984 return CXChildVisit_Recurse;
3985 }
3986
Douglas Gregor4419b672010-10-21 06:10:04 +00003987 // Items in the preprocessing record are kept separate from items in
3988 // declarations, so we keep a separate token index.
3989 unsigned SavedTokIdx = TokIdx;
3990 TokIdx = PreprocessingTokIdx;
3991
3992 // Skip tokens up until we catch up to the beginning of the preprocessing
3993 // entry.
3994 while (MoreTokens()) {
3995 const unsigned I = NextToken();
3996 SourceLocation TokLoc = GetTokenLoc(I);
3997 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
3998 case RangeBefore:
3999 AdvanceToken();
4000 continue;
4001 case RangeAfter:
4002 case RangeOverlap:
4003 break;
4004 }
4005 break;
4006 }
4007
4008 // Look at all of the tokens within this range.
4009 while (MoreTokens()) {
4010 const unsigned I = NextToken();
4011 SourceLocation TokLoc = GetTokenLoc(I);
4012 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4013 case RangeBefore:
4014 assert(0 && "Infeasible");
4015 case RangeAfter:
4016 break;
4017 case RangeOverlap:
4018 Cursors[I] = cursor;
4019 AdvanceToken();
4020 continue;
4021 }
4022 break;
4023 }
4024
4025 // Save the preprocessing token index; restore the non-preprocessing
4026 // token index.
4027 PreprocessingTokIdx = TokIdx;
4028 TokIdx = SavedTokIdx;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004029 return CXChildVisit_Recurse;
4030 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004031
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004032 if (cursorRange.isInvalid())
4033 return CXChildVisit_Continue;
Ted Kremeneka333c662010-05-12 05:29:33 +00004034
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004035 SourceLocation L = SourceLocation::getFromRawEncoding(Loc.int_data);
4036
Ted Kremeneka333c662010-05-12 05:29:33 +00004037 // Adjust the annotated range based specific declarations.
4038 const enum CXCursorKind cursorK = clang_getCursorKind(cursor);
4039 if (cursorK >= CXCursor_FirstDecl && cursorK <= CXCursor_LastDecl) {
Ted Kremenek23173d72010-05-18 21:09:07 +00004040 Decl *D = cxcursor::getCursorDecl(cursor);
4041 // Don't visit synthesized ObjC methods, since they have no syntatic
4042 // representation in the source.
4043 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
4044 if (MD->isSynthesized())
4045 return CXChildVisit_Continue;
4046 }
4047 if (const DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
Ted Kremeneka333c662010-05-12 05:29:33 +00004048 if (TypeSourceInfo *TI = DD->getTypeSourceInfo()) {
4049 TypeLoc TL = TI->getTypeLoc();
Abramo Bagnarabd054db2010-05-20 10:00:11 +00004050 SourceLocation TLoc = TL.getSourceRange().getBegin();
Douglas Gregor81d3c042010-11-01 20:13:04 +00004051 if (TLoc.isValid() && L.isValid() &&
Ted Kremenek6bfd5332010-05-13 15:38:38 +00004052 SrcMgr.isBeforeInTranslationUnit(TLoc, L))
Ted Kremeneka333c662010-05-12 05:29:33 +00004053 cursorRange.setBegin(TLoc);
Ted Kremeneka333c662010-05-12 05:29:33 +00004054 }
4055 }
4056 }
Douglas Gregor81d3c042010-11-01 20:13:04 +00004057
Ted Kremenek3f404602010-08-14 01:14:06 +00004058 // If the location of the cursor occurs within a macro instantiation, record
4059 // the spelling location of the cursor in our annotation map. We can then
4060 // paper over the token labelings during a post-processing step to try and
4061 // get cursor mappings for tokens that are the *arguments* of a macro
4062 // instantiation.
4063 if (L.isMacroID()) {
4064 unsigned rawEncoding = SrcMgr.getSpellingLoc(L).getRawEncoding();
4065 // Only invalidate the old annotation if it isn't part of a preprocessing
4066 // directive. Here we assume that the default construction of CXCursor
4067 // results in CXCursor.kind being an initialized value (i.e., 0). If
4068 // this isn't the case, we can fix by doing lookup + insertion.
Douglas Gregor4419b672010-10-21 06:10:04 +00004069
Ted Kremenek3f404602010-08-14 01:14:06 +00004070 CXCursor &oldC = Annotated[rawEncoding];
4071 if (!clang_isPreprocessing(oldC.kind))
4072 oldC = cursor;
4073 }
4074
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004075 const enum CXCursorKind K = clang_getCursorKind(parent);
4076 const CXCursor updateC =
Ted Kremenekd8b0a842010-08-25 22:16:02 +00004077 (clang_isInvalid(K) || K == CXCursor_TranslationUnit)
4078 ? clang_getNullCursor() : parent;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004079
4080 while (MoreTokens()) {
4081 const unsigned I = NextToken();
4082 SourceLocation TokLoc = GetTokenLoc(I);
4083 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4084 case RangeBefore:
4085 Cursors[I] = updateC;
4086 AdvanceToken();
4087 continue;
4088 case RangeAfter:
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004089 case RangeOverlap:
4090 break;
4091 }
4092 break;
4093 }
4094
4095 // Visit children to get their cursor information.
4096 const unsigned BeforeChildren = NextToken();
4097 VisitChildren(cursor);
4098 const unsigned AfterChildren = NextToken();
4099
4100 // Adjust 'Last' to the last token within the extent of the cursor.
4101 while (MoreTokens()) {
4102 const unsigned I = NextToken();
4103 SourceLocation TokLoc = GetTokenLoc(I);
4104 switch (LocationCompare(SrcMgr, TokLoc, cursorRange)) {
4105 case RangeBefore:
4106 assert(0 && "Infeasible");
4107 case RangeAfter:
4108 break;
4109 case RangeOverlap:
4110 Cursors[I] = updateC;
4111 AdvanceToken();
4112 continue;
4113 }
4114 break;
4115 }
4116 const unsigned Last = NextToken();
Ted Kremenek6db61092010-05-05 00:55:15 +00004117
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004118 // Scan the tokens that are at the beginning of the cursor, but are not
4119 // capture by the child cursors.
4120
4121 // For AST elements within macros, rely on a post-annotate pass to
4122 // to correctly annotate the tokens with cursors. Otherwise we can
4123 // get confusing results of having tokens that map to cursors that really
4124 // are expanded by an instantiation.
4125 if (L.isMacroID())
4126 cursor = clang_getNullCursor();
4127
4128 for (unsigned I = BeforeChildren; I != AfterChildren; ++I) {
4129 if (!clang_isInvalid(clang_getCursorKind(Cursors[I])))
4130 break;
Douglas Gregor4419b672010-10-21 06:10:04 +00004131
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004132 Cursors[I] = cursor;
4133 }
4134 // Scan the tokens that are at the end of the cursor, but are not captured
4135 // but the child cursors.
4136 for (unsigned I = AfterChildren; I != Last; ++I)
4137 Cursors[I] = cursor;
4138
4139 TokIdx = Last;
4140 return CXChildVisit_Continue;
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004141}
4142
Ted Kremenek6db61092010-05-05 00:55:15 +00004143static enum CXChildVisitResult AnnotateTokensVisitor(CXCursor cursor,
4144 CXCursor parent,
4145 CXClientData client_data) {
4146 return static_cast<AnnotateTokensWorker*>(client_data)->Visit(cursor, parent);
4147}
4148
4149extern "C" {
4150
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004151void clang_annotateTokens(CXTranslationUnit TU,
4152 CXToken *Tokens, unsigned NumTokens,
4153 CXCursor *Cursors) {
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004154
4155 if (NumTokens == 0 || !Tokens || !Cursors)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004156 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004157
Douglas Gregor4419b672010-10-21 06:10:04 +00004158 // Any token we don't specifically annotate will have a NULL cursor.
4159 CXCursor C = clang_getNullCursor();
4160 for (unsigned I = 0; I != NumTokens; ++I)
4161 Cursors[I] = C;
4162
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004163 ASTUnit *CXXUnit = static_cast<ASTUnit *>(TU);
Douglas Gregor4419b672010-10-21 06:10:04 +00004164 if (!CXXUnit)
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004165 return;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004166
Douglas Gregorbdf60622010-03-05 21:16:25 +00004167 ASTUnit::ConcurrencyCheck Check(*CXXUnit);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004168
Douglas Gregor0396f462010-03-19 05:22:59 +00004169 // Determine the region of interest, which contains all of the tokens.
Douglas Gregor0045e9f2010-01-26 18:31:56 +00004170 SourceRange RegionOfInterest;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004171 RegionOfInterest.setBegin(cxloc::translateSourceLocation(
4172 clang_getTokenLocation(TU, Tokens[0])));
Douglas Gregora8e5c5b2010-07-22 20:22:31 +00004173 RegionOfInterest.setEnd(cxloc::translateSourceLocation(
4174 clang_getTokenLocation(TU,
4175 Tokens[NumTokens - 1])));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004176
Douglas Gregor0396f462010-03-19 05:22:59 +00004177 // A mapping from the source locations found when re-lexing or traversing the
4178 // region of interest to the corresponding cursors.
4179 AnnotateTokensData Annotated;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004180
4181 // Relex the tokens within the source range to look for preprocessing
Douglas Gregor0396f462010-03-19 05:22:59 +00004182 // directives.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004183 SourceManager &SourceMgr = CXXUnit->getSourceManager();
4184 std::pair<FileID, unsigned> BeginLocInfo
4185 = SourceMgr.getDecomposedLoc(RegionOfInterest.getBegin());
4186 std::pair<FileID, unsigned> EndLocInfo
4187 = SourceMgr.getDecomposedLoc(RegionOfInterest.getEnd());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004188
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004189 llvm::StringRef Buffer;
Douglas Gregor0396f462010-03-19 05:22:59 +00004190 bool Invalid = false;
4191 if (BeginLocInfo.first == EndLocInfo.first &&
4192 ((Buffer = SourceMgr.getBufferData(BeginLocInfo.first, &Invalid)),true) &&
4193 !Invalid) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004194 Lexer Lex(SourceMgr.getLocForStartOfFile(BeginLocInfo.first),
4195 CXXUnit->getASTContext().getLangOptions(),
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004196 Buffer.begin(), Buffer.data() + BeginLocInfo.second,
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004197 Buffer.end());
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004198 Lex.SetCommentRetentionState(true);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004199
4200 // Lex tokens in raw mode until we hit the end of the range, to avoid
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004201 // entering #includes or expanding macros.
Douglas Gregor48072312010-03-18 15:23:44 +00004202 while (true) {
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004203 Token Tok;
4204 Lex.LexFromRawLexer(Tok);
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004205
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004206 reprocess:
4207 if (Tok.is(tok::hash) && Tok.isAtStartOfLine()) {
4208 // We have found a preprocessing directive. Gobble it up so that we
Daniel Dunbar9e1ebdd2010-11-05 07:19:21 +00004209 // don't see it while preprocessing these tokens later, but keep track
4210 // of all of the token locations inside this preprocessing directive so
4211 // that we can annotate them appropriately.
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004212 //
4213 // FIXME: Some simple tests here could identify macro definitions and
4214 // #undefs, to provide specific cursor kinds for those.
4215 std::vector<SourceLocation> Locations;
4216 do {
4217 Locations.push_back(Tok.getLocation());
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004218 Lex.LexFromRawLexer(Tok);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004219 } while (!Tok.isAtStartOfLine() && !Tok.is(tok::eof));
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004220
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004221 using namespace cxcursor;
4222 CXCursor Cursor
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004223 = MakePreprocessingDirectiveCursor(SourceRange(Locations.front(),
4224 Locations.back()),
Ted Kremenek6db61092010-05-05 00:55:15 +00004225 CXXUnit);
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004226 for (unsigned I = 0, N = Locations.size(); I != N; ++I) {
4227 Annotated[Locations[I].getRawEncoding()] = Cursor;
4228 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004229
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004230 if (Tok.isAtStartOfLine())
4231 goto reprocess;
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004232
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004233 continue;
4234 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004235
Douglas Gregor48072312010-03-18 15:23:44 +00004236 if (Tok.is(tok::eof))
Douglas Gregor9f1e3ff2010-03-18 00:42:48 +00004237 break;
4238 }
Douglas Gregor4ae8f292010-03-18 17:52:52 +00004239 }
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004240
Douglas Gregor0396f462010-03-19 05:22:59 +00004241 // Annotate all of the source locations in the region of interest that map to
Ted Kremenekfbd84ca2010-05-05 00:55:23 +00004242 // a specific cursor.
4243 AnnotateTokensWorker W(Annotated, Tokens, Cursors, NumTokens,
4244 CXXUnit, RegionOfInterest);
4245 W.AnnotateTokens(clang_getTranslationUnitCursor(CXXUnit));
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004246}
Douglas Gregorfc8ea232010-01-26 17:06:03 +00004247} // end: extern "C"
4248
4249//===----------------------------------------------------------------------===//
Ted Kremenek16b42592010-03-03 06:36:57 +00004250// Operations for querying linkage of a cursor.
4251//===----------------------------------------------------------------------===//
4252
4253extern "C" {
4254CXLinkageKind clang_getCursorLinkage(CXCursor cursor) {
Douglas Gregor0396f462010-03-19 05:22:59 +00004255 if (!clang_isDeclaration(cursor.kind))
4256 return CXLinkage_Invalid;
4257
Ted Kremenek16b42592010-03-03 06:36:57 +00004258 Decl *D = cxcursor::getCursorDecl(cursor);
4259 if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
4260 switch (ND->getLinkage()) {
4261 case NoLinkage: return CXLinkage_NoLinkage;
4262 case InternalLinkage: return CXLinkage_Internal;
4263 case UniqueExternalLinkage: return CXLinkage_UniqueExternal;
4264 case ExternalLinkage: return CXLinkage_External;
4265 };
4266
4267 return CXLinkage_Invalid;
4268}
4269} // end: extern "C"
4270
4271//===----------------------------------------------------------------------===//
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004272// Operations for querying language of a cursor.
4273//===----------------------------------------------------------------------===//
4274
4275static CXLanguageKind getDeclLanguage(const Decl *D) {
4276 switch (D->getKind()) {
4277 default:
4278 break;
4279 case Decl::ImplicitParam:
4280 case Decl::ObjCAtDefsField:
4281 case Decl::ObjCCategory:
4282 case Decl::ObjCCategoryImpl:
4283 case Decl::ObjCClass:
4284 case Decl::ObjCCompatibleAlias:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004285 case Decl::ObjCForwardProtocol:
4286 case Decl::ObjCImplementation:
4287 case Decl::ObjCInterface:
4288 case Decl::ObjCIvar:
4289 case Decl::ObjCMethod:
4290 case Decl::ObjCProperty:
4291 case Decl::ObjCPropertyImpl:
4292 case Decl::ObjCProtocol:
4293 return CXLanguage_ObjC;
4294 case Decl::CXXConstructor:
4295 case Decl::CXXConversion:
4296 case Decl::CXXDestructor:
4297 case Decl::CXXMethod:
4298 case Decl::CXXRecord:
4299 case Decl::ClassTemplate:
4300 case Decl::ClassTemplatePartialSpecialization:
4301 case Decl::ClassTemplateSpecialization:
4302 case Decl::Friend:
4303 case Decl::FriendTemplate:
4304 case Decl::FunctionTemplate:
4305 case Decl::LinkageSpec:
4306 case Decl::Namespace:
4307 case Decl::NamespaceAlias:
4308 case Decl::NonTypeTemplateParm:
4309 case Decl::StaticAssert:
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004310 case Decl::TemplateTemplateParm:
4311 case Decl::TemplateTypeParm:
4312 case Decl::UnresolvedUsingTypename:
4313 case Decl::UnresolvedUsingValue:
4314 case Decl::Using:
4315 case Decl::UsingDirective:
4316 case Decl::UsingShadow:
4317 return CXLanguage_CPlusPlus;
4318 }
4319
4320 return CXLanguage_C;
4321}
4322
4323extern "C" {
Douglas Gregor58ddb602010-08-23 23:00:57 +00004324
4325enum CXAvailabilityKind clang_getCursorAvailability(CXCursor cursor) {
4326 if (clang_isDeclaration(cursor.kind))
4327 if (Decl *D = cxcursor::getCursorDecl(cursor)) {
4328 if (D->hasAttr<UnavailableAttr>() ||
4329 (isa<FunctionDecl>(D) && cast<FunctionDecl>(D)->isDeleted()))
4330 return CXAvailability_Available;
4331
4332 if (D->hasAttr<DeprecatedAttr>())
4333 return CXAvailability_Deprecated;
4334 }
4335
4336 return CXAvailability_Available;
4337}
4338
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004339CXLanguageKind clang_getCursorLanguage(CXCursor cursor) {
4340 if (clang_isDeclaration(cursor.kind))
4341 return getDeclLanguage(cxcursor::getCursorDecl(cursor));
4342
4343 return CXLanguage_Invalid;
4344}
Douglas Gregor2be5bc92010-09-22 21:22:29 +00004345
4346CXCursor clang_getCursorSemanticParent(CXCursor cursor) {
4347 if (clang_isDeclaration(cursor.kind)) {
4348 if (Decl *D = getCursorDecl(cursor)) {
4349 DeclContext *DC = D->getDeclContext();
4350 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4351 }
4352 }
4353
4354 if (clang_isStatement(cursor.kind) || clang_isExpression(cursor.kind)) {
4355 if (Decl *D = getCursorDecl(cursor))
4356 return MakeCXCursor(D, getCursorASTUnit(cursor));
4357 }
4358
4359 return clang_getNullCursor();
4360}
4361
4362CXCursor clang_getCursorLexicalParent(CXCursor cursor) {
4363 if (clang_isDeclaration(cursor.kind)) {
4364 if (Decl *D = getCursorDecl(cursor)) {
4365 DeclContext *DC = D->getLexicalDeclContext();
4366 return MakeCXCursor(cast<Decl>(DC), getCursorASTUnit(cursor));
4367 }
4368 }
4369
4370 // FIXME: Note that we can't easily compute the lexical context of a
4371 // statement or expression, so we return nothing.
4372 return clang_getNullCursor();
4373}
4374
Douglas Gregor9f592342010-10-01 20:25:15 +00004375static void CollectOverriddenMethods(DeclContext *Ctx,
4376 ObjCMethodDecl *Method,
4377 llvm::SmallVectorImpl<ObjCMethodDecl *> &Methods) {
4378 if (!Ctx)
4379 return;
4380
4381 // If we have a class or category implementation, jump straight to the
4382 // interface.
4383 if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(Ctx))
4384 return CollectOverriddenMethods(Impl->getClassInterface(), Method, Methods);
4385
4386 ObjCContainerDecl *Container = dyn_cast<ObjCContainerDecl>(Ctx);
4387 if (!Container)
4388 return;
4389
4390 // Check whether we have a matching method at this level.
4391 if (ObjCMethodDecl *Overridden = Container->getMethod(Method->getSelector(),
4392 Method->isInstanceMethod()))
4393 if (Method != Overridden) {
4394 // We found an override at this level; there is no need to look
4395 // into other protocols or categories.
4396 Methods.push_back(Overridden);
4397 return;
4398 }
4399
4400 if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Container)) {
4401 for (ObjCProtocolDecl::protocol_iterator P = Protocol->protocol_begin(),
4402 PEnd = Protocol->protocol_end();
4403 P != PEnd; ++P)
4404 CollectOverriddenMethods(*P, Method, Methods);
4405 }
4406
4407 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Container)) {
4408 for (ObjCCategoryDecl::protocol_iterator P = Category->protocol_begin(),
4409 PEnd = Category->protocol_end();
4410 P != PEnd; ++P)
4411 CollectOverriddenMethods(*P, Method, Methods);
4412 }
4413
4414 if (ObjCInterfaceDecl *Interface = dyn_cast<ObjCInterfaceDecl>(Container)) {
4415 for (ObjCInterfaceDecl::protocol_iterator P = Interface->protocol_begin(),
4416 PEnd = Interface->protocol_end();
4417 P != PEnd; ++P)
4418 CollectOverriddenMethods(*P, Method, Methods);
4419
4420 for (ObjCCategoryDecl *Category = Interface->getCategoryList();
4421 Category; Category = Category->getNextClassCategory())
4422 CollectOverriddenMethods(Category, Method, Methods);
4423
4424 // We only look into the superclass if we haven't found anything yet.
4425 if (Methods.empty())
4426 if (ObjCInterfaceDecl *Super = Interface->getSuperClass())
4427 return CollectOverriddenMethods(Super, Method, Methods);
4428 }
4429}
4430
4431void clang_getOverriddenCursors(CXCursor cursor,
4432 CXCursor **overridden,
4433 unsigned *num_overridden) {
4434 if (overridden)
4435 *overridden = 0;
4436 if (num_overridden)
4437 *num_overridden = 0;
4438 if (!overridden || !num_overridden)
4439 return;
4440
4441 if (!clang_isDeclaration(cursor.kind))
4442 return;
4443
4444 Decl *D = getCursorDecl(cursor);
4445 if (!D)
4446 return;
4447
4448 // Handle C++ member functions.
4449 ASTUnit *CXXUnit = getCursorASTUnit(cursor);
4450 if (CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
4451 *num_overridden = CXXMethod->size_overridden_methods();
4452 if (!*num_overridden)
4453 return;
4454
4455 *overridden = new CXCursor [*num_overridden];
4456 unsigned I = 0;
4457 for (CXXMethodDecl::method_iterator
4458 M = CXXMethod->begin_overridden_methods(),
4459 MEnd = CXXMethod->end_overridden_methods();
4460 M != MEnd; (void)++M, ++I)
4461 (*overridden)[I] = MakeCXCursor(const_cast<CXXMethodDecl*>(*M), CXXUnit);
4462 return;
4463 }
4464
4465 ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D);
4466 if (!Method)
4467 return;
4468
4469 // Handle Objective-C methods.
4470 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
4471 CollectOverriddenMethods(Method->getDeclContext(), Method, Methods);
4472
4473 if (Methods.empty())
4474 return;
4475
4476 *num_overridden = Methods.size();
4477 *overridden = new CXCursor [Methods.size()];
4478 for (unsigned I = 0, N = Methods.size(); I != N; ++I)
4479 (*overridden)[I] = MakeCXCursor(Methods[I], CXXUnit);
4480}
4481
4482void clang_disposeOverriddenCursors(CXCursor *overridden) {
4483 delete [] overridden;
4484}
4485
Douglas Gregorecdcb882010-10-20 22:00:55 +00004486CXFile clang_getIncludedFile(CXCursor cursor) {
4487 if (cursor.kind != CXCursor_InclusionDirective)
4488 return 0;
4489
4490 InclusionDirective *ID = getCursorInclusionDirective(cursor);
4491 return (void *)ID->getFile();
4492}
4493
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004494} // end: extern "C"
4495
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004496
4497//===----------------------------------------------------------------------===//
4498// C++ AST instrospection.
4499//===----------------------------------------------------------------------===//
4500
4501extern "C" {
4502unsigned clang_CXXMethod_isStatic(CXCursor C) {
4503 if (!clang_isDeclaration(C.kind))
4504 return 0;
Douglas Gregor49f6f542010-08-31 22:12:17 +00004505
4506 CXXMethodDecl *Method = 0;
4507 Decl *D = cxcursor::getCursorDecl(C);
4508 if (FunctionTemplateDecl *FunTmpl = dyn_cast_or_null<FunctionTemplateDecl>(D))
4509 Method = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
4510 else
4511 Method = dyn_cast_or_null<CXXMethodDecl>(D);
4512 return (Method && Method->isStatic()) ? 1 : 0;
Ted Kremenek40b492a2010-05-17 20:12:45 +00004513}
Ted Kremenekb12903e2010-05-18 22:32:15 +00004514
Ted Kremenek9ada39a2010-05-17 20:06:56 +00004515} // end: extern "C"
4516
Ted Kremenek45e1dae2010-04-12 21:22:16 +00004517//===----------------------------------------------------------------------===//
Ted Kremenek95f33552010-08-26 01:42:22 +00004518// Attribute introspection.
4519//===----------------------------------------------------------------------===//
4520
4521extern "C" {
4522CXType clang_getIBOutletCollectionType(CXCursor C) {
4523 if (C.kind != CXCursor_IBOutletCollectionAttr)
4524 return cxtype::MakeCXType(QualType(), cxcursor::getCursorASTUnit(C));
4525
4526 IBOutletCollectionAttr *A =
4527 cast<IBOutletCollectionAttr>(cxcursor::getCursorAttr(C));
4528
4529 return cxtype::MakeCXType(A->getInterface(), cxcursor::getCursorASTUnit(C));
4530}
4531} // end: extern "C"
4532
4533//===----------------------------------------------------------------------===//
Ted Kremenekfb480492010-01-13 21:46:36 +00004534// CXString Operations.
4535//===----------------------------------------------------------------------===//
4536
4537extern "C" {
4538const char *clang_getCString(CXString string) {
4539 return string.Spelling;
4540}
4541
4542void clang_disposeString(CXString string) {
4543 if (string.MustFreeString && string.Spelling)
4544 free((void*)string.Spelling);
4545}
Ted Kremenek04bb7162010-01-22 22:44:15 +00004546
Ted Kremenekfb480492010-01-13 21:46:36 +00004547} // end: extern "C"
Ted Kremenek04bb7162010-01-22 22:44:15 +00004548
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004549namespace clang { namespace cxstring {
4550CXString createCXString(const char *String, bool DupString){
4551 CXString Str;
4552 if (DupString) {
4553 Str.Spelling = strdup(String);
4554 Str.MustFreeString = 1;
4555 } else {
4556 Str.Spelling = String;
4557 Str.MustFreeString = 0;
4558 }
4559 return Str;
4560}
4561
4562CXString createCXString(llvm::StringRef String, bool DupString) {
4563 CXString Result;
4564 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
4565 char *Spelling = (char *)malloc(String.size() + 1);
4566 memmove(Spelling, String.data(), String.size());
4567 Spelling[String.size()] = 0;
4568 Result.Spelling = Spelling;
4569 Result.MustFreeString = 1;
4570 } else {
4571 Result.Spelling = String.data();
4572 Result.MustFreeString = 0;
4573 }
4574 return Result;
4575}
4576}}
4577
Ted Kremenek04bb7162010-01-22 22:44:15 +00004578//===----------------------------------------------------------------------===//
4579// Misc. utility functions.
4580//===----------------------------------------------------------------------===//
Ted Kremenekf0e23e82010-02-17 00:41:40 +00004581
Daniel Dunbarabdce7a2010-11-05 17:21:46 +00004582/// Default to using an 8 MB stack size on "safety" threads.
4583static unsigned SafetyStackThreadSize = 8 << 20;
Daniel Dunbarbf44c3b2010-11-05 07:19:31 +00004584
4585namespace clang {
4586
4587bool RunSafely(llvm::CrashRecoveryContext &CRC,
4588 void (*Fn)(void*), void *UserData) {
4589 if (unsigned Size = GetSafetyThreadStackSize())
4590 return CRC.RunSafelyOnThread(Fn, UserData, Size);
4591 return CRC.RunSafely(Fn, UserData);
4592}
4593
4594unsigned GetSafetyThreadStackSize() {
4595 return SafetyStackThreadSize;
4596}
4597
4598void SetSafetyThreadStackSize(unsigned Value) {
4599 SafetyStackThreadSize = Value;
4600}
4601
4602}
4603
Ted Kremenek04bb7162010-01-22 22:44:15 +00004604extern "C" {
4605
Ted Kremeneka2a9d6e2010-02-12 22:54:40 +00004606CXString clang_getClangVersion() {
Ted Kremenekee4db4f2010-02-17 00:41:08 +00004607 return createCXString(getClangFullVersion());
Ted Kremenek04bb7162010-01-22 22:44:15 +00004608}
4609
4610} // end: extern "C"