blob: bed9c2f16d44cc6f80b34304e0f4076311b04aa6 [file] [log] [blame]
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnera3fc41d2008-01-04 22:32:30 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
Steve Naroff021ca182008-05-29 21:12:08 +000017#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor0c78ad92010-04-21 19:57:20 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21#include "clang/Edit/Commit.h"
22#include "clang/Edit/Rewriters.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Scope.h"
27#include "clang/Sema/ScopeInfo.h"
28#include "llvm/ADT/SmallString.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000029
Chris Lattnera3fc41d2008-01-04 22:32:30 +000030using namespace clang;
John McCall5f2d5562011-02-03 09:00:02 +000031using namespace sema;
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +000032using llvm::makeArrayRef;
Chris Lattnera3fc41d2008-01-04 22:32:30 +000033
John McCallfaf5fb42010-08-26 23:41:50 +000034ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 Expr **strings,
36 unsigned NumStrings) {
Chris Lattner163ffd22009-02-18 06:48:40 +000037 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
Chris Lattnerd7670d92009-02-18 06:13:04 +000039 // Most ObjC strings are formed out of a single piece. However, we *can*
40 // have strings formed out of multiple @ strings with multiple pptokens in
41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
42 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner163ffd22009-02-18 06:48:40 +000043 StringLiteral *S = Strings[0];
Mike Stump11289f42009-09-09 15:08:12 +000044
Chris Lattnerd7670d92009-02-18 06:13:04 +000045 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
Chris Lattnera3fc41d2008-01-04 22:32:30 +000047 // Concatenate objc strings.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000048 SmallString<128> StrBuf;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000049 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump11289f42009-09-09 15:08:12 +000050
Chris Lattner630970d2009-02-18 05:49:11 +000051 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner163ffd22009-02-18 06:48:40 +000052 S = Strings[i];
Mike Stump11289f42009-09-09 15:08:12 +000053
Douglas Gregorfb65e592011-07-27 05:40:30 +000054 // ObjC strings can't be wide or UTF.
55 if (!S->isAscii()) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000056 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
58 return true;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Benjamin Kramer35b077e2010-08-17 12:54:38 +000061 // Append the string.
62 StrBuf += S->getString();
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner163ffd22009-02-18 06:48:40 +000064 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000066 }
Mike Stump11289f42009-09-09 15:08:12 +000067
Chris Lattner163ffd22009-02-18 06:48:40 +000068 // Create the aggregate string with the appropriate content and location
69 // information.
Benjamin Kramercdac7612014-02-25 12:26:20 +000070 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
71 assert(CAT && "String literal not of constant array type!");
72 QualType StrTy = Context.getConstantArrayType(
73 CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1),
74 CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers());
75 S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii,
76 /*Pascal=*/false, StrTy, &StrLocs[0],
77 StrLocs.size());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000078 }
Ted Kremeneke65b0862012-03-06 20:05:56 +000079
80 return BuildObjCStringLiteral(AtLocs[0], S);
81}
Mike Stump11289f42009-09-09 15:08:12 +000082
Ted Kremeneke65b0862012-03-06 20:05:56 +000083ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner6436fb62009-02-18 06:01:06 +000084 // Verify that this composite string is acceptable for ObjC strings.
85 if (CheckObjCString(S))
Chris Lattnera3fc41d2008-01-04 22:32:30 +000086 return true;
Chris Lattnerfffd6a72009-02-18 06:06:56 +000087
88 // Initialize the constant string interface lazily. This assumes
Steve Naroff54e59452009-04-07 14:18:33 +000089 // the NSString interface is seen in this translation unit. Note: We
90 // don't use NSConstantString, since the runtime team considers this
91 // interface private (even though it appears in the header files).
Chris Lattnerfffd6a72009-02-18 06:06:56 +000092 QualType Ty = Context.getObjCConstantStringInterface();
93 if (!Ty.isNull()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +000094 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikiebbafb8a2012-03-11 07:00:24 +000095 } else if (getLangOpts().NoConstantCFStrings) {
Craig Topperc3ec1492014-05-26 06:22:03 +000096 IdentifierInfo *NSIdent=nullptr;
David Blaikiebbafb8a2012-03-11 07:00:24 +000097 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000098
99 if (StringClass.empty())
100 NSIdent = &Context.Idents.get("NSConstantString");
101 else
102 NSIdent = &Context.Idents.get(StringClass);
103
Ted Kremeneke65b0862012-03-06 20:05:56 +0000104 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian07317632010-04-23 23:19:04 +0000105 LookupOrdinaryName);
106 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
107 Context.setObjCConstantStringInterface(StrIF);
108 Ty = Context.getObjCConstantStringInterface();
109 Ty = Context.getObjCObjectPointerType(Ty);
110 } else {
111 // If there is no NSConstantString interface defined then treat this
112 // as error and recover from it.
113 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
114 << S->getSourceRange();
115 Ty = Context.getObjCIdType();
116 }
Chris Lattner091f6982008-06-21 21:44:18 +0000117 } else {
Patrick Beard0caa3942012-04-19 00:25:12 +0000118 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000119 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000120 LookupOrdinaryName);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000121 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
122 Context.setObjCConstantStringInterface(StrIF);
123 Ty = Context.getObjCConstantStringInterface();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000124 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000125 } else {
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000126 // If there is no NSString interface defined, implicitly declare
127 // a @class NSString; and use that instead. This is to make sure
128 // type of an NSString literal is represented correctly, instead of
129 // being an 'id' type.
130 Ty = Context.getObjCNSStringType();
131 if (Ty.isNull()) {
132 ObjCInterfaceDecl *NSStringIDecl =
133 ObjCInterfaceDecl::Create (Context,
134 Context.getTranslationUnitDecl(),
135 SourceLocation(), NSIdent,
Craig Topperc3ec1492014-05-26 06:22:03 +0000136 nullptr, SourceLocation());
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000137 Ty = Context.getObjCInterfaceType(NSStringIDecl);
138 Context.setObjCNSStringType(Ty);
139 }
140 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000141 }
Chris Lattner091f6982008-06-21 21:44:18 +0000142 }
Mike Stump11289f42009-09-09 15:08:12 +0000143
Ted Kremeneke65b0862012-03-06 20:05:56 +0000144 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
145}
146
Jordy Rose08e500c2012-05-12 17:32:44 +0000147/// \brief Emits an error if the given method does not exist, or if the return
148/// type is not an Objective-C object.
149static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
150 const ObjCInterfaceDecl *Class,
151 Selector Sel, const ObjCMethodDecl *Method) {
152 if (!Method) {
153 // FIXME: Is there a better way to avoid quotes than using getName()?
154 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
155 return false;
156 }
157
158 // Make sure the return type is reasonable.
Alp Toker314cc812014-01-25 16:55:45 +0000159 QualType ReturnType = Method->getReturnType();
Jordy Rose08e500c2012-05-12 17:32:44 +0000160 if (!ReturnType->isObjCObjectPointerType()) {
161 S.Diag(Loc, diag::err_objc_literal_method_sig)
162 << Sel;
163 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
164 << ReturnType;
165 return false;
166 }
167
168 return true;
169}
170
Ted Kremeneke65b0862012-03-06 20:05:56 +0000171/// \brief Retrieve the NSNumber factory method that should be used to create
172/// an Objective-C literal for the given type.
173static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000174 QualType NumberType,
175 bool isLiteral = false,
176 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000177 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
178 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
179
Ted Kremeneke65b0862012-03-06 20:05:56 +0000180 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000181 if (isLiteral) {
182 S.Diag(Loc, diag::err_invalid_nsnumber_type)
183 << NumberType << R;
184 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000186 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000187
Ted Kremeneke65b0862012-03-06 20:05:56 +0000188 // If we already looked up this method, we're done.
189 if (S.NSNumberLiteralMethods[*Kind])
190 return S.NSNumberLiteralMethods[*Kind];
191
192 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
193 /*Instance=*/false);
194
Patrick Beard0caa3942012-04-19 00:25:12 +0000195 ASTContext &CX = S.Context;
196
197 // Look up the NSNumber class, if we haven't done so already. It's cached
198 // in the Sema instance.
199 if (!S.NSNumberDecl) {
Jordy Roseaca01f92012-05-12 17:32:52 +0000200 IdentifierInfo *NSNumberId =
201 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
Patrick Beard0caa3942012-04-19 00:25:12 +0000202 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
203 Loc, Sema::LookupOrdinaryName);
204 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
205 if (!S.NSNumberDecl) {
206 if (S.getLangOpts().DebuggerObjCLiteral) {
207 // Create a stub definition of NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000208 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
209 CX.getTranslationUnitDecl(),
210 SourceLocation(), NSNumberId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000211 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000212 } else {
213 // Otherwise, require a declaration of NSNumber.
214 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000215 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000216 }
217 } else if (!S.NSNumberDecl->hasDefinition()) {
218 S.Diag(Loc, diag::err_undeclared_nsnumber);
Craig Topperc3ec1492014-05-26 06:22:03 +0000219 return nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000220 }
221
222 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000223 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
224 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000225 }
226
Ted Kremeneke65b0862012-03-06 20:05:56 +0000227 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000228 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000229 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000230 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000231 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000232 Method =
233 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
234 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
235 /*isInstance=*/false, /*isVariadic=*/false,
236 /*isPropertyAccessor=*/false,
237 /*isImplicitlyDeclared=*/true,
238 /*isDefined=*/false, ObjCMethodDecl::Required,
239 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000240 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
241 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000242 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000243 NumberType, /*TInfo=*/nullptr,
244 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000245 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000246 }
247
Jordy Rose08e500c2012-05-12 17:32:44 +0000248 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000249 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000250
251 // Note: if the parameter type is out-of-line, we'll catch it later in the
252 // implicit conversion.
253
254 S.NSNumberLiteralMethods[*Kind] = Method;
255 return Method;
256}
257
Patrick Beard0caa3942012-04-19 00:25:12 +0000258/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
259/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000260ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000261 // Determine the type of the literal.
262 QualType NumberType = Number->getType();
263 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
264 // In C, character literals have type 'int'. That's not the type we want
265 // to use to determine the Objective-c literal kind.
266 switch (Char->getKind()) {
267 case CharacterLiteral::Ascii:
268 NumberType = Context.CharTy;
269 break;
270
271 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000272 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000273 break;
274
275 case CharacterLiteral::UTF16:
276 NumberType = Context.Char16Ty;
277 break;
278
279 case CharacterLiteral::UTF32:
280 NumberType = Context.Char32Ty;
281 break;
282 }
283 }
284
Ted Kremeneke65b0862012-03-06 20:05:56 +0000285 // Look for the appropriate method within NSNumber.
286 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000287 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000288 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000289 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000290 if (!Method)
291 return ExprError();
292
293 // Convert the number to the type that the parameter expects.
Alp Toker03376dc2014-07-07 09:02:20 +0000294 ParmVarDecl *ParamDecl = Method->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000295 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
296 ParamDecl);
297 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
298 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000299 Number);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000300 if (ConvertedNumber.isInvalid())
301 return ExprError();
302 Number = ConvertedNumber.get();
303
Patrick Beard2565c592012-05-01 21:47:19 +0000304 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000305 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000306 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
307 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000308}
309
310ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
311 SourceLocation ValueLoc,
312 bool Value) {
313 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000314 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000315 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
316 } else {
317 // C doesn't actually have a way to represent literal values of type
318 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
319 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
320 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
321 CK_IntegralToBoolean);
322 }
323
324 return BuildObjCNumericLiteral(AtLoc, Inner.get());
325}
326
327/// \brief Check that the given expression is a valid element of an Objective-C
328/// collection literal.
329static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000330 QualType T,
331 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000332 // If the expression is type-dependent, there's nothing for us to do.
333 if (Element->isTypeDependent())
334 return Element;
335
336 ExprResult Result = S.CheckPlaceholderExpr(Element);
337 if (Result.isInvalid())
338 return ExprError();
339 Element = Result.get();
340
341 // In C++, check for an implicit conversion to an Objective-C object pointer
342 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000343 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000344 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000345 = InitializedEntity::InitializeParameter(S.Context, T,
346 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000347 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000348 = InitializationKind::CreateCopy(Element->getLocStart(),
349 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000350 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000351 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000352 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000353 }
354
355 Expr *OrigElement = Element;
356
357 // Perform lvalue-to-rvalue conversion.
358 Result = S.DefaultLvalueConversion(Element);
359 if (Result.isInvalid())
360 return ExprError();
361 Element = Result.get();
362
363 // Make sure that we have an Objective-C pointer type or block.
364 if (!Element->getType()->isObjCObjectPointerType() &&
365 !Element->getType()->isBlockPointerType()) {
366 bool Recovered = false;
367
368 // If this is potentially an Objective-C numeric literal, add the '@'.
369 if (isa<IntegerLiteral>(OrigElement) ||
370 isa<CharacterLiteral>(OrigElement) ||
371 isa<FloatingLiteral>(OrigElement) ||
372 isa<ObjCBoolLiteralExpr>(OrigElement) ||
373 isa<CXXBoolLiteralExpr>(OrigElement)) {
374 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
375 int Which = isa<CharacterLiteral>(OrigElement) ? 1
376 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
377 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
378 : 3;
379
380 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
381 << Which << OrigElement->getSourceRange()
382 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
383
384 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
385 OrigElement);
386 if (Result.isInvalid())
387 return ExprError();
388
389 Element = Result.get();
390 Recovered = true;
391 }
392 }
393 // If this is potentially an Objective-C string literal, add the '@'.
394 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
395 if (String->isAscii()) {
396 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
397 << 0 << OrigElement->getSourceRange()
398 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
399
400 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
401 if (Result.isInvalid())
402 return ExprError();
403
404 Element = Result.get();
405 Recovered = true;
406 }
407 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000408
Ted Kremeneke65b0862012-03-06 20:05:56 +0000409 if (!Recovered) {
410 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
411 << Element->getType();
412 return ExprError();
413 }
414 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000415 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000416 if (ObjCStringLiteral *getString =
417 dyn_cast<ObjCStringLiteral>(OrigElement)) {
418 if (StringLiteral *SL = getString->getString()) {
419 unsigned numConcat = SL->getNumConcatenated();
420 if (numConcat > 1) {
421 // Only warn if the concatenated string doesn't come from a macro.
422 bool hasMacro = false;
423 for (unsigned i = 0; i < numConcat ; ++i)
424 if (SL->getStrTokenLoc(i).isMacroID()) {
425 hasMacro = true;
426 break;
427 }
428 if (!hasMacro)
429 S.Diag(Element->getLocStart(),
430 diag::warn_concatenated_nsarray_literal)
431 << Element->getType();
432 }
433 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000434 }
435
Ted Kremeneke65b0862012-03-06 20:05:56 +0000436 // Make sure that the element has the type that the container factory
437 // function expects.
438 return S.PerformCopyInitialization(
439 InitializedEntity::InitializeParameter(S.Context, T,
440 /*Consumed=*/false),
441 Element->getLocStart(), Element);
442}
443
Patrick Beard0caa3942012-04-19 00:25:12 +0000444ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
445 if (ValueExpr->isTypeDependent()) {
446 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000447 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000448 return BoxedExpr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000449 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000450 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000451 QualType BoxedType;
452 // Convert the expression to an RValue, so we can check for pointer types...
453 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
454 if (RValue.isInvalid()) {
455 return ExprError();
456 }
457 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000458 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000459 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
460 QualType PointeeType = PT->getPointeeType();
461 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
462
463 if (!NSStringDecl) {
464 IdentifierInfo *NSStringId =
465 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
466 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
467 SR.getBegin(), LookupOrdinaryName);
468 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
469 if (!NSStringDecl) {
470 if (getLangOpts().DebuggerObjCLiteral) {
471 // Support boxed expressions in the debugger w/o NSString declaration.
Jordy Roseaca01f92012-05-12 17:32:52 +0000472 DeclContext *TU = Context.getTranslationUnitDecl();
473 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
474 SourceLocation(),
475 NSStringId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000476 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000477 } else {
478 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
479 return ExprError();
480 }
481 } else if (!NSStringDecl->hasDefinition()) {
482 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
483 return ExprError();
484 }
485 assert(NSStringDecl && "NSStringDecl should not be NULL");
Jordy Roseaca01f92012-05-12 17:32:52 +0000486 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
487 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000488 }
489
490 if (!StringWithUTF8StringMethod) {
491 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
492 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
493
494 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000495 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
496 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000497 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000498 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000499 ObjCMethodDecl *M = ObjCMethodDecl::Create(
500 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
501 NSStringPointer, ReturnTInfo, NSStringDecl,
502 /*isInstance=*/false, /*isVariadic=*/false,
503 /*isPropertyAccessor=*/false,
504 /*isImplicitlyDeclared=*/true,
505 /*isDefined=*/false, ObjCMethodDecl::Required,
506 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000507 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000508 ParmVarDecl *value =
509 ParmVarDecl::Create(Context, M,
510 SourceLocation(), SourceLocation(),
511 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000512 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000513 /*TInfo=*/nullptr,
514 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000515 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000516 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000517 }
Jordy Rose890f4572012-05-12 15:53:41 +0000518
Jordy Rose08e500c2012-05-12 17:32:44 +0000519 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
520 stringWithUTF8String, BoxingMethod))
521 return ExprError();
522
523 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000524 }
525
526 BoxingMethod = StringWithUTF8StringMethod;
527 BoxedType = NSStringPointer;
528 }
Patrick Beard2565c592012-05-01 21:47:19 +0000529 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000530 // The other types we support are numeric, char and BOOL/bool. We could also
531 // provide limited support for structure types, such as NSRange, NSRect, and
532 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
533 // for more details.
534
535 // Check for a top-level character literal.
536 if (const CharacterLiteral *Char =
537 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
538 // In C, character literals have type 'int'. That's not the type we want
539 // to use to determine the Objective-c literal kind.
540 switch (Char->getKind()) {
541 case CharacterLiteral::Ascii:
542 ValueType = Context.CharTy;
543 break;
544
545 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000546 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000547 break;
548
549 case CharacterLiteral::UTF16:
550 ValueType = Context.Char16Ty;
551 break;
552
553 case CharacterLiteral::UTF32:
554 ValueType = Context.Char32Ty;
555 break;
556 }
557 }
Fariborz Jahanian5d64abb2014-06-18 20:49:02 +0000558 CheckForIntOverflow(ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000559 // FIXME: Do I need to do anything special with BoolTy expressions?
560
561 // Look for the appropriate method within NSNumber.
562 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
563 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000564
565 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
566 if (!ET->getDecl()->isComplete()) {
567 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
568 << ValueType << ValueExpr->getSourceRange();
569 return ExprError();
570 }
571
572 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
573 ET->getDecl()->getIntegerType());
574 BoxedType = NSNumberPointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000575 }
576
577 if (!BoxingMethod) {
578 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
579 << ValueType << ValueExpr->getSourceRange();
580 return ExprError();
581 }
582
583 // Convert the expression to the type that the parameter requires.
Alp Toker03376dc2014-07-07 09:02:20 +0000584 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000585 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
586 ParamDecl);
587 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
588 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000589 ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000590 if (ConvertedValueExpr.isInvalid())
591 return ExprError();
592 ValueExpr = ConvertedValueExpr.get();
593
594 ObjCBoxedExpr *BoxedExpr =
595 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
596 BoxingMethod, SR);
597 return MaybeBindToTemporary(BoxedExpr);
598}
599
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000600static ObjCMethodDecl *FindAllocMethod(Sema &S, ObjCInterfaceDecl *NSClass) {
601 ObjCMethodDecl *Method = nullptr;
602 ASTContext &Context = S.Context;
603
604 // Find +[NSClass alloc] method.
605 IdentifierInfo *II = &Context.Idents.get("alloc");
606 Selector AllocSel = Context.Selectors.getSelector(0, &II);
607 Method = NSClass->lookupClassMethod(AllocSel);
608 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
609 Method = ObjCMethodDecl::Create(Context,
610 SourceLocation(), SourceLocation(), AllocSel,
611 Context.getObjCIdType(),
612 nullptr /*TypeSourceInfo */,
613 Context.getTranslationUnitDecl(),
614 false /*Instance*/, false/*isVariadic*/,
615 /*isPropertyAccessor=*/false,
616 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
617 ObjCMethodDecl::Required,
618 false);
619 SmallVector<ParmVarDecl *, 1> Params;
620 Method->setMethodParams(Context, Params, None);
621 }
622 return Method;
623}
624
John McCallf2538342012-07-31 05:14:30 +0000625/// Build an ObjC subscript pseudo-object expression, given that
626/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000627ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
628 Expr *IndexExpr,
629 ObjCMethodDecl *getterMethod,
630 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000631 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000632
John McCallf2538342012-07-31 05:14:30 +0000633 // We can't get dependent types here; our callers should have
634 // filtered them out.
635 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
636 "base or index cannot have dependent type here");
637
638 // Filter out placeholders in the index. In theory, overloads could
639 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000640 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
641 if (Result.isInvalid())
642 return ExprError();
643 IndexExpr = Result.get();
644
John McCallf2538342012-07-31 05:14:30 +0000645 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000646 Result = DefaultLvalueConversion(BaseExpr);
647 if (Result.isInvalid())
648 return ExprError();
649 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000650
651 // Build the pseudo-object expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000652 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
653 Context.PseudoObjectTy, getterMethod,
654 setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000655}
656
657ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000658 bool Arc = getLangOpts().ObjCAutoRefCount;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000659 // Look up the NSArray class, if we haven't done so already.
660 if (!NSArrayDecl) {
661 NamedDecl *IF = LookupSingleName(TUScope,
662 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
663 SR.getBegin(),
664 LookupOrdinaryName);
665 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000666 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000667 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
668 Context.getTranslationUnitDecl(),
669 SourceLocation(),
670 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
Craig Topperc3ec1492014-05-26 06:22:03 +0000671 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000672
673 if (!NSArrayDecl) {
674 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
675 return ExprError();
676 }
677 }
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000678 if (Arc && !ArrayAllocObjectsMethod) {
679 // Find +[NSArray alloc] method.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000680 ArrayAllocObjectsMethod = FindAllocMethod(*this, NSArrayDecl);
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000681 if (!ArrayAllocObjectsMethod) {
682 Diag(SR.getBegin(), diag::err_undeclared_alloc);
683 return ExprError();
684 }
685 }
686 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000687 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000688 if (!ArrayWithObjectsMethod) {
689 Selector
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000690 Sel = NSAPIObj->getNSArraySelector(
691 Arc? NSAPI::NSArr_initWithObjectsCount : NSAPI::NSArr_arrayWithObjectsCount);
692 ObjCMethodDecl *Method =
693 Arc? NSArrayDecl->lookupInstanceMethod(Sel)
694 : NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000695 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000696 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000697 Method = ObjCMethodDecl::Create(
698 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000699 Context.getTranslationUnitDecl(),
700 Arc /*Instance for Arc, Class for MRR*/,
Alp Toker314cc812014-01-25 16:55:45 +0000701 false /*isVariadic*/,
702 /*isPropertyAccessor=*/false,
703 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
704 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000705 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000706 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000707 SourceLocation(),
708 SourceLocation(),
709 &Context.Idents.get("objects"),
710 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000711 /*TInfo=*/nullptr,
712 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000713 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000714 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000715 SourceLocation(),
716 SourceLocation(),
717 &Context.Idents.get("cnt"),
718 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000719 /*TInfo=*/nullptr, SC_None,
720 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000721 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000722 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000723 }
724
Jordy Rose08e500c2012-05-12 17:32:44 +0000725 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000726 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000727
Jordy Rose4af44872012-05-12 17:32:56 +0000728 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000729 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000730 const PointerType *PtrT = T->getAs<PointerType>();
731 if (!PtrT ||
732 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
733 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
734 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000735 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000736 diag::note_objc_literal_method_param)
737 << 0 << T
738 << Context.getPointerType(IdT.withConst());
739 return ExprError();
740 }
741
742 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000743 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000744 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
745 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000746 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000747 diag::note_objc_literal_method_param)
748 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000749 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000750 << "integral";
751 return ExprError();
752 }
753
754 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000755 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000756 }
757
Alp Toker03376dc2014-07-07 09:02:20 +0000758 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000759 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000760
761 // Check that each of the elements provided is valid in a collection literal,
762 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000763 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000764 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
765 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
766 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000767 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000768 if (Converted.isInvalid())
769 return ExprError();
770
771 ElementsBuffer[I] = Converted.get();
772 }
773
774 QualType Ty
775 = Context.getObjCObjectPointerType(
776 Context.getObjCInterfaceType(NSArrayDecl));
777
778 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000779 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000780 ArrayWithObjectsMethod,
781 ArrayAllocObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000782}
783
784ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
785 ObjCDictionaryElement *Elements,
786 unsigned NumElements) {
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000787 bool Arc = getLangOpts().ObjCAutoRefCount;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000788 // Look up the NSDictionary class, if we haven't done so already.
789 if (!NSDictionaryDecl) {
790 NamedDecl *IF = LookupSingleName(TUScope,
791 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
792 SR.getBegin(), LookupOrdinaryName);
793 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000794 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000795 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
796 Context.getTranslationUnitDecl(),
797 SourceLocation(),
798 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
Craig Topperc3ec1492014-05-26 06:22:03 +0000799 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000800
801 if (!NSDictionaryDecl) {
802 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
803 return ExprError();
804 }
805 }
806
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000807 if (Arc && !DictAllocObjectsMethod) {
808 // Find +[NSDictionary alloc] method.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000809 DictAllocObjectsMethod = FindAllocMethod(*this, NSDictionaryDecl);
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000810 if (!DictAllocObjectsMethod) {
811 Diag(SR.getBegin(), diag::err_undeclared_alloc);
812 return ExprError();
813 }
814 }
815
Fariborz Jahaniand45e7ce2014-08-07 20:57:35 +0000816 // Find the dictionaryWithObjects:forKeys:count: or initWithObjects:forKeys:count:
817 // (for arc) method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000818 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000819 if (!DictionaryWithObjectsMethod) {
Fariborz Jahaniand45e7ce2014-08-07 20:57:35 +0000820 Selector Sel =
821 NSAPIObj->getNSDictionarySelector(Arc? NSAPI::NSDict_initWithObjectsForKeysCount
822 : NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
823 ObjCMethodDecl *Method =
824 Arc ? NSDictionaryDecl->lookupInstanceMethod(Sel)
825 : NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000826 if (!Method && getLangOpts().DebuggerObjCLiteral) {
827 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000828 SourceLocation(), SourceLocation(), Sel,
829 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000830 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000831 Context.getTranslationUnitDecl(),
Fariborz Jahaniand45e7ce2014-08-07 20:57:35 +0000832 Arc /*Instance for Arc, Class for MRR*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000833 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000834 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
835 ObjCMethodDecl::Required,
836 false);
837 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000838 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000839 SourceLocation(),
840 SourceLocation(),
841 &Context.Idents.get("objects"),
842 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000843 /*TInfo=*/nullptr, SC_None,
844 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000845 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000846 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000847 SourceLocation(),
848 SourceLocation(),
849 &Context.Idents.get("keys"),
850 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000851 /*TInfo=*/nullptr, SC_None,
852 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000853 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000854 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000855 SourceLocation(),
856 SourceLocation(),
857 &Context.Idents.get("cnt"),
858 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000859 /*TInfo=*/nullptr, SC_None,
860 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000861 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000862 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000863 }
864
Jordy Rose08e500c2012-05-12 17:32:44 +0000865 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
866 Method))
867 return ExprError();
868
Jordy Rose4af44872012-05-12 17:32:56 +0000869 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000870 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000871 const PointerType *PtrValue = ValueT->getAs<PointerType>();
872 if (!PtrValue ||
873 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000874 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000875 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000876 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000877 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000878 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000879 << Context.getPointerType(IdT.withConst());
880 return ExprError();
881 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000882
Jordy Rose4af44872012-05-12 17:32:56 +0000883 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000884 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000885 const PointerType *PtrKey = KeyT->getAs<PointerType>();
886 if (!PtrKey ||
887 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
888 IdT)) {
889 bool err = true;
890 if (PtrKey) {
891 if (QIDNSCopying.isNull()) {
892 // key argument of selector is id<NSCopying>?
893 if (ObjCProtocolDecl *NSCopyingPDecl =
894 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
895 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
896 QIDNSCopying =
897 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
898 (ObjCProtocolDecl**) PQ,1);
899 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
900 }
901 }
902 if (!QIDNSCopying.isNull())
903 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
904 QIDNSCopying);
905 }
906
907 if (err) {
908 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
909 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000910 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000911 diag::note_objc_literal_method_param)
912 << 1 << KeyT
913 << Context.getPointerType(IdT.withConst());
914 return ExprError();
915 }
916 }
917
918 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000919 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000920 if (!CountType->isIntegerType()) {
921 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
922 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000923 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000924 diag::note_objc_literal_method_param)
925 << 2 << CountType
926 << "integral";
927 return ExprError();
928 }
929
930 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
931 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000932 }
933
Alp Toker03376dc2014-07-07 09:02:20 +0000934 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000935 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +0000936 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000937 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
938
Ted Kremeneke65b0862012-03-06 20:05:56 +0000939 // Check that each of the keys and values provided is valid in a collection
940 // literal, performing conversions as necessary.
941 bool HasPackExpansions = false;
942 for (unsigned I = 0, N = NumElements; I != N; ++I) {
943 // Check the key.
944 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
945 KeyT);
946 if (Key.isInvalid())
947 return ExprError();
948
949 // Check the value.
950 ExprResult Value
951 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
952 if (Value.isInvalid())
953 return ExprError();
954
955 Elements[I].Key = Key.get();
956 Elements[I].Value = Value.get();
957
958 if (Elements[I].EllipsisLoc.isInvalid())
959 continue;
960
961 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
962 !Elements[I].Value->containsUnexpandedParameterPack()) {
963 Diag(Elements[I].EllipsisLoc,
964 diag::err_pack_expansion_without_parameter_packs)
965 << SourceRange(Elements[I].Key->getLocStart(),
966 Elements[I].Value->getLocEnd());
967 return ExprError();
968 }
969
970 HasPackExpansions = true;
971 }
972
973
974 QualType Ty
975 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +0000976 Context.getObjCInterfaceType(NSDictionaryDecl));
977 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
978 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
Fariborz Jahanian2a25dba2014-08-06 23:40:31 +0000979 DictionaryWithObjectsMethod, DictAllocObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000980}
981
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000982ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +0000983 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +0000984 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +0000985 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +0000986 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +0000987 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +0000988 StrTy = Context.DependentTy;
989 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +0000990 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
991 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000992 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000993 diag::err_incomplete_type_objc_at_encode,
994 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000995 return ExprError();
996
Anders Carlsson315d2292009-06-07 18:45:35 +0000997 std::string Str;
998 Context.getObjCEncodingForType(EncodedType, Str);
999
1000 // The type of @encode is the same as the type of the corresponding string,
1001 // which is an array type.
1002 StrTy = Context.CharTy;
1003 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001004 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +00001005 StrTy.addConst();
1006 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
1007 ArrayType::Normal, 0);
1008 }
Mike Stump11289f42009-09-09 15:08:12 +00001009
Douglas Gregorabd9e962010-04-20 15:39:42 +00001010 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +00001011}
1012
John McCallfaf5fb42010-08-26 23:41:50 +00001013ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
1014 SourceLocation EncodeLoc,
1015 SourceLocation LParenLoc,
1016 ParsedType ty,
1017 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +00001018 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +00001019 TypeSourceInfo *TInfo;
1020 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
1021 if (!TInfo)
1022 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
1023 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001024
Douglas Gregorabd9e962010-04-20 15:39:42 +00001025 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001026}
1027
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001028static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
1029 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001030 SourceLocation LParenLoc,
1031 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001032 ObjCMethodDecl *Method,
1033 ObjCMethodList &MethList) {
1034 ObjCMethodList *M = &MethList;
1035 bool Warned = false;
1036 for (M = M->getNext(); M; M=M->getNext()) {
1037 ObjCMethodDecl *MatchingMethodDecl = M->Method;
1038 if (MatchingMethodDecl == Method ||
1039 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
1040 MatchingMethodDecl->getSelector() != Method->getSelector())
1041 continue;
1042 if (!S.MatchTwoMethodDeclarations(Method,
1043 MatchingMethodDecl, Sema::MMS_loose)) {
1044 if (!Warned) {
1045 Warned = true;
1046 S.Diag(AtLoc, diag::warning_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001047 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1048 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001049 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1050 << Method->getDeclName();
1051 }
1052 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1053 << MatchingMethodDecl->getDeclName();
1054 }
1055 }
1056 return Warned;
1057}
1058
1059static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001060 ObjCMethodDecl *Method,
1061 SourceLocation LParenLoc,
1062 SourceLocation RParenLoc,
1063 bool WarnMultipleSelectors) {
1064 if (!WarnMultipleSelectors ||
1065 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001066 return;
1067 bool Warned = false;
1068 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1069 e = S.MethodPool.end(); b != e; b++) {
1070 // first, instance methods
1071 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001072 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001073 Method, InstMethList))
1074 Warned = true;
1075
1076 // second, class methods
1077 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001078 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1079 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001080 return;
1081 }
1082}
1083
John McCallfaf5fb42010-08-26 23:41:50 +00001084ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1085 SourceLocation AtLoc,
1086 SourceLocation SelLoc,
1087 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001088 SourceLocation RParenLoc,
1089 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001090 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1091 SourceRange(LParenLoc, RParenLoc), false, false);
1092 if (!Method)
1093 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001094 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001095 if (!Method) {
1096 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1097 Selector MatchedSel = OM->getSelector();
1098 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1099 RParenLoc.getLocWithOffset(-1));
1100 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1101 << Sel << MatchedSel
1102 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1103
1104 } else
1105 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001106 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001107 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1108 WarnMultipleSelectors);
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001109
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001110 if (Method &&
1111 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
1112 !getSourceManager().isInSystemHeader(Method->getLocation())) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001113 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
1114 = ReferencedSelectors.find(Sel);
1115 if (Pos == ReferencedSelectors.end())
1116 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian9a881012011-07-13 19:05:43 +00001117 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001118
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001119 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001120 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001121 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001122 switch (Sel.getMethodFamily()) {
1123 case OMF_retain:
1124 case OMF_release:
1125 case OMF_autorelease:
1126 case OMF_retainCount:
1127 case OMF_dealloc:
1128 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1129 Sel << SourceRange(LParenLoc, RParenLoc);
1130 break;
1131
1132 case OMF_None:
1133 case OMF_alloc:
1134 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001135 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001136 case OMF_init:
1137 case OMF_mutableCopy:
1138 case OMF_new:
1139 case OMF_self:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001140 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001141 break;
1142 }
1143 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001144 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001145 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001146}
1147
John McCallfaf5fb42010-08-26 23:41:50 +00001148ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1149 SourceLocation AtLoc,
1150 SourceLocation ProtoLoc,
1151 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001152 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001153 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001154 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001155 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001156 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001157 return true;
1158 }
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001159 if (PDecl->hasDefinition())
1160 PDecl = PDecl->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00001161
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001162 QualType Ty = Context.getObjCProtoType();
1163 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001164 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001165 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001166 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001167}
1168
John McCall5f2d5562011-02-03 09:00:02 +00001169/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001170ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1171 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001172
1173 // If we're not in an ObjC method, error out. Note that, unlike the
1174 // C++ case, we don't require an instance method --- class methods
1175 // still have a 'self', and we really do still need to capture it!
1176 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1177 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001178 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001179
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001180 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001181
1182 return method;
1183}
1184
Douglas Gregor64910ca2011-09-09 20:05:21 +00001185static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1186 if (T == Context.getObjCInstanceType())
1187 return Context.getObjCIdType();
1188
1189 return T;
1190}
1191
Douglas Gregor33823722011-06-11 01:09:30 +00001192QualType Sema::getMessageSendResultType(QualType ReceiverType,
1193 ObjCMethodDecl *Method,
1194 bool isClassMessage, bool isSuperMessage) {
1195 assert(Method && "Must have a method");
1196 if (!Method->hasRelatedResultType())
1197 return Method->getSendResultType();
1198
1199 // If a method has a related return type:
1200 // - if the method found is an instance method, but the message send
1201 // was a class message send, T is the declared return type of the method
1202 // found
1203 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001204 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001205
1206 // - if the receiver is super, T is a pointer to the class of the
1207 // enclosing method definition
1208 if (isSuperMessage) {
1209 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1210 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1211 return Context.getObjCObjectPointerType(
1212 Context.getObjCInterfaceType(Class));
1213 }
1214
1215 // - if the receiver is the name of a class U, T is a pointer to U
1216 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1217 ReceiverType->isObjCQualifiedInterfaceType())
1218 return Context.getObjCObjectPointerType(ReceiverType);
1219 // - if the receiver is of type Class or qualified Class type,
1220 // T is the declared return type of the method.
1221 if (ReceiverType->isObjCClassType() ||
1222 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001223 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001224
1225 // - if the receiver is id, qualified id, Class, or qualified Class, T
1226 // is the receiver type, otherwise
1227 // - T is the type of the receiver expression.
1228 return ReceiverType;
1229}
John McCall5f2d5562011-02-03 09:00:02 +00001230
John McCall5ec7e7d2013-03-19 07:04:25 +00001231/// Look for an ObjC method whose result type exactly matches the given type.
1232static const ObjCMethodDecl *
1233findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1234 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001235 if (MD->getReturnType() == instancetype)
1236 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001237
1238 // For these purposes, a method in an @implementation overrides a
1239 // declaration in the @interface.
1240 if (const ObjCImplDecl *impl =
1241 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1242 const ObjCContainerDecl *iface;
1243 if (const ObjCCategoryImplDecl *catImpl =
1244 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1245 iface = catImpl->getCategoryDecl();
1246 } else {
1247 iface = impl->getClassInterface();
1248 }
1249
1250 const ObjCMethodDecl *ifaceMD =
1251 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1252 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1253 }
1254
1255 SmallVector<const ObjCMethodDecl *, 4> overrides;
1256 MD->getOverriddenMethods(overrides);
1257 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1258 if (const ObjCMethodDecl *result =
1259 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1260 return result;
1261 }
1262
Craig Topperc3ec1492014-05-26 06:22:03 +00001263 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001264}
1265
1266void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1267 // Only complain if we're in an ObjC method and the required return
1268 // type doesn't match the method's declared return type.
1269 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1270 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001271 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001272 return;
1273
1274 // Look for a method overridden by this method which explicitly uses
1275 // 'instancetype'.
1276 if (const ObjCMethodDecl *overridden =
1277 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001278 SourceRange range = overridden->getReturnTypeSourceRange();
1279 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001280 if (loc.isInvalid())
1281 loc = overridden->getLocation();
1282 Diag(loc, diag::note_related_result_type_explicit)
1283 << /*current method*/ 1 << range;
1284 return;
1285 }
1286
1287 // Otherwise, if we have an interesting method family, note that.
1288 // This should always trigger if the above didn't.
1289 if (ObjCMethodFamily family = MD->getMethodFamily())
1290 Diag(MD->getLocation(), diag::note_related_result_type_family)
1291 << /*current method*/ 1
1292 << family;
1293}
1294
Douglas Gregor33823722011-06-11 01:09:30 +00001295void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1296 E = E->IgnoreParenImpCasts();
1297 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1298 if (!MsgSend)
1299 return;
1300
1301 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1302 if (!Method)
1303 return;
1304
1305 if (!Method->hasRelatedResultType())
1306 return;
Alp Toker314cc812014-01-25 16:55:45 +00001307
1308 if (Context.hasSameUnqualifiedType(
1309 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001310 return;
Alp Toker314cc812014-01-25 16:55:45 +00001311
1312 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001313 Context.getObjCInstanceType()))
1314 return;
1315
Douglas Gregor33823722011-06-11 01:09:30 +00001316 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1317 << Method->isInstanceMethod() << Method->getSelector()
1318 << MsgSend->getType();
1319}
1320
1321bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001322 MultiExprArg Args,
1323 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001324 ArrayRef<SourceLocation> SelectorLocs,
1325 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001326 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001327 SourceLocation lbrac, SourceLocation rbrac,
John McCall7decc9e2010-11-18 06:31:45 +00001328 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001329 SourceLocation SelLoc;
1330 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1331 SelLoc = SelectorLocs.front();
1332 else
1333 SelLoc = lbrac;
1334
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001335 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001336 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001337 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001338 if (Args[i]->isTypeDependent())
1339 continue;
1340
John McCallcc5788c2013-03-04 07:34:02 +00001341 ExprResult result;
1342 if (getLangOpts().DebuggerSupport) {
1343 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001344 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001345 } else {
1346 result = DefaultArgumentPromotion(Args[i]);
1347 }
1348 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001349 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001350 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001351 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001352
John McCall31168b02011-06-15 23:02:42 +00001353 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001354 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001355 DiagID = diag::err_arc_method_not_found;
1356 else
1357 DiagID = isClassMessage ? diag::warn_class_method_not_found
1358 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001359 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001360 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001361 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001362 if (getLangOpts().ObjCAutoRefCount)
1363 DiagID = diag::error_method_not_found_with_typo;
1364 else
1365 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1366 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001367 Selector MatchedSel = OMD->getSelector();
1368 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001369 Diag(SelLoc, DiagID)
1370 << Sel<< isClassMessage << MatchedSel
Fariborz Jahanian75481672013-06-17 17:10:54 +00001371 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1372 }
1373 else
1374 Diag(SelLoc, DiagID)
1375 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001376 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001377 // Find the class to which we are sending this message.
1378 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian478536b2013-05-15 15:27:35 +00001379 if (ObjCInterfaceDecl *Class =
1380 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl())
1381 Diag(Class->getLocation(), diag::note_receiver_class_declared);
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001382 }
1383 }
John McCall3f4138c2011-07-13 17:56:40 +00001384
1385 // In debuggers, we want to use __unknown_anytype for these
1386 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001387 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001388 ReturnType = Context.UnknownAnyTy;
1389 } else {
1390 ReturnType = Context.getObjCIdType();
1391 }
John McCall7decc9e2010-11-18 06:31:45 +00001392 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001393 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001394 }
Mike Stump11289f42009-09-09 15:08:12 +00001395
Douglas Gregor33823722011-06-11 01:09:30 +00001396 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1397 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001398 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001399
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001400 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001401 // Method might have more arguments than selector indicates. This is due
1402 // to addition of c-style arguments in method.
1403 if (Method->param_size() > Sel.getNumArgs())
1404 NumNamedArgs = Method->param_size();
1405 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001406 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001407 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001408 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001409 return false;
1410 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001411
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001412 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001413 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001414 // We can't do any type-checking on a type-dependent argument.
1415 if (Args[i]->isTypeDependent())
1416 continue;
1417
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001418 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001419
Alp Toker03376dc2014-07-07 09:02:20 +00001420 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001421 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001422
John McCall4124c492011-10-17 18:40:02 +00001423 // Strip the unbridged-cast placeholder expression off unless it's
1424 // a consumed argument.
1425 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1426 !param->hasAttr<CFConsumedAttr>())
1427 argExpr = stripARCUnbridgedCast(argExpr);
1428
John McCallea0a39e2012-11-14 00:49:39 +00001429 // If the parameter is __unknown_anytype, infer its type
1430 // from the argument.
1431 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001432 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001433 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001434 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001435 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001436 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001437 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001438
John McCallcc5788c2013-03-04 07:34:02 +00001439 // Update the parameter type in-place.
1440 param->setType(paramType);
1441 }
1442 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001443 }
1444
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001445 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001446 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001447 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001448 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001449
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001450 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001451 param);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001452 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001453 if (ArgE.isInvalid())
1454 IsError = true;
1455 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001456 Args[i] = ArgE.getAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001457 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001458
1459 // Promote additional arguments to variadic methods.
1460 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001461 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001462 if (Args[i]->isTypeDependent())
1463 continue;
1464
Jordy Roseaca01f92012-05-12 17:32:52 +00001465 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001466 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001467 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001468 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001469 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001470 } else {
1471 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001472 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001473 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001474 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001475 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001476 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001477 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001478 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001479 }
1480 }
1481
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001482 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001483
1484 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001485 IsError |= CheckObjCMethodCall(
Robert Wilhelm88e02492013-08-19 07:57:02 +00001486 Method, SelLoc, makeArrayRef<const Expr *>(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001487
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001488 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001489}
1490
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001491bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001492 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001493 ObjCMethodDecl *Method =
1494 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1495 return isSelfExpr(RExpr, Method);
1496}
1497
1498bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001499 if (!method) return false;
1500
John McCall31168b02011-06-15 23:02:42 +00001501 receiver = receiver->IgnoreParenLValueCasts();
1502 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001503 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001504 return true;
1505 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001506}
1507
John McCall526ab472011-10-25 17:37:35 +00001508/// LookupMethodInType - Look up a method in an ObjCObjectType.
1509ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1510 bool isInstance) {
1511 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1512 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1513 // Look it up in the main interface (and categories, etc.)
1514 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1515 return method;
1516
1517 // Okay, look for "private" methods declared in any
1518 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001519 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1520 return method;
John McCall526ab472011-10-25 17:37:35 +00001521 }
1522
1523 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001524 for (const auto *I : objType->quals())
1525 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001526 return method;
1527
Craig Topperc3ec1492014-05-26 06:22:03 +00001528 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001529}
1530
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001531/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1532/// list of a qualified objective pointer type.
1533ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1534 const ObjCObjectPointerType *OPT,
1535 bool Instance)
1536{
Craig Topperc3ec1492014-05-26 06:22:03 +00001537 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001538 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001539 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1540 return MD;
1541 }
1542 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001543 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001544}
1545
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001546static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1547 if (!Receiver)
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001548 return;
1549
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001550 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1551 Receiver = OVE->getSourceExpr();
1552
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001553 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1554 SourceLocation Loc = RExpr->getLocStart();
1555 QualType T = RExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00001556 const ObjCPropertyDecl *PDecl = nullptr;
1557 const ObjCMethodDecl *GDecl = nullptr;
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001558 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1559 RExpr = POE->getSyntacticForm();
1560 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1561 if (PRE->isImplicitProperty()) {
1562 GDecl = PRE->getImplicitPropertyGetter();
1563 if (GDecl) {
Alp Toker314cc812014-01-25 16:55:45 +00001564 T = GDecl->getReturnType();
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001565 }
1566 }
1567 else {
1568 PDecl = PRE->getExplicitProperty();
1569 if (PDecl) {
1570 T = PDecl->getType();
1571 }
1572 }
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001573 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001574 }
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001575 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1576 // See if receiver is a method which envokes a synthesized getter
1577 // backing a 'weak' property.
1578 ObjCMethodDecl *Method = ME->getMethodDecl();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001579 if (Method && Method->getSelector().getNumArgs() == 0) {
1580 PDecl = Method->findPropertyDecl();
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001581 if (PDecl)
1582 T = PDecl->getType();
1583 }
1584 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001585
Jordan Rose13d6b712012-09-28 22:21:42 +00001586 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1587 if (!PDecl)
1588 return;
1589 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1590 return;
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001591 }
Jordan Rose13d6b712012-09-28 22:21:42 +00001592
1593 S.Diag(Loc, diag::warn_receiver_is_weak)
1594 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1595
1596 if (PDecl)
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001597 S.Diag(PDecl->getLocation(), diag::note_property_declare);
Jordan Rose13d6b712012-09-28 22:21:42 +00001598 else if (GDecl)
1599 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1600
1601 S.Diag(Loc, diag::note_arc_assign_to_strong);
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001602}
1603
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001604/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1605/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001606ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001607HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001608 Expr *BaseExpr, SourceLocation OpLoc,
1609 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001610 SourceLocation MemberLoc,
1611 SourceLocation SuperLoc, QualType SuperType,
1612 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001613 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1614 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001615
Benjamin Kramer365082d2012-05-19 16:34:46 +00001616 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001617 Diag(MemberLoc, diag::err_invalid_property_name)
1618 << MemberName << QualType(OPT, 0);
1619 return ExprError();
1620 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001621
1622 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001623
Douglas Gregor4123a862011-11-14 22:10:01 +00001624 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1625 : BaseExpr->getSourceRange();
1626 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001627 diag::err_property_not_found_forward_class,
1628 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001629 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001630
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001631 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001632 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001633 // Check whether we can reference this property.
1634 if (DiagnoseUseOfDecl(PD, MemberLoc))
1635 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001636 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001637 return new (Context)
1638 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1639 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001640 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001641 return new (Context)
1642 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1643 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001644 }
1645 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001646 for (const auto *I : OPT->quals())
1647 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001648 // Check whether we can reference this property.
1649 if (DiagnoseUseOfDecl(PD, MemberLoc))
1650 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001651
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001652 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001653 return new (Context) ObjCPropertyRefExpr(
1654 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1655 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001656 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001657 return new (Context)
1658 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1659 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001660 }
1661 // If that failed, look for an "implicit" property by seeing if the nullary
1662 // selector is implemented.
1663
1664 // FIXME: The logic for looking up nullary and unary selectors should be
1665 // shared with the code in ActOnInstanceMessage.
1666
1667 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1668 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001669
1670 // May be founf in property's qualified list.
1671 if (!Getter)
1672 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001673
1674 // If this reference is in an @implementation, check for 'private' methods.
1675 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001676 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001677
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001678 if (Getter) {
1679 // Check if we can reference this property.
1680 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1681 return ExprError();
1682 }
1683 // If we found a getter then this may be a valid dot-reference, we
1684 // will look for the matching setter, in case it is needed.
1685 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001686 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1687 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001688 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001689
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001690 // May be founf in property's qualified list.
1691 if (!Setter)
1692 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1693
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001694 if (!Setter) {
1695 // If this reference is in an @implementation, also check for 'private'
1696 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001697 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001698 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001699
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001700 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1701 return ExprError();
1702
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001703 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001704 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001705 return new (Context)
1706 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1707 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001708 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001709 return new (Context)
1710 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1711 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001712
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001713 }
1714
1715 // Attempt to correct for typos in property names.
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001716 DeclFilterCCC<ObjCPropertyDecl> Validator;
1717 if (TypoCorrection Corrected = CorrectTypo(
Craig Topperc3ec1492014-05-26 06:22:03 +00001718 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName,
1719 nullptr, nullptr, Validator, CTK_ErrorRecovery, IFace, false, OPT)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001720 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1721 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001722 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001723 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1724 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001725 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001726 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001727 ObjCInterfaceDecl *ClassDeclared;
1728 if (ObjCIvarDecl *Ivar =
1729 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1730 QualType T = Ivar->getType();
1731 if (const ObjCObjectPointerType * OBJPT =
1732 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001733 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001734 diag::err_property_not_as_forward_class,
1735 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001736 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001737 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001738 Diag(MemberLoc,
1739 diag::err_ivar_access_using_property_syntax_suggest)
1740 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1741 << FixItHint::CreateReplacement(OpLoc, "->");
1742 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001743 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001744
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001745 Diag(MemberLoc, diag::err_property_not_found)
1746 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001747 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001748 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001749 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001750 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001751}
1752
1753
1754
John McCalldadc5752010-08-24 06:29:42 +00001755ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001756ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1757 IdentifierInfo &propertyName,
1758 SourceLocation receiverNameLoc,
1759 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001760
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001761 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001762 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1763 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001764
1765 bool IsSuper = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001766 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001767 // If the "receiver" is 'super' in a method, handle it as an expression-like
1768 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001769 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001770 IsSuper = true;
1771
Eli Friedman24af8502012-02-03 22:47:37 +00001772 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001773 if (CurMethod->isInstanceMethod()) {
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001774 ObjCInterfaceDecl *Super =
1775 CurMethod->getClassInterface()->getSuperClass();
1776 if (!Super) {
1777 // The current class does not have a superclass.
1778 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1779 << CurMethod->getClassInterface()->getIdentifier();
1780 return ExprError();
1781 }
1782 QualType T = Context.getObjCInterfaceType(Super);
Chris Lattnera36ec422010-04-11 08:28:14 +00001783 T = Context.getObjCObjectPointerType(T);
Craig Topperc3ec1492014-05-26 06:22:03 +00001784
Chris Lattnera36ec422010-04-11 08:28:14 +00001785 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001786 /*BaseExpr*/nullptr,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001787 SourceLocation()/*OpLoc*/,
1788 &propertyName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001789 propertyNameLoc,
1790 receiverNameLoc, T, true);
Chris Lattnera36ec422010-04-11 08:28:14 +00001791 }
Mike Stump11289f42009-09-09 15:08:12 +00001792
Chris Lattnera36ec422010-04-11 08:28:14 +00001793 // Otherwise, if this is a class method, try dispatching to our
1794 // superclass.
1795 IFace = CurMethod->getClassInterface()->getSuperClass();
1796 }
John McCall5f2d5562011-02-03 09:00:02 +00001797 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001798
1799 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001800 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1801 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001802 return ExprError();
1803 }
1804 }
1805
1806 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001807 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001808 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001809
1810 // If this reference is in an @implementation, check for 'private' methods.
1811 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001812 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001813
1814 if (Getter) {
1815 // FIXME: refactor/share with ActOnMemberReference().
1816 // Check if we can reference this property.
1817 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1818 return ExprError();
1819 }
Mike Stump11289f42009-09-09 15:08:12 +00001820
Steve Naroff9527bbf2009-03-09 21:12:44 +00001821 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001822 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001823 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1824 PP.getSelectorTable(),
1825 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001826
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001827 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001828 if (!Setter) {
1829 // If this reference is in an @implementation, also check for 'private'
1830 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001831 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001832 }
1833 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001834 if (!Setter)
1835 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001836
1837 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1838 return ExprError();
1839
1840 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001841 if (IsSuper)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001842 return new (Context)
1843 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1844 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
1845 Context.getObjCInterfaceType(IFace));
Douglas Gregor33823722011-06-11 01:09:30 +00001846
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001847 return new (Context) ObjCPropertyRefExpr(
1848 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
1849 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001850 }
1851 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1852 << &propertyName << Context.getObjCInterfaceType(IFace));
1853}
1854
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001855namespace {
1856
1857class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1858 public:
1859 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1860 // Determine whether "super" is acceptable in the current context.
1861 if (Method && Method->getClassInterface())
1862 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1863 }
1864
Craig Toppere14c0f82014-03-12 04:55:44 +00001865 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001866 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1867 candidate.isKeyword("super");
1868 }
1869};
1870
1871}
1872
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001873Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001874 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001875 SourceLocation NameLoc,
1876 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001877 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001878 ParsedType &ReceiverType) {
1879 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001880
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001881 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001882 // messaging super. If the identifier is "super" and there is a
1883 // trailing dot, it's an instance message.
1884 if (IsSuper && S->isInObjcMethodScope())
1885 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001886
1887 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1888 LookupName(Result, S);
1889
1890 switch (Result.getResultKind()) {
1891 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001892 // Normal name lookup didn't find anything. If we're in an
1893 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001894 // FIXME: This is a hack. Ivar lookup should be part of normal
1895 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001896 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001897 if (!Method->getClassInterface()) {
1898 // Fall back: let the parser try to parse it as an instance message.
1899 return ObjCInstanceMessage;
1900 }
1901
Douglas Gregorca7136b2010-04-19 20:09:36 +00001902 ObjCInterfaceDecl *ClassDeclared;
1903 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1904 ClassDeclared))
1905 return ObjCInstanceMessage;
1906 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001907
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001908 // Break out; we'll perform typo correction below.
1909 break;
1910
1911 case LookupResult::NotFoundInCurrentInstantiation:
1912 case LookupResult::FoundOverloaded:
1913 case LookupResult::FoundUnresolvedValue:
1914 case LookupResult::Ambiguous:
1915 Result.suppressDiagnostics();
1916 return ObjCInstanceMessage;
1917
1918 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001919 // If the identifier is a class or not, and there is a trailing dot,
1920 // it's an instance message.
1921 if (HasTrailingDot)
1922 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001923 // We found something. If it's a type, then we have a class
1924 // message. Otherwise, it's an instance message.
1925 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001926 QualType T;
1927 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1928 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001929 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001930 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001931 DiagnoseUseOfDecl(Type, NameLoc);
1932 }
1933 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001934 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001935
Douglas Gregore5798dc2010-04-21 20:38:13 +00001936 // We have a class message, and T is the type we're
1937 // messaging. Build source-location information for it.
1938 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001939 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001940 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001941 }
1942 }
1943
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001944 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Kaelyn Uhrain0e238442013-09-27 19:40:08 +00001945 if (TypoCorrection Corrected =
1946 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
Craig Topperc3ec1492014-05-26 06:22:03 +00001947 nullptr, Validator, CTK_ErrorRecovery, nullptr, false,
1948 nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001949 if (Corrected.isKeyword()) {
1950 // If we've found the keyword "super" (the only keyword that would be
1951 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00001952 diagnoseTypo(Corrected,
1953 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001954 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001955 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00001956 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001957 // If we found a declaration, correct when it refers to an Objective-C
1958 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00001959 diagnoseTypo(Corrected,
1960 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001961 QualType T = Context.getObjCInterfaceType(Class);
1962 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1963 ReceiverType = CreateParsedType(T, TSInfo);
1964 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001965 }
1966 }
Richard Smithf9b15102013-08-17 00:46:16 +00001967
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001968 // Fall back: let the parser try to parse it as an instance message.
1969 return ObjCInstanceMessage;
1970}
Steve Naroff9527bbf2009-03-09 21:12:44 +00001971
John McCalldadc5752010-08-24 06:29:42 +00001972ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001973 SourceLocation SuperLoc,
1974 Selector Sel,
1975 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00001976 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001977 SourceLocation RBracLoc,
1978 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001979 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00001980 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00001981 if (!Method) {
1982 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1983 return ExprError();
1984 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001985
Douglas Gregor4fdba132010-04-21 20:01:04 +00001986 ObjCInterfaceDecl *Class = Method->getClassInterface();
1987 if (!Class) {
1988 Diag(SuperLoc, diag::error_no_super_class_message)
1989 << Method->getDeclName();
1990 return ExprError();
1991 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001992
Douglas Gregor4fdba132010-04-21 20:01:04 +00001993 ObjCInterfaceDecl *Super = Class->getSuperClass();
1994 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001995 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00001996 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1997 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001998 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00001999 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002000
Douglas Gregor4fdba132010-04-21 20:01:04 +00002001 // We are in a method whose class has a superclass, so 'super'
2002 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00002003 if (Method->getSelector() == Sel)
2004 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00002005
Jordan Rose2afd6612012-10-19 16:05:26 +00002006 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00002007 // Since we are in an instance method, this is an instance
2008 // message to the superclass instance.
2009 QualType SuperTy = Context.getObjCInterfaceType(Super);
2010 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00002011 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
2012 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002013 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002014 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00002015
2016 // Since we are in a class method, this is a class message to
2017 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00002018 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregor4fdba132010-04-21 20:01:04 +00002019 Context.getObjCInterfaceType(Super),
Craig Topperc3ec1492014-05-26 06:22:03 +00002020 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002021 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002022}
2023
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002024
2025ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
2026 bool isSuperReceiver,
2027 SourceLocation Loc,
2028 Selector Sel,
2029 ObjCMethodDecl *Method,
2030 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002031 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002032 if (!ReceiverType.isNull())
2033 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
2034
2035 return BuildClassMessage(receiverTypeInfo, ReceiverType,
2036 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
2037 Sel, Method, Loc, Loc, Loc, Args,
2038 /*isImplicit=*/true);
2039
2040}
2041
Ted Kremeneke65b0862012-03-06 20:05:56 +00002042static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
2043 unsigned DiagID,
2044 bool (*refactor)(const ObjCMessageExpr *,
2045 const NSAPI &, edit::Commit &)) {
2046 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002047 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00002048 return;
2049
2050 SourceManager &SM = S.SourceMgr;
2051 edit::Commit ECommit(SM, S.LangOpts);
2052 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
2053 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
2054 << Msg->getSelector() << Msg->getSourceRange();
2055 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
2056 if (!ECommit.isCommitable())
2057 return;
2058 for (edit::Commit::edit_iterator
2059 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
2060 const edit::Commit::Edit &Edit = *I;
2061 switch (Edit.Kind) {
2062 case edit::Commit::Act_Insert:
2063 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
2064 Edit.Text,
2065 Edit.BeforePrev));
2066 break;
2067 case edit::Commit::Act_InsertFromRange:
2068 Builder.AddFixItHint(
2069 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
2070 Edit.getInsertFromRange(SM),
2071 Edit.BeforePrev));
2072 break;
2073 case edit::Commit::Act_Remove:
2074 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
2075 break;
2076 }
2077 }
2078 }
2079}
2080
2081static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2082 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2083 edit::rewriteObjCRedundantCallWithLiteral);
2084}
2085
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002086/// \brief Build an Objective-C class message expression.
2087///
2088/// This routine takes care of both normal class messages and
2089/// class messages to the superclass.
2090///
2091/// \param ReceiverTypeInfo Type source information that describes the
2092/// receiver of this message. This may be NULL, in which case we are
2093/// sending to the superclass and \p SuperLoc must be a valid source
2094/// location.
2095
2096/// \param ReceiverType The type of the object receiving the
2097/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2098/// type as that refers to. For a superclass send, this is the type of
2099/// the superclass.
2100///
2101/// \param SuperLoc The location of the "super" keyword in a
2102/// superclass message.
2103///
2104/// \param Sel The selector to which the message is being sent.
2105///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002106/// \param Method The method that this class message is invoking, if
2107/// already known.
2108///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002109/// \param LBracLoc The location of the opening square bracket ']'.
2110///
James Dennettffad8b72012-06-22 08:10:18 +00002111/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002112///
James Dennettffad8b72012-06-22 08:10:18 +00002113/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002114ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002115 QualType ReceiverType,
2116 SourceLocation SuperLoc,
2117 Selector Sel,
2118 ObjCMethodDecl *Method,
2119 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002120 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002121 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002122 MultiExprArg ArgsIn,
2123 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002124 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002125 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002126 if (LBracLoc.isInvalid()) {
2127 Diag(Loc, diag::err_missing_open_square_message_send)
2128 << FixItHint::CreateInsertion(Loc, "[");
2129 LBracLoc = Loc;
2130 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002131 SourceLocation SelLoc;
2132 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2133 SelLoc = SelectorLocs.front();
2134 else
2135 SelLoc = Loc;
2136
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002137 if (ReceiverType->isDependentType()) {
2138 // If the receiver type is dependent, we can't type-check anything
2139 // at this point. Build a dependent expression.
2140 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002141 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002142 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002143 return ObjCMessageExpr::Create(
2144 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2145 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2146 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002147 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002148
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002149 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002150 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002151 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2152 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002153 Diag(Loc, diag::err_invalid_receiver_class_message)
2154 << ReceiverType;
2155 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002156 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002157 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002158 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002159 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002160 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002161 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002162 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002163 SourceRange TypeRange
2164 = SuperLoc.isValid()? SourceRange(SuperLoc)
2165 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002166 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002167 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002168 ? diag::err_arc_receiver_forward_class
2169 : diag::warn_receiver_forward_class),
2170 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002171 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002172 Method = LookupFactoryMethodInGlobalPool(Sel,
2173 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002174 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002175 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2176 << Method->getDeclName();
2177 }
2178 if (!Method)
2179 Method = Class->lookupClassMethod(Sel);
2180
2181 // If we have an implementation in scope, check "private" methods.
2182 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002183 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002184
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002185 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002186 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002187 }
Mike Stump11289f42009-09-09 15:08:12 +00002188
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002189 // Check the argument types and determine the result type.
2190 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002191 ExprValueKind VK = VK_RValue;
2192
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002193 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002194 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002195 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2196 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002197 Method, true,
Douglas Gregor33823722011-06-11 01:09:30 +00002198 SuperLoc.isValid(), LBracLoc, RBracLoc,
2199 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002200 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002201
Alp Toker314cc812014-01-25 16:55:45 +00002202 if (Method && !Method->getReturnType()->isVoidType() &&
2203 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002204 diag::err_illegal_message_expr_incomplete_type))
2205 return ExprError();
2206
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002207 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002208 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002209 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002210 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002211 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002212 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002213 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002214 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002215 else {
John McCall7decc9e2010-11-18 06:31:45 +00002216 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002217 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002218 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002219 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002220 if (!isImplicit)
2221 checkCocoaAPI(*this, Result);
2222 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002223 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002224}
2225
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002226// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002227// ArgExprs is optional - if it is present, the number of expressions
2228// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002229ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002230 ParsedType Receiver,
2231 Selector Sel,
2232 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002233 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002234 SourceLocation RBracLoc,
2235 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002236 TypeSourceInfo *ReceiverTypeInfo;
2237 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2238 if (ReceiverType.isNull())
2239 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002240
Mike Stump11289f42009-09-09 15:08:12 +00002241
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002242 if (!ReceiverTypeInfo)
2243 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2244
2245 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002246 /*SuperLoc=*/SourceLocation(), Sel,
2247 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2248 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002249}
2250
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002251ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2252 QualType ReceiverType,
2253 SourceLocation Loc,
2254 Selector Sel,
2255 ObjCMethodDecl *Method,
2256 MultiExprArg Args) {
2257 return BuildInstanceMessage(Receiver, ReceiverType,
2258 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2259 Sel, Method, Loc, Loc, Loc, Args,
2260 /*isImplicit=*/true);
2261}
2262
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002263/// \brief Build an Objective-C instance message expression.
2264///
2265/// This routine takes care of both normal instance messages and
2266/// instance messages to the superclass instance.
2267///
2268/// \param Receiver The expression that computes the object that will
2269/// receive this message. This may be empty, in which case we are
2270/// sending to the superclass instance and \p SuperLoc must be a valid
2271/// source location.
2272///
2273/// \param ReceiverType The (static) type of the object receiving the
2274/// message. When a \p Receiver expression is provided, this is the
2275/// same type as that expression. For a superclass instance send, this
2276/// is a pointer to the type of the superclass.
2277///
2278/// \param SuperLoc The location of the "super" keyword in a
2279/// superclass instance message.
2280///
2281/// \param Sel The selector to which the message is being sent.
2282///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002283/// \param Method The method that this instance message is invoking, if
2284/// already known.
2285///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002286/// \param LBracLoc The location of the opening square bracket ']'.
2287///
James Dennettffad8b72012-06-22 08:10:18 +00002288/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002289///
James Dennettffad8b72012-06-22 08:10:18 +00002290/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002291ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002292 QualType ReceiverType,
2293 SourceLocation SuperLoc,
2294 Selector Sel,
2295 ObjCMethodDecl *Method,
2296 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002297 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002298 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002299 MultiExprArg ArgsIn,
2300 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002301 // The location of the receiver.
2302 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002303 SourceRange RecRange =
2304 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2305 SourceLocation SelLoc;
2306 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2307 SelLoc = SelectorLocs.front();
2308 else
2309 SelLoc = Loc;
2310
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002311 if (LBracLoc.isInvalid()) {
2312 Diag(Loc, diag::err_missing_open_square_message_send)
2313 << FixItHint::CreateInsertion(Loc, "[");
2314 LBracLoc = Loc;
2315 }
2316
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002317 // If we have a receiver expression, perform appropriate promotions
2318 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002319 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002320 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002321 ExprResult Result;
2322 if (Receiver->getType() == Context.UnknownAnyTy)
2323 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2324 else
2325 Result = CheckPlaceholderExpr(Receiver);
2326 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002327 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002328 }
2329
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002330 if (Receiver->isTypeDependent()) {
2331 // If the receiver is type-dependent, we can't type-check anything
2332 // at this point. Build a dependent expression.
2333 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002334 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002335 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002336 return ObjCMessageExpr::Create(
2337 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2338 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2339 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002340 }
2341
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002342 // If necessary, apply function/array conversion to the receiver.
2343 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002344 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2345 if (Result.isInvalid())
2346 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002347 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002348 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002349
2350 // If the receiver is an ObjC pointer, a block pointer, or an
2351 // __attribute__((NSObject)) pointer, we don't need to do any
2352 // special conversion in order to look up a receiver.
2353 if (ReceiverType->isObjCRetainableType()) {
2354 // do nothing
2355 } else if (!getLangOpts().ObjCAutoRefCount &&
2356 !Context.getObjCIdType().isNull() &&
2357 (ReceiverType->isPointerType() ||
2358 ReceiverType->isIntegerType())) {
2359 // Implicitly convert integers and pointers to 'id' but emit a warning.
2360 // But not in ARC.
2361 Diag(Loc, diag::warn_bad_receiver_type)
2362 << ReceiverType
2363 << Receiver->getSourceRange();
2364 if (ReceiverType->isPointerType()) {
2365 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002366 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002367 } else {
2368 // TODO: specialized warning on null receivers?
2369 bool IsNull = Receiver->isNullPointerConstant(Context,
2370 Expr::NPC_ValueDependentIsNull);
2371 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2372 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002373 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002374 }
2375 ReceiverType = Receiver->getType();
2376 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002377 // The receiver must be a complete type.
2378 if (RequireCompleteType(Loc, Receiver->getType(),
2379 diag::err_incomplete_receiver_type))
2380 return ExprError();
2381
John McCall80c93a02013-03-01 09:20:14 +00002382 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2383 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002384 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002385 ReceiverType = Receiver->getType();
2386 }
2387 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002388 }
2389
John McCall80c93a02013-03-01 09:20:14 +00002390 // There's a somewhat weird interaction here where we assume that we
2391 // won't actually have a method unless we also don't need to do some
2392 // of the more detailed type-checking on the receiver.
2393
Douglas Gregorb5186b12010-04-22 17:01:48 +00002394 if (!Method) {
2395 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002396 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002397 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002398 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2399 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002400 SourceRange(LBracLoc, RBracLoc),
2401 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002402 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002403 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002404 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002405 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002406 } else if (ReceiverType->isObjCClassType() ||
2407 ReceiverType->isObjCQualifiedClassType()) {
2408 // Handle messages to Class.
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002409 // We allow sending a message to a qualified Class ("Class<foo>"), which
2410 // is ok as long as one of the protocols implements the selector (if not, warn).
2411 if (const ObjCObjectPointerType *QClassTy
2412 = ReceiverType->getAsObjCQualifiedClassType()) {
2413 // Search protocols for class methods.
2414 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2415 if (!Method) {
2416 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2417 // warn if instance method found for a Class message.
2418 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002419 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002420 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002421 Diag(Method->getLocation(), diag::note_method_declared_at)
2422 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002423 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002424 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002425 } else {
2426 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2427 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2428 // First check the public methods in the class interface.
2429 Method = ClassDecl->lookupClassMethod(Sel);
2430
2431 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002432 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002433 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002434 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002435 return ExprError();
2436 }
2437 if (!Method) {
2438 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002439 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002440 Method = LookupFactoryMethodInGlobalPool(Sel,
2441 SourceRange(LBracLoc, RBracLoc),
2442 true);
2443 if (!Method) {
2444 // If no class (factory) method was found, check if an _instance_
2445 // method of the same name exists in the root class only.
2446 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002447 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002448 true);
2449 if (Method)
2450 if (const ObjCInterfaceDecl *ID =
2451 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2452 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002453 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002454 << Sel << SourceRange(LBracLoc, RBracLoc);
2455 }
2456 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002457 }
2458 }
2459 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002460 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002461 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002462
2463 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2464 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002465 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002466 if (const ObjCObjectPointerType *QIdTy
2467 = ReceiverType->getAsObjCQualifiedIdType()) {
2468 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002469 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2470 if (!Method)
2471 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002472 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002473 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002474 } else if (const ObjCObjectPointerType *OCIType
2475 = ReceiverType->getAsObjCInterfacePointerType()) {
2476 // We allow sending a message to a pointer to an interface (an object).
2477 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002478
Douglas Gregor4123a862011-11-14 22:10:01 +00002479 // Try to complete the type. Under ARC, this is a hard error from which
2480 // we don't try to recover.
Craig Topperc3ec1492014-05-26 06:22:03 +00002481 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002482 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002483 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002484 ? diag::err_arc_receiver_forward_instance
2485 : diag::warn_receiver_forward_instance,
2486 Receiver? Receiver->getSourceRange()
2487 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002488 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002489 return ExprError();
2490
2491 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002492 Diag(Receiver ? Receiver->getLocStart()
2493 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002494 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002495 } else {
2496 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002497 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002498
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002499 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002500 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002501 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2502
Douglas Gregorb5186b12010-04-22 17:01:48 +00002503 if (!Method) {
2504 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002505 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002506
David Blaikiebbafb8a2012-03-11 07:00:24 +00002507 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002508 Diag(SelLoc, diag::err_arc_may_not_respond)
2509 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002510 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002511 return ExprError();
2512 }
2513
Douglas Gregor486b74e2011-09-27 16:10:05 +00002514 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002515 // If we still haven't found a method, look in the global pool. This
2516 // behavior isn't very desirable, however we need it for GCC
2517 // compatibility. FIXME: should we deviate??
2518 if (OCIType->qual_empty()) {
2519 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002520 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002521 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002522 Diag(SelLoc, diag::warn_maynot_respond)
2523 << OCIType->getInterfaceDecl()->getIdentifier()
2524 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002525 }
2526 }
2527 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002528 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002529 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002530 } else {
John McCall80c93a02013-03-01 09:20:14 +00002531 // Reject other random receiver types (e.g. structs).
2532 Diag(Loc, diag::err_bad_receiver_type)
2533 << ReceiverType << Receiver->getSourceRange();
2534 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002535 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002536 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002537 }
Mike Stump11289f42009-09-09 15:08:12 +00002538
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002539 FunctionScopeInfo *DIFunctionScopeInfo =
2540 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002541 ? getEnclosingFunction() : nullptr;
2542
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002543 if (DIFunctionScopeInfo &&
2544 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002545 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2546 bool isDesignatedInitChain = false;
2547 if (SuperLoc.isValid()) {
2548 if (const ObjCObjectPointerType *
2549 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2550 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002551 // Either we know this is a designated initializer or we
2552 // conservatively assume it because we don't know for sure.
2553 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2554 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002555 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002556 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002557 }
2558 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002559 }
2560 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002561 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002562 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002563 bool isDesignated =
2564 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2565 assert(isDesignated && InitMethod);
2566 (void)isDesignated;
2567 Diag(SelLoc, SuperLoc.isValid() ?
2568 diag::warn_objc_designated_init_non_designated_init_call :
2569 diag::warn_objc_designated_init_non_super_designated_init_call);
2570 Diag(InitMethod->getLocation(),
2571 diag::note_objc_designated_init_marked_here);
2572 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002573 }
2574
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002575 if (DIFunctionScopeInfo &&
2576 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002577 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2578 if (SuperLoc.isValid()) {
2579 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2580 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002581 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002582 }
2583 }
2584
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002585 // Check the message arguments.
2586 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002587 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002588 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002589 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002590 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2591 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002592 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2593 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002594 ClassMessage, SuperLoc.isValid(),
John McCall7decc9e2010-11-18 06:31:45 +00002595 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002596 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002597
2598 if (Method && !Method->getReturnType()->isVoidType() &&
2599 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002600 diag::err_illegal_message_expr_incomplete_type))
2601 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002602
John McCall31168b02011-06-15 23:02:42 +00002603 // In ARC, forbid the user from sending messages to
2604 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002605 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002606 ObjCMethodFamily family =
2607 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2608 switch (family) {
2609 case OMF_init:
2610 if (Method)
2611 checkInitMethod(Method, ReceiverType);
2612
2613 case OMF_None:
2614 case OMF_alloc:
2615 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002616 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002617 case OMF_mutableCopy:
2618 case OMF_new:
2619 case OMF_self:
2620 break;
2621
2622 case OMF_dealloc:
2623 case OMF_retain:
2624 case OMF_release:
2625 case OMF_autorelease:
2626 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002627 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2628 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002629 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002630
2631 case OMF_performSelector:
2632 if (Method && NumArgs >= 1) {
2633 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2634 Selector ArgSel = SelExp->getSelector();
2635 ObjCMethodDecl *SelMethod =
2636 LookupInstanceMethodInGlobalPool(ArgSel,
2637 SelExp->getSourceRange());
2638 if (!SelMethod)
2639 SelMethod =
2640 LookupFactoryMethodInGlobalPool(ArgSel,
2641 SelExp->getSourceRange());
2642 if (SelMethod) {
2643 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2644 switch (SelFamily) {
2645 case OMF_alloc:
2646 case OMF_copy:
2647 case OMF_mutableCopy:
2648 case OMF_new:
2649 case OMF_self:
2650 case OMF_init:
2651 // Issue error, unless ns_returns_not_retained.
2652 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2653 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002654 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002655 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002656 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2657 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002658 }
2659 break;
2660 default:
2661 // +0 call. OK. unless ns_returns_retained.
2662 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2663 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002664 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002665 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002666 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2667 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002668 }
2669 break;
2670 }
2671 }
2672 } else {
2673 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002674 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002675 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2676 }
2677 }
2678 break;
John McCall31168b02011-06-15 23:02:42 +00002679 }
2680 }
2681
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002682 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002683 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002684 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002685 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002686 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002687 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002688 makeArrayRef(Args, NumArgs), RBracLoc,
2689 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002690 else {
John McCall7decc9e2010-11-18 06:31:45 +00002691 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002692 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002693 makeArrayRef(Args, NumArgs), RBracLoc,
2694 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002695 if (!isImplicit)
2696 checkCocoaAPI(*this, Result);
2697 }
John McCall31168b02011-06-15 23:02:42 +00002698
David Blaikiebbafb8a2012-03-11 07:00:24 +00002699 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian9277ff42014-06-17 23:35:13 +00002700 // Do not warn about IBOutlet weak property receivers being set to null
2701 // as this cannot asynchronously happen.
2702 bool WarnWeakReceiver = true;
2703 if (isImplicit && Method)
2704 if (const ObjCPropertyDecl *PropertyDecl = Method->findPropertyDecl())
2705 WarnWeakReceiver = !PropertyDecl->hasAttr<IBOutletAttr>();
2706 if (WarnWeakReceiver)
2707 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian6bd22262012-04-04 20:05:25 +00002708
John McCall31168b02011-06-15 23:02:42 +00002709 // In ARC, annotate delegate init calls.
2710 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002711 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002712 // Only consider init calls *directly* in init implementations,
2713 // not within blocks.
2714 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2715 if (method && method->getMethodFamily() == OMF_init) {
2716 // The implicit assignment to self means we also don't want to
2717 // consume the result.
2718 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002719 return Result;
John McCall31168b02011-06-15 23:02:42 +00002720 }
2721 }
2722
2723 // In ARC, check for message sends which are likely to introduce
2724 // retain cycles.
2725 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002726
2727 if (!isImplicit && Method) {
2728 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2729 bool IsWeak =
2730 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2731 if (!IsWeak && Sel.isUnarySelector())
2732 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002733 if (IsWeak &&
2734 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2735 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00002736 }
2737 }
John McCall31168b02011-06-15 23:02:42 +00002738 }
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00002739
Douglas Gregoraae38d62010-05-22 05:17:18 +00002740 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002741}
2742
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002743static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2744 if (ObjCSelectorExpr *OSE =
2745 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2746 Selector Sel = OSE->getSelector();
2747 SourceLocation Loc = OSE->getAtLoc();
2748 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2749 = S.ReferencedSelectors.find(Sel);
2750 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2751 S.ReferencedSelectors.erase(Pos);
2752 }
2753}
2754
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002755// ActOnInstanceMessage - used for both unary and keyword messages.
2756// ArgExprs is optional - if it is present, the number of expressions
2757// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002758ExprResult Sema::ActOnInstanceMessage(Scope *S,
2759 Expr *Receiver,
2760 Selector Sel,
2761 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002762 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002763 SourceLocation RBracLoc,
2764 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002765 if (!Receiver)
2766 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002767
2768 // A ParenListExpr can show up while doing error recovery with invalid code.
2769 if (isa<ParenListExpr>(Receiver)) {
2770 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2771 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002772 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002773 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002774
2775 if (RespondsToSelectorSel.isNull()) {
2776 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2777 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2778 }
2779 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002780 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00002781
John McCallb268a282010-08-23 23:25:46 +00002782 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002783 /*SuperLoc=*/SourceLocation(), Sel,
2784 /*Method=*/nullptr, LBracLoc, SelectorLocs,
2785 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002786}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002787
John McCall31168b02011-06-15 23:02:42 +00002788enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002789 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002790 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002791
2792 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002793 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002794
2795 /// id*, id***, void (^*)(),
2796 ACTC_indirectRetainable,
2797
2798 /// void* might be a normal C type, or it might a CF type.
2799 ACTC_voidPtr,
2800
2801 /// struct A*
2802 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002803};
John McCalle4fe2452011-10-01 01:01:08 +00002804static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2805 return (ACTC == ACTC_retainable ||
2806 ACTC == ACTC_coreFoundation ||
2807 ACTC == ACTC_voidPtr);
2808}
2809static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2810 return ACTC == ACTC_none ||
2811 ACTC == ACTC_voidPtr ||
2812 ACTC == ACTC_coreFoundation;
2813}
2814
John McCall31168b02011-06-15 23:02:42 +00002815static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002816 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002817
2818 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002819 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002820 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002821 isIndirect = true;
2822 }
John McCall31168b02011-06-15 23:02:42 +00002823
2824 // Drill through pointers and arrays recursively.
2825 while (true) {
2826 if (const PointerType *ptr = type->getAs<PointerType>()) {
2827 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002828
2829 // The first level of pointer may be the innermost pointer on a CF type.
2830 if (!isIndirect) {
2831 if (type->isVoidType()) return ACTC_voidPtr;
2832 if (type->isRecordType()) return ACTC_coreFoundation;
2833 }
John McCall31168b02011-06-15 23:02:42 +00002834 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2835 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2836 } else {
2837 break;
2838 }
John McCalle4fe2452011-10-01 01:01:08 +00002839 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002840 }
2841
John McCalle4fe2452011-10-01 01:01:08 +00002842 if (isIndirect) {
2843 if (type->isObjCARCBridgableType())
2844 return ACTC_indirectRetainable;
2845 return ACTC_none;
2846 }
2847
2848 if (type->isObjCARCBridgableType())
2849 return ACTC_retainable;
2850
2851 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002852}
2853
2854namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002855 /// A result from the cast checker.
2856 enum ACCResult {
2857 /// Cannot be casted.
2858 ACC_invalid,
2859
2860 /// Can be safely retained or not retained.
2861 ACC_bottom,
2862
2863 /// Can be casted at +0.
2864 ACC_plusZero,
2865
2866 /// Can be casted at +1.
2867 ACC_plusOne
2868 };
2869 ACCResult merge(ACCResult left, ACCResult right) {
2870 if (left == right) return left;
2871 if (left == ACC_bottom) return right;
2872 if (right == ACC_bottom) return left;
2873 return ACC_invalid;
2874 }
2875
2876 /// A checker which white-lists certain expressions whose conversion
2877 /// to or from retainable type would otherwise be forbidden in ARC.
2878 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2879 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2880
John McCall31168b02011-06-15 23:02:42 +00002881 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002882 ARCConversionTypeClass SourceClass;
2883 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002884 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002885
2886 static bool isCFType(QualType type) {
2887 // Someday this can use ns_bridged. For now, it has to do this.
2888 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002889 }
John McCalle4fe2452011-10-01 01:01:08 +00002890
2891 public:
2892 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002893 ARCConversionTypeClass target, bool diagnose)
2894 : Context(Context), SourceClass(source), TargetClass(target),
2895 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00002896
2897 using super::Visit;
2898 ACCResult Visit(Expr *e) {
2899 return super::Visit(e->IgnoreParens());
2900 }
2901
2902 ACCResult VisitStmt(Stmt *s) {
2903 return ACC_invalid;
2904 }
2905
2906 /// Null pointer constants can be casted however you please.
2907 ACCResult VisitExpr(Expr *e) {
2908 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2909 return ACC_bottom;
2910 return ACC_invalid;
2911 }
2912
2913 /// Objective-C string literals can be safely casted.
2914 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2915 // If we're casting to any retainable type, go ahead. Global
2916 // strings are immune to retains, so this is bottom.
2917 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2918
2919 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002920 }
2921
John McCalle4fe2452011-10-01 01:01:08 +00002922 /// Look through certain implicit and explicit casts.
2923 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002924 switch (e->getCastKind()) {
2925 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00002926 return ACC_bottom;
2927
John McCall31168b02011-06-15 23:02:42 +00002928 case CK_NoOp:
2929 case CK_LValueToRValue:
2930 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002931 case CK_CPointerToObjCPointerCast:
2932 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002933 case CK_AnyPointerToBlockPointerCast:
2934 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00002935
John McCall31168b02011-06-15 23:02:42 +00002936 default:
John McCalle4fe2452011-10-01 01:01:08 +00002937 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002938 }
2939 }
John McCalle4fe2452011-10-01 01:01:08 +00002940
2941 /// Look through unary extension.
2942 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002943 return Visit(e->getSubExpr());
2944 }
John McCalle4fe2452011-10-01 01:01:08 +00002945
2946 /// Ignore the LHS of a comma operator.
2947 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002948 return Visit(e->getRHS());
2949 }
John McCalle4fe2452011-10-01 01:01:08 +00002950
2951 /// Conditional operators are okay if both sides are okay.
2952 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2953 ACCResult left = Visit(e->getTrueExpr());
2954 if (left == ACC_invalid) return ACC_invalid;
2955 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00002956 }
John McCalle4fe2452011-10-01 01:01:08 +00002957
John McCallfe96e0b2011-11-06 09:01:30 +00002958 /// Look through pseudo-objects.
2959 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2960 // If we're getting here, we should always have a result.
2961 return Visit(e->getResultExpr());
2962 }
2963
John McCalle4fe2452011-10-01 01:01:08 +00002964 /// Statement expressions are okay if their result expression is okay.
2965 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002966 return Visit(e->getSubStmt()->body_back());
2967 }
John McCall31168b02011-06-15 23:02:42 +00002968
John McCalle4fe2452011-10-01 01:01:08 +00002969 /// Some declaration references are okay.
2970 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2971 // References to global constants from system headers are okay.
2972 // These are things like 'kCFStringTransformToLatin'. They are
2973 // can also be assumed to be immune to retains.
2974 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2975 if (isAnyRetainable(TargetClass) &&
2976 isAnyRetainable(SourceClass) &&
2977 var &&
2978 var->getStorageClass() == SC_Extern &&
2979 var->getType().isConstQualified() &&
2980 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2981 return ACC_bottom;
2982 }
2983
2984 // Nothing else.
2985 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00002986 }
John McCalle4fe2452011-10-01 01:01:08 +00002987
2988 /// Some calls are okay.
2989 ACCResult VisitCallExpr(CallExpr *e) {
2990 if (FunctionDecl *fn = e->getDirectCallee())
2991 if (ACCResult result = checkCallToFunction(fn))
2992 return result;
2993
2994 return super::VisitCallExpr(e);
2995 }
2996
2997 ACCResult checkCallToFunction(FunctionDecl *fn) {
2998 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00002999 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003000 return ACC_invalid;
3001
3002 if (!isAnyRetainable(TargetClass))
3003 return ACC_invalid;
3004
3005 // Honor an explicit 'not retained' attribute.
3006 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3007 return ACC_plusZero;
3008
3009 // Honor an explicit 'retained' attribute, except that for
3010 // now we're not going to permit implicit handling of +1 results,
3011 // because it's a bit frightening.
3012 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003013 return Diagnose ? ACC_plusOne
3014 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003015
3016 // Recognize this specific builtin function, which is used by CFSTR.
3017 unsigned builtinID = fn->getBuiltinID();
3018 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3019 return ACC_bottom;
3020
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003021 // Otherwise, don't do anything implicit with an unaudited function.
3022 if (!fn->hasAttr<CFAuditedTransferAttr>())
3023 return ACC_invalid;
3024
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003025 // Otherwise, it's +0 unless it follows the create convention.
3026 if (ento::coreFoundation::followsCreateRule(fn))
3027 return Diagnose ? ACC_plusOne
3028 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003029
John McCalle4fe2452011-10-01 01:01:08 +00003030 return ACC_plusZero;
3031 }
3032
3033 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3034 return checkCallToMethod(e->getMethodDecl());
3035 }
3036
3037 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3038 ObjCMethodDecl *method;
3039 if (e->isExplicitProperty())
3040 method = e->getExplicitProperty()->getGetterMethodDecl();
3041 else
3042 method = e->getImplicitPropertyGetter();
3043 return checkCallToMethod(method);
3044 }
3045
3046 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3047 if (!method) return ACC_invalid;
3048
3049 // Check for message sends to functions returning CF types. We
3050 // just obey the Cocoa conventions with these, even though the
3051 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003052 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003053 return ACC_invalid;
3054
3055 // If the method is explicitly marked not-retained, it's +0.
3056 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3057 return ACC_plusZero;
3058
3059 // If the method is explicitly marked as returning retained, or its
3060 // selector follows a +1 Cocoa convention, treat it as +1.
3061 if (method->hasAttr<CFReturnsRetainedAttr>())
3062 return ACC_plusOne;
3063
3064 switch (method->getSelector().getMethodFamily()) {
3065 case OMF_alloc:
3066 case OMF_copy:
3067 case OMF_mutableCopy:
3068 case OMF_new:
3069 return ACC_plusOne;
3070
3071 default:
3072 // Otherwise, treat it as +0.
3073 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003074 }
3075 }
John McCalle4fe2452011-10-01 01:01:08 +00003076 };
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003077}
3078
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003079bool Sema::isKnownName(StringRef name) {
3080 if (name.empty())
3081 return false;
3082 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003083 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003084 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003085}
3086
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003087static void addFixitForObjCARCConversion(Sema &S,
3088 DiagnosticBuilder &DiagB,
3089 Sema::CheckedConversionKind CCK,
3090 SourceLocation afterLParen,
3091 QualType castType,
3092 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003093 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003094 const char *bridgeKeyword,
3095 const char *CFBridgeName) {
3096 // We handle C-style and implicit casts here.
3097 switch (CCK) {
3098 case Sema::CCK_ImplicitConversion:
3099 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003100 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003101 break;
3102 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003103 return;
3104 }
3105
3106 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003107 if (CCK == Sema::CCK_OtherCast) {
3108 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3109 SourceRange range(NCE->getOperatorLoc(),
3110 NCE->getAngleBrackets().getEnd());
3111 SmallString<32> BridgeCall;
3112
3113 SourceManager &SM = S.getSourceManager();
3114 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3115 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3116 BridgeCall += ' ';
3117
3118 BridgeCall += CFBridgeName;
3119 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3120 }
3121 return;
3122 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003123 Expr *castedE = castExpr;
3124 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3125 castedE = CCE->getSubExpr();
3126 castedE = castedE->IgnoreImpCasts();
3127 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003128
3129 SmallString<32> BridgeCall;
3130
3131 SourceManager &SM = S.getSourceManager();
3132 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3133 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3134 BridgeCall += ' ';
3135
3136 BridgeCall += CFBridgeName;
3137
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003138 if (isa<ParenExpr>(castedE)) {
3139 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003140 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003141 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003142 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003143 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003144 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003145 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3146 S.PP.getLocForEndOfToken(range.getEnd()),
3147 ")"));
3148 }
3149 return;
3150 }
3151
3152 if (CCK == Sema::CCK_CStyleCast) {
3153 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003154 } else if (CCK == Sema::CCK_OtherCast) {
3155 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3156 std::string castCode = "(";
3157 castCode += bridgeKeyword;
3158 castCode += castType.getAsString();
3159 castCode += ")";
3160 SourceRange Range(NCE->getOperatorLoc(),
3161 NCE->getAngleBrackets().getEnd());
3162 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3163 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003164 } else {
3165 std::string castCode = "(";
3166 castCode += bridgeKeyword;
3167 castCode += castType.getAsString();
3168 castCode += ")";
3169 Expr *castedE = castExpr->IgnoreImpCasts();
3170 SourceRange range = castedE->getSourceRange();
3171 if (isa<ParenExpr>(castedE)) {
3172 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3173 castCode));
3174 } else {
3175 castCode += "(";
3176 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3177 castCode));
3178 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3179 S.PP.getLocForEndOfToken(range.getEnd()),
3180 ")"));
3181 }
3182 }
3183}
3184
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003185template <typename T>
3186static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3187 TypedefNameDecl *TDNDecl = TD->getDecl();
3188 QualType QT = TDNDecl->getUnderlyingType();
3189 if (QT->isPointerType()) {
3190 QT = QT->getPointeeType();
3191 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003192 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003193 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003194 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003195 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003196}
3197
3198static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3199 TypedefNameDecl *&TDNDecl) {
3200 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3201 TDNDecl = TD->getDecl();
3202 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3203 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3204 return ObjCBAttr;
3205 T = TDNDecl->getUnderlyingType();
3206 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003207 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003208}
3209
John McCall4124c492011-10-17 18:40:02 +00003210static void
3211diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3212 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003213 Expr *castExpr, Expr *realCast,
3214 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003215 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003216 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003217 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003218
John McCall4124c492011-10-17 18:40:02 +00003219 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003220 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003221 return;
John McCall4124c492011-10-17 18:40:02 +00003222
3223 QualType castExprType = castExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003224 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003225 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3226 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3227 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003228 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003229 return;
John McCall31168b02011-06-15 23:02:42 +00003230
John McCall640767f2011-06-17 06:50:50 +00003231 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003232 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003233 case ACTC_none:
3234 case ACTC_coreFoundation:
3235 case ACTC_voidPtr:
3236 srcKind = (castExprType->isPointerType() ? 1 : 0);
3237 break;
3238 case ACTC_retainable:
3239 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3240 break;
3241 case ACTC_indirectRetainable:
3242 srcKind = 4;
3243 break;
John McCall31168b02011-06-15 23:02:42 +00003244 }
3245
John McCall4124c492011-10-17 18:40:02 +00003246 // Check whether this could be fixed with a bridge cast.
3247 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3248 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003249
John McCall4124c492011-10-17 18:40:02 +00003250 // Bridge from an ARC type to a CF type.
3251 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003252
John McCall4124c492011-10-17 18:40:02 +00003253 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3254 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3255 << 2 // of C pointer type
3256 << castExprType
3257 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3258 << castType
3259 << castRange
3260 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003261 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003262 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003263 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003264 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003265 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003266 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003267 DiagnosticBuilder DiagB =
3268 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3269 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003270
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003271 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003272 castType, castExpr, realCast, "__bridge ",
3273 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003274 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003275 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003276 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003277 DiagnosticBuilder DiagB =
3278 (CCK == Sema::CCK_OtherCast && !br) ?
3279 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3280 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3281 diag::note_arc_bridge_transfer)
3282 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003283
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003284 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003285 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003286 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003287 }
John McCall4124c492011-10-17 18:40:02 +00003288
3289 return;
3290 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003291
John McCall4124c492011-10-17 18:40:02 +00003292 // Bridge from a CF type to an ARC type.
3293 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003294 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003295 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3296 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3297 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3298 << castExprType
3299 << 2 // to C pointer type
3300 << castType
3301 << castRange
3302 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003303 ACCResult CreateRule =
3304 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003305 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003306 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003307 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003308 DiagnosticBuilder DiagB =
3309 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3310 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003311 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003312 castType, castExpr, realCast, "__bridge ",
3313 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003314 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003315 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003316 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003317 DiagnosticBuilder DiagB =
3318 (CCK == Sema::CCK_OtherCast && !br) ?
3319 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3320 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3321 diag::note_arc_bridge_retained)
3322 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003323
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003324 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003325 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003326 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003327 }
John McCall4124c492011-10-17 18:40:02 +00003328
3329 return;
John McCall31168b02011-06-15 23:02:42 +00003330 }
3331
John McCall4124c492011-10-17 18:40:02 +00003332 S.Diag(loc, diag::err_arc_mismatched_cast)
3333 << (CCK != Sema::CCK_ImplicitConversion)
3334 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003335 << castRange << castExpr->getSourceRange();
3336}
3337
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003338template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003339static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3340 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003341 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003342 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003343 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3344 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003345 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003346 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003347 HadTheAttribute = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003348 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003349 // Check for an existing type with this name.
3350 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3351 Sema::LookupOrdinaryName);
3352 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003353 Target = R.getFoundDecl();
3354 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3355 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3356 if (const ObjCObjectPointerType *InterfacePointerType =
3357 castType->getAsObjCInterfacePointerType()) {
3358 ObjCInterfaceDecl *CastClass
3359 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003360 if ((CastClass == ExprClass) ||
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003361 (CastClass && ExprClass->isSuperClassOf(CastClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003362 return true;
3363 if (warn)
3364 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3365 << T << Target->getName() << castType->getPointeeType();
3366 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003367 } else if (castType->isObjCIdType() ||
3368 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3369 castType, ExprClass)))
3370 // ok to cast to 'id'.
3371 // casting to id<p-list> is ok if bridge type adopts all of
3372 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003373 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003374 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003375 if (warn) {
3376 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3377 << T << Target->getName() << castType;
3378 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3379 S.Diag(Target->getLocStart(), diag::note_declared_at);
3380 }
3381 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003382 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003383 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003384 }
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003385 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
Aaron Ballmanc0550742014-01-03 02:07:43 +00003386 << castExpr->getType() << Parm;
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003387 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3388 if (Target)
3389 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003390 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003391 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003392 return false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003393 }
3394 T = TDNDecl->getUnderlyingType();
3395 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003396 return true;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003397}
3398
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003399template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003400static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr,
3401 bool &HadTheAttribute, bool warn) {
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003402 QualType T = castType;
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003403 HadTheAttribute = false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003404 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3405 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003406 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003407 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003408 HadTheAttribute = true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003409 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003410 // Check for an existing type with this name.
3411 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3412 Sema::LookupOrdinaryName);
3413 if (S.LookupName(R, S.TUScope)) {
3414 Target = R.getFoundDecl();
3415 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3416 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3417 if (const ObjCObjectPointerType *InterfacePointerType =
3418 castExpr->getType()->getAsObjCInterfacePointerType()) {
3419 ObjCInterfaceDecl *ExprClass
3420 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003421 if ((CastClass == ExprClass) ||
3422 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003423 return true;
3424 if (warn) {
3425 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3426 << castExpr->getType()->getPointeeType() << T;
3427 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3428 }
3429 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003430 } else if (castExpr->getType()->isObjCIdType() ||
3431 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3432 castExpr->getType(), CastClass)))
3433 // ok to cast an 'id' expression to a CFtype.
3434 // ok to cast an 'id<plist>' expression to CFtype provided plist
3435 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003436 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003437 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003438 if (warn) {
3439 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3440 << castExpr->getType() << castType;
3441 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3442 S.Diag(Target->getLocStart(), diag::note_declared_at);
3443 }
3444 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003445 }
3446 }
3447 }
3448 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3449 << castExpr->getType() << castType;
3450 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3451 if (Target)
3452 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003453 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003454 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003455 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003456 }
3457 T = TDNDecl->getUnderlyingType();
3458 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003459 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003460}
3461
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003462void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003463 if (!getLangOpts().ObjC1)
3464 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003465 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003466 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3467 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003468 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003469 bool HasObjCBridgeAttr;
3470 bool ObjCBridgeAttrWillNotWarn =
3471 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3472 false);
3473 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3474 return;
3475 bool HasObjCBridgeMutableAttr;
3476 bool ObjCBridgeMutableAttrWillNotWarn =
3477 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3478 HasObjCBridgeMutableAttr, false);
3479 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3480 return;
3481
3482 if (HasObjCBridgeAttr)
3483 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3484 true);
3485 else if (HasObjCBridgeMutableAttr)
3486 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3487 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003488 }
3489 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003490 bool HasObjCBridgeAttr;
3491 bool ObjCBridgeAttrWillNotWarn =
3492 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3493 false);
3494 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3495 return;
3496 bool HasObjCBridgeMutableAttr;
3497 bool ObjCBridgeMutableAttrWillNotWarn =
3498 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3499 HasObjCBridgeMutableAttr, false);
3500 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3501 return;
3502
3503 if (HasObjCBridgeAttr)
3504 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3505 true);
3506 else if (HasObjCBridgeMutableAttr)
3507 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3508 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003509 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003510}
3511
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003512void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3513 QualType SrcType = castExpr->getType();
3514 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3515 if (PRE->isExplicitProperty()) {
3516 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3517 SrcType = PDecl->getType();
3518 }
3519 else if (PRE->isImplicitProperty()) {
3520 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3521 SrcType = Getter->getReturnType();
3522
3523 }
3524 }
3525
3526 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3527 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3528 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3529 return;
3530 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3531 castType, SrcType, castExpr);
3532 return;
3533}
3534
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003535bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3536 CastKind &Kind) {
3537 if (!getLangOpts().ObjC1)
3538 return false;
3539 ARCConversionTypeClass exprACTC =
3540 classifyTypeForARCConversion(castExpr->getType());
3541 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3542 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3543 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3544 CheckTollFreeBridgeCast(castType, castExpr);
3545 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3546 : CK_CPointerToObjCPointerCast;
3547 return true;
3548 }
3549 return false;
3550}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003551
3552bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3553 QualType DestType, QualType SrcType,
3554 ObjCInterfaceDecl *&RelatedClass,
3555 ObjCMethodDecl *&ClassMethod,
3556 ObjCMethodDecl *&InstanceMethod,
3557 TypedefNameDecl *&TDNDecl,
3558 bool CfToNs) {
3559 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003560 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3561 if (!ObjCBAttr)
3562 return false;
3563
3564 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3565 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3566 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3567 if (!RCId)
3568 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003569 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003570 // Check for an existing type with this name.
3571 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3572 Sema::LookupOrdinaryName);
3573 if (!LookupName(R, TUScope)) {
3574 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003575 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003576 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3577 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003578 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003579 Target = R.getFoundDecl();
3580 if (Target && isa<ObjCInterfaceDecl>(Target))
3581 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3582 else {
3583 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3584 << SrcType << DestType;
3585 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3586 if (Target)
3587 Diag(Target->getLocStart(), diag::note_declared_at);
3588 return false;
3589 }
3590
3591 // Check for an existing class method with the given selector name.
3592 if (CfToNs && CMId) {
3593 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3594 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3595 if (!ClassMethod) {
3596 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003597 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003598 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3599 return false;
3600 }
3601 }
3602
3603 // Check for an existing instance method with the given selector name.
3604 if (!CfToNs && IMId) {
3605 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3606 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3607 if (!InstanceMethod) {
3608 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003609 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003610 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3611 return false;
3612 }
3613 }
3614 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003615}
3616
3617bool
3618Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003619 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003620 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003621 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3622 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3623 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3624 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3625 if (!CfToNs && !NsToCf)
3626 return false;
3627
3628 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00003629 ObjCMethodDecl *ClassMethod = nullptr;
3630 ObjCMethodDecl *InstanceMethod = nullptr;
3631 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003632 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3633 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3634 return false;
3635
3636 if (CfToNs) {
3637 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003638 if (ClassMethod) {
3639 std::string ExpressionString = "[";
3640 ExpressionString += RelatedClass->getNameAsString();
3641 ExpressionString += " ";
3642 ExpressionString += ClassMethod->getSelector().getAsString();
3643 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3644 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003645 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003646 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003647 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3648 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003649 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3650 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3651
3652 QualType receiverType =
3653 Context.getObjCInterfaceType(RelatedClass);
3654 // Argument.
3655 Expr *args[] = { SrcExpr };
3656 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3657 ClassMethod->getLocation(),
3658 ClassMethod->getSelector(), ClassMethod,
3659 MultiExprArg(args, 1));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003660 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003661 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003662 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003663 }
3664 else {
3665 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003666 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003667 std::string ExpressionString;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003668 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003669 if (InstanceMethod->isPropertyAccessor())
3670 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3671 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3672 ExpressionString = ".";
3673 ExpressionString += PDecl->getNameAsString();
3674 Diag(Loc, diag::err_objc_bridged_related_known_method)
3675 << SrcType << DestType << InstanceMethod->getSelector() << true
3676 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3677 }
3678 if (ExpressionString.empty()) {
3679 // Provide a fixit: [ObjectExpr InstanceMethod]
3680 ExpressionString = " ";
3681 ExpressionString += InstanceMethod->getSelector().getAsString();
3682 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003683
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003684 Diag(Loc, diag::err_objc_bridged_related_known_method)
3685 << SrcType << DestType << InstanceMethod->getSelector() << true
3686 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3687 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3688 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003689 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3690 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3691
3692 ExprResult msg =
3693 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3694 InstanceMethod->getLocation(),
3695 InstanceMethod->getSelector(),
3696 InstanceMethod, None);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003697 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003698 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003699 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003700 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003701 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003702}
3703
John McCall4124c492011-10-17 18:40:02 +00003704Sema::ARCConversionResult
3705Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003706 Expr *&castExpr, CheckedConversionKind CCK,
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003707 bool DiagnoseCFAudited,
3708 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00003709 QualType castExprType = castExpr->getType();
3710
3711 // For the purposes of the classification, we assume reference types
3712 // will bind to temporaries.
3713 QualType effCastType = castType;
3714 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3715 effCastType = ref->getPointeeType();
3716
3717 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3718 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003719 if (exprACTC == castACTC) {
3720 // check for viablity and report error if casting an rvalue to a
3721 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003722 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003723 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003724 (castType != castExprType)) {
3725 const Type *DT = castType.getTypePtr();
3726 QualType QDT = castType;
3727 // We desugar some types but not others. We ignore those
3728 // that cannot happen in a cast; i.e. auto, and those which
3729 // should not be de-sugared; i.e typedef.
3730 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3731 QDT = PT->desugar();
3732 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3733 QDT = TP->desugar();
3734 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3735 QDT = AT->desugar();
3736 if (QDT != castType &&
3737 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3738 SourceLocation loc =
3739 (castRange.isValid() ? castRange.getBegin()
3740 : castExpr->getExprLoc());
3741 Diag(loc, diag::err_arc_nolifetime_behavior);
3742 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003743 }
3744 return ACR_okay;
3745 }
3746
John McCall4124c492011-10-17 18:40:02 +00003747 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3748
3749 // Allow all of these types to be cast to integer types (but not
3750 // vice-versa).
3751 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3752 return ACR_okay;
3753
3754 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3755 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3756 // must be explicit.
3757 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3758 return ACR_okay;
3759 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3760 CCK != CCK_ImplicitConversion)
3761 return ACR_okay;
3762
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003763 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003764 // For invalid casts, fall through.
3765 case ACC_invalid:
3766 break;
3767
3768 // Do nothing for both bottom and +0.
3769 case ACC_bottom:
3770 case ACC_plusZero:
3771 return ACR_okay;
3772
3773 // If the result is +1, consume it here.
3774 case ACC_plusOne:
3775 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3776 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00003777 nullptr, VK_RValue);
John McCall4124c492011-10-17 18:40:02 +00003778 ExprNeedsCleanups = true;
3779 return ACR_okay;
3780 }
3781
3782 // If this is a non-implicit cast from id or block type to a
3783 // CoreFoundation type, delay complaining in case the cast is used
3784 // in an acceptable context.
3785 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3786 CCK != CCK_ImplicitConversion)
3787 return ACR_unbridged;
3788
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003789 // Do not issue bridge cast" diagnostic when implicit casting a cstring
3790 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3791 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00003792 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3793 ConversionToObjCStringLiteralCheck(castType, castExpr))
3794 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003795
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003796 // Do not issue "bridge cast" diagnostic when implicit casting
3797 // a retainable object to a CF type parameter belonging to an audited
3798 // CF API function. Let caller issue a normal type mismatched diagnostic
3799 // instead.
3800 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3801 castACTC != ACTC_coreFoundation)
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003802 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
3803 (Opc == BO_NE || Opc == BO_EQ)))
3804 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3805 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003806 return ACR_okay;
3807}
3808
3809/// Given that we saw an expression with the ARCUnbridgedCastTy
3810/// placeholder type, complain bitterly.
3811void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3812 // We expect the spurious ImplicitCastExpr to already have been stripped.
3813 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3814 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3815
3816 SourceRange castRange;
3817 QualType castType;
3818 CheckedConversionKind CCK;
3819
3820 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3821 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3822 castType = cast->getTypeAsWritten();
3823 CCK = CCK_CStyleCast;
3824 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3825 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3826 castType = cast->getTypeAsWritten();
3827 CCK = CCK_OtherCast;
3828 } else {
3829 castType = cast->getType();
3830 CCK = CCK_ImplicitConversion;
3831 }
3832
3833 ARCConversionTypeClass castACTC =
3834 classifyTypeForARCConversion(castType.getNonReferenceType());
3835
3836 Expr *castExpr = realCast->getSubExpr();
3837 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3838
3839 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003840 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003841}
3842
3843/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3844/// type, remove the placeholder cast.
3845Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3846 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3847
3848 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3849 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3850 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3851 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3852 assert(uo->getOpcode() == UO_Extension);
3853 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3854 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3855 sub->getValueKind(), sub->getObjectKind(),
3856 uo->getOperatorLoc());
3857 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3858 assert(!gse->isResultDependent());
3859
3860 unsigned n = gse->getNumAssocs();
3861 SmallVector<Expr*, 4> subExprs(n);
3862 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3863 for (unsigned i = 0; i != n; ++i) {
3864 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3865 Expr *sub = gse->getAssocExpr(i);
3866 if (i == gse->getResultIndex())
3867 sub = stripARCUnbridgedCast(sub);
3868 subExprs[i] = sub;
3869 }
3870
3871 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3872 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003873 subTypes, subExprs,
3874 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003875 gse->getRParenLoc(),
3876 gse->containsUnexpandedParameterPack(),
3877 gse->getResultIndex());
3878 } else {
3879 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3880 return cast<ImplicitCastExpr>(e)->getSubExpr();
3881 }
3882}
3883
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003884bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3885 QualType exprType) {
3886 QualType canCastType =
3887 Context.getCanonicalType(castType).getUnqualifiedType();
3888 QualType canExprType =
3889 Context.getCanonicalType(exprType).getUnqualifiedType();
3890 if (isa<ObjCObjectPointerType>(canCastType) &&
3891 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3892 canExprType->isObjCObjectPointerType()) {
3893 if (const ObjCObjectPointerType *ObjT =
3894 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00003895 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3896 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003897 }
3898 return true;
3899}
3900
John McCall4db5c3c2011-07-07 06:58:02 +00003901/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3902static Expr *maybeUndoReclaimObject(Expr *e) {
3903 // For now, we just undo operands that are *immediately* reclaim
3904 // expressions, which prevents the vast majority of potential
3905 // problems here. To catch them all, we'd need to rebuild arbitrary
3906 // value-propagating subexpressions --- we can't reliably rebuild
3907 // in-place because of expression sharing.
3908 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00003909 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00003910 return ice->getSubExpr();
3911
3912 return e;
3913}
3914
John McCall31168b02011-06-15 23:02:42 +00003915ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3916 ObjCBridgeCastKind Kind,
3917 SourceLocation BridgeKeywordLoc,
3918 TypeSourceInfo *TSInfo,
3919 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00003920 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3921 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003922 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00003923
John McCall31168b02011-06-15 23:02:42 +00003924 QualType T = TSInfo->getType();
3925 QualType FromType = SubExpr->getType();
3926
John McCall9320b872011-09-09 05:25:32 +00003927 CastKind CK;
3928
John McCall31168b02011-06-15 23:02:42 +00003929 bool MustConsume = false;
3930 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3931 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00003932 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00003933 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3934 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00003935 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3936 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00003937 switch (Kind) {
3938 case OBC_Bridge:
3939 break;
3940
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003941 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003942 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00003943 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3944 << 2
3945 << FromType
3946 << (T->isBlockPointerType()? 1 : 0)
3947 << T
3948 << SubExpr->getSourceRange()
3949 << Kind;
3950 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3951 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3952 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003953 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00003954 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003955 br ? "CFBridgingRelease "
3956 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00003957
3958 Kind = OBC_Bridge;
3959 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003960 }
John McCall31168b02011-06-15 23:02:42 +00003961
3962 case OBC_BridgeTransfer:
3963 // We must consume the Objective-C object produced by the cast.
3964 MustConsume = true;
3965 break;
3966 }
3967 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3968 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00003969 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00003970 switch (Kind) {
3971 case OBC_Bridge:
John McCall4db5c3c2011-07-07 06:58:02 +00003972 // Reclaiming a value that's going to be __bridge-casted to CF
3973 // is very dangerous, so we don't do it.
3974 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCall31168b02011-06-15 23:02:42 +00003975 break;
3976
3977 case OBC_BridgeRetained:
3978 // Produce the object before casting it.
3979 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00003980 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00003981 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00003982 break;
3983
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003984 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003985 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00003986 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3987 << (FromType->isBlockPointerType()? 1 : 0)
3988 << FromType
3989 << 2
3990 << T
3991 << SubExpr->getSourceRange()
3992 << Kind;
3993
3994 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3995 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3996 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003997 << T << br
3998 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3999 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00004000
4001 Kind = OBC_Bridge;
4002 break;
4003 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004004 }
John McCall31168b02011-06-15 23:02:42 +00004005 } else {
4006 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4007 << FromType << T << Kind
4008 << SubExpr->getSourceRange()
4009 << TSInfo->getTypeLoc().getSourceRange();
4010 return ExprError();
4011 }
4012
John McCall9320b872011-09-09 05:25:32 +00004013 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004014 BridgeKeywordLoc,
4015 TSInfo, SubExpr);
4016
4017 if (MustConsume) {
4018 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00004019 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004020 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004021 }
4022
4023 return Result;
4024}
4025
4026ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4027 SourceLocation LParenLoc,
4028 ObjCBridgeCastKind Kind,
4029 SourceLocation BridgeKeywordLoc,
4030 ParsedType Type,
4031 SourceLocation RParenLoc,
4032 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004033 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004034 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004035 if (Kind == OBC_Bridge)
4036 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004037 if (!TSInfo)
4038 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4039 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4040 SubExpr);
4041}