blob: 62c1b874d5acc095c09c2632394febc768efe441 [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 }
Alex Denisove36748a2015-02-16 16:17:05 +0000221 }
222
223 if (S.NSNumberPointer.isNull()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000224 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000225 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
226 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000227 }
228
Ted Kremeneke65b0862012-03-06 20:05:56 +0000229 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000230 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000231 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000232 // create a stub definition this NSNumber factory method.
Craig Topperc3ec1492014-05-26 06:22:03 +0000233 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000234 Method =
235 ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
236 S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl,
237 /*isInstance=*/false, /*isVariadic=*/false,
238 /*isPropertyAccessor=*/false,
239 /*isImplicitlyDeclared=*/true,
240 /*isDefined=*/false, ObjCMethodDecl::Required,
241 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000242 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
243 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000244 &CX.Idents.get("value"),
Craig Topperc3ec1492014-05-26 06:22:03 +0000245 NumberType, /*TInfo=*/nullptr,
246 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000247 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000248 }
249
Jordy Rose08e500c2012-05-12 17:32:44 +0000250 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Craig Topperc3ec1492014-05-26 06:22:03 +0000251 return nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000252
253 // Note: if the parameter type is out-of-line, we'll catch it later in the
254 // implicit conversion.
255
256 S.NSNumberLiteralMethods[*Kind] = Method;
257 return Method;
258}
259
Patrick Beard0caa3942012-04-19 00:25:12 +0000260/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
261/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000262ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000263 // Determine the type of the literal.
264 QualType NumberType = Number->getType();
265 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
266 // In C, character literals have type 'int'. That's not the type we want
267 // to use to determine the Objective-c literal kind.
268 switch (Char->getKind()) {
269 case CharacterLiteral::Ascii:
270 NumberType = Context.CharTy;
271 break;
272
273 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000274 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000275 break;
276
277 case CharacterLiteral::UTF16:
278 NumberType = Context.Char16Ty;
279 break;
280
281 case CharacterLiteral::UTF32:
282 NumberType = Context.Char32Ty;
283 break;
284 }
285 }
286
Ted Kremeneke65b0862012-03-06 20:05:56 +0000287 // Look for the appropriate method within NSNumber.
288 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000289 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000290 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000291 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000292 if (!Method)
293 return ExprError();
294
295 // Convert the number to the type that the parameter expects.
Alp Toker03376dc2014-07-07 09:02:20 +0000296 ParmVarDecl *ParamDecl = Method->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000297 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
298 ParamDecl);
299 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
300 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000301 Number);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000302 if (ConvertedNumber.isInvalid())
303 return ExprError();
304 Number = ConvertedNumber.get();
305
Patrick Beard2565c592012-05-01 21:47:19 +0000306 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000307 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000308 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
309 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000310}
311
312ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
313 SourceLocation ValueLoc,
314 bool Value) {
315 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000316 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000317 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
318 } else {
319 // C doesn't actually have a way to represent literal values of type
320 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
321 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
322 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
323 CK_IntegralToBoolean);
324 }
325
326 return BuildObjCNumericLiteral(AtLoc, Inner.get());
327}
328
329/// \brief Check that the given expression is a valid element of an Objective-C
330/// collection literal.
331static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000332 QualType T,
333 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000334 // If the expression is type-dependent, there's nothing for us to do.
335 if (Element->isTypeDependent())
336 return Element;
337
338 ExprResult Result = S.CheckPlaceholderExpr(Element);
339 if (Result.isInvalid())
340 return ExprError();
341 Element = Result.get();
342
343 // In C++, check for an implicit conversion to an Objective-C object pointer
344 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000345 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000346 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000347 = InitializedEntity::InitializeParameter(S.Context, T,
348 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000349 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000350 = InitializationKind::CreateCopy(Element->getLocStart(),
351 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000352 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000353 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000354 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000355 }
356
357 Expr *OrigElement = Element;
358
359 // Perform lvalue-to-rvalue conversion.
360 Result = S.DefaultLvalueConversion(Element);
361 if (Result.isInvalid())
362 return ExprError();
363 Element = Result.get();
364
365 // Make sure that we have an Objective-C pointer type or block.
366 if (!Element->getType()->isObjCObjectPointerType() &&
367 !Element->getType()->isBlockPointerType()) {
368 bool Recovered = false;
369
370 // If this is potentially an Objective-C numeric literal, add the '@'.
371 if (isa<IntegerLiteral>(OrigElement) ||
372 isa<CharacterLiteral>(OrigElement) ||
373 isa<FloatingLiteral>(OrigElement) ||
374 isa<ObjCBoolLiteralExpr>(OrigElement) ||
375 isa<CXXBoolLiteralExpr>(OrigElement)) {
376 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
377 int Which = isa<CharacterLiteral>(OrigElement) ? 1
378 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
379 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
380 : 3;
381
382 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
383 << Which << OrigElement->getSourceRange()
384 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
385
386 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
387 OrigElement);
388 if (Result.isInvalid())
389 return ExprError();
390
391 Element = Result.get();
392 Recovered = true;
393 }
394 }
395 // If this is potentially an Objective-C string literal, add the '@'.
396 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
397 if (String->isAscii()) {
398 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
399 << 0 << OrigElement->getSourceRange()
400 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
401
402 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
403 if (Result.isInvalid())
404 return ExprError();
405
406 Element = Result.get();
407 Recovered = true;
408 }
409 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000410
Ted Kremeneke65b0862012-03-06 20:05:56 +0000411 if (!Recovered) {
412 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
413 << Element->getType();
414 return ExprError();
415 }
416 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000417 if (ArrayLiteral)
Ted Kremenek197fee42013-10-09 22:34:33 +0000418 if (ObjCStringLiteral *getString =
419 dyn_cast<ObjCStringLiteral>(OrigElement)) {
420 if (StringLiteral *SL = getString->getString()) {
421 unsigned numConcat = SL->getNumConcatenated();
422 if (numConcat > 1) {
423 // Only warn if the concatenated string doesn't come from a macro.
424 bool hasMacro = false;
425 for (unsigned i = 0; i < numConcat ; ++i)
426 if (SL->getStrTokenLoc(i).isMacroID()) {
427 hasMacro = true;
428 break;
429 }
430 if (!hasMacro)
431 S.Diag(Element->getLocStart(),
432 diag::warn_concatenated_nsarray_literal)
433 << Element->getType();
434 }
435 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000436 }
437
Ted Kremeneke65b0862012-03-06 20:05:56 +0000438 // Make sure that the element has the type that the container factory
439 // function expects.
440 return S.PerformCopyInitialization(
441 InitializedEntity::InitializeParameter(S.Context, T,
442 /*Consumed=*/false),
443 Element->getLocStart(), Element);
444}
445
Patrick Beard0caa3942012-04-19 00:25:12 +0000446ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
447 if (ValueExpr->isTypeDependent()) {
448 ObjCBoxedExpr *BoxedExpr =
Craig Topperc3ec1492014-05-26 06:22:03 +0000449 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, nullptr, SR);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000450 return BoxedExpr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000451 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000452 ObjCMethodDecl *BoxingMethod = nullptr;
Patrick Beard0caa3942012-04-19 00:25:12 +0000453 QualType BoxedType;
454 // Convert the expression to an RValue, so we can check for pointer types...
455 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
456 if (RValue.isInvalid()) {
457 return ExprError();
458 }
459 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000460 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000461 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
462 QualType PointeeType = PT->getPointeeType();
463 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
464
465 if (!NSStringDecl) {
466 IdentifierInfo *NSStringId =
467 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
468 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
469 SR.getBegin(), LookupOrdinaryName);
470 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
471 if (!NSStringDecl) {
472 if (getLangOpts().DebuggerObjCLiteral) {
473 // Support boxed expressions in the debugger w/o NSString declaration.
Jordy Roseaca01f92012-05-12 17:32:52 +0000474 DeclContext *TU = Context.getTranslationUnitDecl();
475 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
476 SourceLocation(),
477 NSStringId,
Craig Topperc3ec1492014-05-26 06:22:03 +0000478 nullptr, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000479 } else {
480 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
481 return ExprError();
482 }
483 } else if (!NSStringDecl->hasDefinition()) {
484 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
485 return ExprError();
486 }
487 assert(NSStringDecl && "NSStringDecl should not be NULL");
Jordy Roseaca01f92012-05-12 17:32:52 +0000488 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
489 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000490 }
491
492 if (!StringWithUTF8StringMethod) {
493 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
494 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
495
496 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000497 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
498 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000499 // Debugger needs to work even if NSString hasn't been defined.
Craig Topperc3ec1492014-05-26 06:22:03 +0000500 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000501 ObjCMethodDecl *M = ObjCMethodDecl::Create(
502 Context, SourceLocation(), SourceLocation(), stringWithUTF8String,
503 NSStringPointer, ReturnTInfo, NSStringDecl,
504 /*isInstance=*/false, /*isVariadic=*/false,
505 /*isPropertyAccessor=*/false,
506 /*isImplicitlyDeclared=*/true,
507 /*isDefined=*/false, ObjCMethodDecl::Required,
508 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000509 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000510 ParmVarDecl *value =
511 ParmVarDecl::Create(Context, M,
512 SourceLocation(), SourceLocation(),
513 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000514 Context.getPointerType(ConstCharType),
Craig Topperc3ec1492014-05-26 06:22:03 +0000515 /*TInfo=*/nullptr,
516 SC_None, nullptr);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000517 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000518 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000519 }
Jordy Rose890f4572012-05-12 15:53:41 +0000520
Jordy Rose08e500c2012-05-12 17:32:44 +0000521 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
522 stringWithUTF8String, BoxingMethod))
523 return ExprError();
524
525 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000526 }
527
528 BoxingMethod = StringWithUTF8StringMethod;
529 BoxedType = NSStringPointer;
530 }
Patrick Beard2565c592012-05-01 21:47:19 +0000531 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000532 // The other types we support are numeric, char and BOOL/bool. We could also
533 // provide limited support for structure types, such as NSRange, NSRect, and
534 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
535 // for more details.
536
537 // Check for a top-level character literal.
538 if (const CharacterLiteral *Char =
539 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
540 // In C, character literals have type 'int'. That's not the type we want
541 // to use to determine the Objective-c literal kind.
542 switch (Char->getKind()) {
543 case CharacterLiteral::Ascii:
544 ValueType = Context.CharTy;
545 break;
546
547 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000548 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000549 break;
550
551 case CharacterLiteral::UTF16:
552 ValueType = Context.Char16Ty;
553 break;
554
555 case CharacterLiteral::UTF32:
556 ValueType = Context.Char32Ty;
557 break;
558 }
559 }
Fariborz Jahanian5d64abb2014-06-18 20:49:02 +0000560 CheckForIntOverflow(ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000561 // FIXME: Do I need to do anything special with BoolTy expressions?
562
563 // Look for the appropriate method within NSNumber.
564 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
565 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000566
567 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
568 if (!ET->getDecl()->isComplete()) {
569 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
570 << ValueType << ValueExpr->getSourceRange();
571 return ExprError();
572 }
573
574 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
575 ET->getDecl()->getIntegerType());
576 BoxedType = NSNumberPointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000577 }
578
579 if (!BoxingMethod) {
580 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
581 << ValueType << ValueExpr->getSourceRange();
582 return ExprError();
583 }
584
585 // Convert the expression to the type that the parameter requires.
Alp Toker03376dc2014-07-07 09:02:20 +0000586 ParmVarDecl *ParamDecl = BoxingMethod->parameters()[0];
Patrick Beard2565c592012-05-01 21:47:19 +0000587 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
588 ParamDecl);
589 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
590 SourceLocation(),
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000591 ValueExpr);
Patrick Beard0caa3942012-04-19 00:25:12 +0000592 if (ConvertedValueExpr.isInvalid())
593 return ExprError();
594 ValueExpr = ConvertedValueExpr.get();
595
596 ObjCBoxedExpr *BoxedExpr =
597 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
598 BoxingMethod, SR);
599 return MaybeBindToTemporary(BoxedExpr);
600}
601
John McCallf2538342012-07-31 05:14:30 +0000602/// Build an ObjC subscript pseudo-object expression, given that
603/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000604ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
605 Expr *IndexExpr,
606 ObjCMethodDecl *getterMethod,
607 ObjCMethodDecl *setterMethod) {
Fariborz Jahaniane1e33f82013-11-01 21:58:17 +0000608 assert(!LangOpts.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000609
John McCallf2538342012-07-31 05:14:30 +0000610 // We can't get dependent types here; our callers should have
611 // filtered them out.
612 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
613 "base or index cannot have dependent type here");
614
615 // Filter out placeholders in the index. In theory, overloads could
616 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000617 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
618 if (Result.isInvalid())
619 return ExprError();
620 IndexExpr = Result.get();
621
John McCallf2538342012-07-31 05:14:30 +0000622 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000623 Result = DefaultLvalueConversion(BaseExpr);
624 if (Result.isInvalid())
625 return ExprError();
626 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000627
628 // Build the pseudo-object expression.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000629 return ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr,
630 Context.PseudoObjectTy, getterMethod,
631 setterMethod, RB);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000632}
633
634ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
635 // Look up the NSArray class, if we haven't done so already.
636 if (!NSArrayDecl) {
637 NamedDecl *IF = LookupSingleName(TUScope,
638 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
639 SR.getBegin(),
640 LookupOrdinaryName);
641 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000642 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000643 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
644 Context.getTranslationUnitDecl(),
645 SourceLocation(),
646 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
Craig Topperc3ec1492014-05-26 06:22:03 +0000647 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000648
649 if (!NSArrayDecl) {
650 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
651 return ExprError();
652 }
653 }
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000654
Fariborz Jahanian495bc3f2014-08-08 17:31:14 +0000655 // Find the arrayWithObjects:count: method, if we haven't done so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000656 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000657 if (!ArrayWithObjectsMethod) {
658 Selector
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000659 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
660 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000661 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000662 TypeSourceInfo *ReturnTInfo = nullptr;
Alp Toker314cc812014-01-25 16:55:45 +0000663 Method = ObjCMethodDecl::Create(
664 Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000665 Context.getTranslationUnitDecl(), false /*Instance*/,
Alp Toker314cc812014-01-25 16:55:45 +0000666 false /*isVariadic*/,
667 /*isPropertyAccessor=*/false,
668 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
669 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000670 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000671 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000672 SourceLocation(),
673 SourceLocation(),
674 &Context.Idents.get("objects"),
675 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000676 /*TInfo=*/nullptr,
677 SC_None, nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000678 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000679 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000680 SourceLocation(),
681 SourceLocation(),
682 &Context.Idents.get("cnt"),
683 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000684 /*TInfo=*/nullptr, SC_None,
685 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000686 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000687 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000688 }
689
Jordy Rose08e500c2012-05-12 17:32:44 +0000690 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000691 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000692
Jordy Rose4af44872012-05-12 17:32:56 +0000693 // Dig out the type that all elements should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000694 QualType T = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000695 const PointerType *PtrT = T->getAs<PointerType>();
696 if (!PtrT ||
697 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
698 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
699 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000700 Diag(Method->parameters()[0]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000701 diag::note_objc_literal_method_param)
702 << 0 << T
703 << Context.getPointerType(IdT.withConst());
704 return ExprError();
705 }
706
707 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000708 if (!Method->parameters()[1]->getType()->isIntegerType()) {
Jordy Rose4af44872012-05-12 17:32:56 +0000709 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
710 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000711 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000712 diag::note_objc_literal_method_param)
713 << 1
Alp Toker03376dc2014-07-07 09:02:20 +0000714 << Method->parameters()[1]->getType()
Jordy Rose4af44872012-05-12 17:32:56 +0000715 << "integral";
716 return ExprError();
717 }
718
719 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000720 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000721 }
722
Alp Toker03376dc2014-07-07 09:02:20 +0000723 QualType ObjectsType = ArrayWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000724 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000725
726 // Check that each of the elements provided is valid in a collection literal,
727 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000728 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000729 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
730 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
731 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000732 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000733 if (Converted.isInvalid())
734 return ExprError();
735
736 ElementsBuffer[I] = Converted.get();
737 }
738
739 QualType Ty
740 = Context.getObjCObjectPointerType(
741 Context.getObjCInterfaceType(NSArrayDecl));
742
743 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000744 ObjCArrayLiteral::Create(Context, Elements, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000745 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000746}
747
748ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
749 ObjCDictionaryElement *Elements,
750 unsigned NumElements) {
751 // Look up the NSDictionary class, if we haven't done so already.
752 if (!NSDictionaryDecl) {
753 NamedDecl *IF = LookupSingleName(TUScope,
754 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
755 SR.getBegin(), LookupOrdinaryName);
756 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000757 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000758 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
759 Context.getTranslationUnitDecl(),
760 SourceLocation(),
761 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
Craig Topperc3ec1492014-05-26 06:22:03 +0000762 nullptr, SourceLocation());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000763
764 if (!NSDictionaryDecl) {
765 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
766 return ExprError();
767 }
768 }
769
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000770 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
771 // so already.
Fariborz Jahanianbf09db42014-08-08 18:29:52 +0000772 QualType IdT = Context.getObjCIdType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000773 if (!DictionaryWithObjectsMethod) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000774 Selector Sel = NSAPIObj->getNSDictionarySelector(
775 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
776 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
Jordy Rose08e500c2012-05-12 17:32:44 +0000777 if (!Method && getLangOpts().DebuggerObjCLiteral) {
778 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000779 SourceLocation(), SourceLocation(), Sel,
780 IdT,
Craig Topperc3ec1492014-05-26 06:22:03 +0000781 nullptr /*TypeSourceInfo */,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000782 Context.getTranslationUnitDecl(),
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000783 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000784 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000785 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
786 ObjCMethodDecl::Required,
787 false);
788 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000789 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000790 SourceLocation(),
791 SourceLocation(),
792 &Context.Idents.get("objects"),
793 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000794 /*TInfo=*/nullptr, SC_None,
795 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000796 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000797 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000798 SourceLocation(),
799 SourceLocation(),
800 &Context.Idents.get("keys"),
801 Context.getPointerType(IdT),
Craig Topperc3ec1492014-05-26 06:22:03 +0000802 /*TInfo=*/nullptr, SC_None,
803 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000804 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000805 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000806 SourceLocation(),
807 SourceLocation(),
808 &Context.Idents.get("cnt"),
809 Context.UnsignedLongTy,
Craig Topperc3ec1492014-05-26 06:22:03 +0000810 /*TInfo=*/nullptr, SC_None,
811 nullptr);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000812 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000813 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000814 }
815
Jordy Rose08e500c2012-05-12 17:32:44 +0000816 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
817 Method))
818 return ExprError();
819
Jordy Rose4af44872012-05-12 17:32:56 +0000820 // Dig out the type that all values should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000821 QualType ValueT = Method->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000822 const PointerType *PtrValue = ValueT->getAs<PointerType>();
823 if (!PtrValue ||
824 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000825 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000826 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000827 Diag(Method->parameters()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000828 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000829 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000830 << Context.getPointerType(IdT.withConst());
831 return ExprError();
832 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000833
Jordy Rose4af44872012-05-12 17:32:56 +0000834 // Dig out the type that all keys should be converted to.
Alp Toker03376dc2014-07-07 09:02:20 +0000835 QualType KeyT = Method->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000836 const PointerType *PtrKey = KeyT->getAs<PointerType>();
837 if (!PtrKey ||
838 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
839 IdT)) {
840 bool err = true;
841 if (PtrKey) {
842 if (QIDNSCopying.isNull()) {
843 // key argument of selector is id<NSCopying>?
844 if (ObjCProtocolDecl *NSCopyingPDecl =
845 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
846 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
847 QIDNSCopying =
848 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
849 (ObjCProtocolDecl**) PQ,1);
850 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
851 }
852 }
853 if (!QIDNSCopying.isNull())
854 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
855 QIDNSCopying);
856 }
857
858 if (err) {
859 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
860 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000861 Diag(Method->parameters()[1]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000862 diag::note_objc_literal_method_param)
863 << 1 << KeyT
864 << Context.getPointerType(IdT.withConst());
865 return ExprError();
866 }
867 }
868
869 // Check that the 'count' parameter is integral.
Alp Toker03376dc2014-07-07 09:02:20 +0000870 QualType CountType = Method->parameters()[2]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000871 if (!CountType->isIntegerType()) {
872 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
873 << Sel;
Alp Toker03376dc2014-07-07 09:02:20 +0000874 Diag(Method->parameters()[2]->getLocation(),
Jordy Rose4af44872012-05-12 17:32:56 +0000875 diag::note_objc_literal_method_param)
876 << 2 << CountType
877 << "integral";
878 return ExprError();
879 }
880
881 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
882 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000883 }
884
Alp Toker03376dc2014-07-07 09:02:20 +0000885 QualType ValuesT = DictionaryWithObjectsMethod->parameters()[0]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000886 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
Alp Toker03376dc2014-07-07 09:02:20 +0000887 QualType KeysT = DictionaryWithObjectsMethod->parameters()[1]->getType();
Jordy Rose4af44872012-05-12 17:32:56 +0000888 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
889
Ted Kremeneke65b0862012-03-06 20:05:56 +0000890 // Check that each of the keys and values provided is valid in a collection
891 // literal, performing conversions as necessary.
892 bool HasPackExpansions = false;
893 for (unsigned I = 0, N = NumElements; I != N; ++I) {
894 // Check the key.
895 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
896 KeyT);
897 if (Key.isInvalid())
898 return ExprError();
899
900 // Check the value.
901 ExprResult Value
902 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
903 if (Value.isInvalid())
904 return ExprError();
905
906 Elements[I].Key = Key.get();
907 Elements[I].Value = Value.get();
908
909 if (Elements[I].EllipsisLoc.isInvalid())
910 continue;
911
912 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
913 !Elements[I].Value->containsUnexpandedParameterPack()) {
914 Diag(Elements[I].EllipsisLoc,
915 diag::err_pack_expansion_without_parameter_packs)
916 << SourceRange(Elements[I].Key->getLocStart(),
917 Elements[I].Value->getLocEnd());
918 return ExprError();
919 }
920
921 HasPackExpansions = true;
922 }
923
924
925 QualType Ty
926 = Context.getObjCObjectPointerType(
Robert Wilhelm88e02492013-08-19 07:57:02 +0000927 Context.getObjCInterfaceType(NSDictionaryDecl));
928 return MaybeBindToTemporary(ObjCDictionaryLiteral::Create(
929 Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000930 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000931}
932
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000933ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +0000934 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +0000935 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +0000936 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +0000937 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +0000938 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +0000939 StrTy = Context.DependentTy;
940 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +0000941 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
942 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000943 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000944 diag::err_incomplete_type_objc_at_encode,
945 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000946 return ExprError();
947
Anders Carlsson315d2292009-06-07 18:45:35 +0000948 std::string Str;
Fariborz Jahanian4bf437e2014-08-22 23:17:52 +0000949 QualType NotEncodedT;
950 Context.getObjCEncodingForType(EncodedType, Str, nullptr, &NotEncodedT);
951 if (!NotEncodedT.isNull())
952 Diag(AtLoc, diag::warn_incomplete_encoded_type)
953 << EncodedType << NotEncodedT;
Anders Carlsson315d2292009-06-07 18:45:35 +0000954
955 // The type of @encode is the same as the type of the corresponding string,
956 // which is an array type.
957 StrTy = Context.CharTy;
958 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000959 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +0000960 StrTy.addConst();
961 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
962 ArrayType::Normal, 0);
963 }
Mike Stump11289f42009-09-09 15:08:12 +0000964
Douglas Gregorabd9e962010-04-20 15:39:42 +0000965 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +0000966}
967
John McCallfaf5fb42010-08-26 23:41:50 +0000968ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
969 SourceLocation EncodeLoc,
970 SourceLocation LParenLoc,
971 ParsedType ty,
972 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000973 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +0000974 TypeSourceInfo *TInfo;
975 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
976 if (!TInfo)
977 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
978 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000979
Douglas Gregorabd9e962010-04-20 15:39:42 +0000980 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000981}
982
Fariborz Jahanian44be1542014-03-12 18:34:01 +0000983static bool HelperToDiagnoseMismatchedMethodsInGlobalPool(Sema &S,
984 SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +0000985 SourceLocation LParenLoc,
986 SourceLocation RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +0000987 ObjCMethodDecl *Method,
988 ObjCMethodList &MethList) {
989 ObjCMethodList *M = &MethList;
990 bool Warned = false;
991 for (M = M->getNext(); M; M=M->getNext()) {
Nico Weber2e0c8f72014-12-27 03:58:08 +0000992 ObjCMethodDecl *MatchingMethodDecl = M->getMethod();
Fariborz Jahanian44be1542014-03-12 18:34:01 +0000993 if (MatchingMethodDecl == Method ||
994 isa<ObjCImplDecl>(MatchingMethodDecl->getDeclContext()) ||
995 MatchingMethodDecl->getSelector() != Method->getSelector())
996 continue;
997 if (!S.MatchTwoMethodDeclarations(Method,
998 MatchingMethodDecl, Sema::MMS_loose)) {
999 if (!Warned) {
1000 Warned = true;
1001 S.Diag(AtLoc, diag::warning_multiple_selectors)
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001002 << Method->getSelector() << FixItHint::CreateInsertion(LParenLoc, "(")
1003 << FixItHint::CreateInsertion(RParenLoc, ")");
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001004 S.Diag(Method->getLocation(), diag::note_method_declared_at)
1005 << Method->getDeclName();
1006 }
1007 S.Diag(MatchingMethodDecl->getLocation(), diag::note_method_declared_at)
1008 << MatchingMethodDecl->getDeclName();
1009 }
1010 }
1011 return Warned;
1012}
1013
1014static void DiagnoseMismatchedSelectors(Sema &S, SourceLocation AtLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001015 ObjCMethodDecl *Method,
1016 SourceLocation LParenLoc,
1017 SourceLocation RParenLoc,
1018 bool WarnMultipleSelectors) {
1019 if (!WarnMultipleSelectors ||
1020 S.Diags.isIgnored(diag::warning_multiple_selectors, SourceLocation()))
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001021 return;
1022 bool Warned = false;
1023 for (Sema::GlobalMethodPool::iterator b = S.MethodPool.begin(),
1024 e = S.MethodPool.end(); b != e; b++) {
1025 // first, instance methods
1026 ObjCMethodList &InstMethList = b->second.first;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001027 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001028 Method, InstMethList))
1029 Warned = true;
1030
1031 // second, class methods
1032 ObjCMethodList &ClsMethList = b->second.second;
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001033 if (HelperToDiagnoseMismatchedMethodsInGlobalPool(S, AtLoc, LParenLoc, RParenLoc,
1034 Method, ClsMethList) || Warned)
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001035 return;
1036 }
1037}
1038
John McCallfaf5fb42010-08-26 23:41:50 +00001039ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
1040 SourceLocation AtLoc,
1041 SourceLocation SelLoc,
1042 SourceLocation LParenLoc,
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001043 SourceLocation RParenLoc,
1044 bool WarnMultipleSelectors) {
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001045 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
1046 SourceRange(LParenLoc, RParenLoc), false, false);
1047 if (!Method)
1048 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +00001049 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00001050 if (!Method) {
1051 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
1052 Selector MatchedSel = OM->getSelector();
1053 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
1054 RParenLoc.getLocWithOffset(-1));
1055 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
1056 << Sel << MatchedSel
1057 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1058
1059 } else
1060 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian44be1542014-03-12 18:34:01 +00001061 } else
Fariborz Jahaniandacffc02014-06-24 17:02:19 +00001062 DiagnoseMismatchedSelectors(*this, AtLoc, Method, LParenLoc, RParenLoc,
1063 WarnMultipleSelectors);
Chandler Carruth12c8f652015-03-27 00:55:05 +00001064
Fariborz Jahanian65a78b52014-05-09 19:51:39 +00001065 if (Method &&
1066 Method->getImplementationControl() != ObjCMethodDecl::Optional &&
Chandler Carruth12c8f652015-03-27 00:55:05 +00001067 !getSourceManager().isInSystemHeader(Method->getLocation()))
1068 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00001069
Fariborz Jahanian02447d82013-01-22 18:35:43 +00001070 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001071 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001072 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001073 switch (Sel.getMethodFamily()) {
1074 case OMF_retain:
1075 case OMF_release:
1076 case OMF_autorelease:
1077 case OMF_retainCount:
1078 case OMF_dealloc:
1079 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1080 Sel << SourceRange(LParenLoc, RParenLoc);
1081 break;
1082
1083 case OMF_None:
1084 case OMF_alloc:
1085 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001086 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001087 case OMF_init:
1088 case OMF_mutableCopy:
1089 case OMF_new:
1090 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001091 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001092 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001093 break;
1094 }
1095 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001096 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001097 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001098}
1099
John McCallfaf5fb42010-08-26 23:41:50 +00001100ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1101 SourceLocation AtLoc,
1102 SourceLocation ProtoLoc,
1103 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001104 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001105 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001106 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001107 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001108 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001109 return true;
1110 }
Fariborz Jahaniana57d91c22014-07-25 19:45:01 +00001111 if (PDecl->hasDefinition())
1112 PDecl = PDecl->getDefinition();
Mike Stump11289f42009-09-09 15:08:12 +00001113
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001114 QualType Ty = Context.getObjCProtoType();
1115 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001116 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001117 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001118 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001119}
1120
John McCall5f2d5562011-02-03 09:00:02 +00001121/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001122ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1123 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001124
1125 // If we're not in an ObjC method, error out. Note that, unlike the
1126 // C++ case, we don't require an instance method --- class methods
1127 // still have a 'self', and we really do still need to capture it!
1128 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1129 if (!method)
Craig Topperc3ec1492014-05-26 06:22:03 +00001130 return nullptr;
John McCall5f2d5562011-02-03 09:00:02 +00001131
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001132 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001133
1134 return method;
1135}
1136
Douglas Gregor64910ca2011-09-09 20:05:21 +00001137static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1138 if (T == Context.getObjCInstanceType())
1139 return Context.getObjCIdType();
1140
1141 return T;
1142}
1143
Douglas Gregor33823722011-06-11 01:09:30 +00001144QualType Sema::getMessageSendResultType(QualType ReceiverType,
1145 ObjCMethodDecl *Method,
1146 bool isClassMessage, bool isSuperMessage) {
1147 assert(Method && "Must have a method");
1148 if (!Method->hasRelatedResultType())
1149 return Method->getSendResultType();
1150
1151 // If a method has a related return type:
1152 // - if the method found is an instance method, but the message send
1153 // was a class message send, T is the declared return type of the method
1154 // found
1155 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001156 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001157
1158 // - if the receiver is super, T is a pointer to the class of the
1159 // enclosing method definition
1160 if (isSuperMessage) {
1161 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1162 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1163 return Context.getObjCObjectPointerType(
1164 Context.getObjCInterfaceType(Class));
1165 }
1166
1167 // - if the receiver is the name of a class U, T is a pointer to U
1168 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1169 ReceiverType->isObjCQualifiedInterfaceType())
1170 return Context.getObjCObjectPointerType(ReceiverType);
1171 // - if the receiver is of type Class or qualified Class type,
1172 // T is the declared return type of the method.
1173 if (ReceiverType->isObjCClassType() ||
1174 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001175 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001176
1177 // - if the receiver is id, qualified id, Class, or qualified Class, T
1178 // is the receiver type, otherwise
1179 // - T is the type of the receiver expression.
1180 return ReceiverType;
1181}
John McCall5f2d5562011-02-03 09:00:02 +00001182
John McCall5ec7e7d2013-03-19 07:04:25 +00001183/// Look for an ObjC method whose result type exactly matches the given type.
1184static const ObjCMethodDecl *
1185findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1186 QualType instancetype) {
Alp Toker314cc812014-01-25 16:55:45 +00001187 if (MD->getReturnType() == instancetype)
1188 return MD;
John McCall5ec7e7d2013-03-19 07:04:25 +00001189
1190 // For these purposes, a method in an @implementation overrides a
1191 // declaration in the @interface.
1192 if (const ObjCImplDecl *impl =
1193 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1194 const ObjCContainerDecl *iface;
1195 if (const ObjCCategoryImplDecl *catImpl =
1196 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1197 iface = catImpl->getCategoryDecl();
1198 } else {
1199 iface = impl->getClassInterface();
1200 }
1201
1202 const ObjCMethodDecl *ifaceMD =
1203 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1204 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1205 }
1206
1207 SmallVector<const ObjCMethodDecl *, 4> overrides;
1208 MD->getOverriddenMethods(overrides);
1209 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1210 if (const ObjCMethodDecl *result =
1211 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1212 return result;
1213 }
1214
Craig Topperc3ec1492014-05-26 06:22:03 +00001215 return nullptr;
John McCall5ec7e7d2013-03-19 07:04:25 +00001216}
1217
1218void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1219 // Only complain if we're in an ObjC method and the required return
1220 // type doesn't match the method's declared return type.
1221 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1222 if (!MD || !MD->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +00001223 Context.hasSameUnqualifiedType(destType, MD->getReturnType()))
John McCall5ec7e7d2013-03-19 07:04:25 +00001224 return;
1225
1226 // Look for a method overridden by this method which explicitly uses
1227 // 'instancetype'.
1228 if (const ObjCMethodDecl *overridden =
1229 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001230 SourceRange range = overridden->getReturnTypeSourceRange();
1231 SourceLocation loc = range.getBegin();
John McCall5ec7e7d2013-03-19 07:04:25 +00001232 if (loc.isInvalid())
1233 loc = overridden->getLocation();
1234 Diag(loc, diag::note_related_result_type_explicit)
1235 << /*current method*/ 1 << range;
1236 return;
1237 }
1238
1239 // Otherwise, if we have an interesting method family, note that.
1240 // This should always trigger if the above didn't.
1241 if (ObjCMethodFamily family = MD->getMethodFamily())
1242 Diag(MD->getLocation(), diag::note_related_result_type_family)
1243 << /*current method*/ 1
1244 << family;
1245}
1246
Douglas Gregor33823722011-06-11 01:09:30 +00001247void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1248 E = E->IgnoreParenImpCasts();
1249 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1250 if (!MsgSend)
1251 return;
1252
1253 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1254 if (!Method)
1255 return;
1256
1257 if (!Method->hasRelatedResultType())
1258 return;
Alp Toker314cc812014-01-25 16:55:45 +00001259
1260 if (Context.hasSameUnqualifiedType(
1261 Method->getReturnType().getNonReferenceType(), MsgSend->getType()))
Douglas Gregor33823722011-06-11 01:09:30 +00001262 return;
Alp Toker314cc812014-01-25 16:55:45 +00001263
1264 if (!Context.hasSameUnqualifiedType(Method->getReturnType(),
Douglas Gregorbab8a962011-09-08 01:46:34 +00001265 Context.getObjCInstanceType()))
1266 return;
1267
Douglas Gregor33823722011-06-11 01:09:30 +00001268 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1269 << Method->isInstanceMethod() << Method->getSelector()
1270 << MsgSend->getType();
1271}
1272
1273bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001274 MultiExprArg Args,
1275 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001276 ArrayRef<SourceLocation> SelectorLocs,
1277 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001278 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001279 SourceLocation lbrac, SourceLocation rbrac,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001280 SourceRange RecRange,
John McCall7decc9e2010-11-18 06:31:45 +00001281 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001282 SourceLocation SelLoc;
1283 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1284 SelLoc = SelectorLocs.front();
1285 else
1286 SelLoc = lbrac;
1287
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001288 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001289 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001290 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001291 if (Args[i]->isTypeDependent())
1292 continue;
1293
John McCallcc5788c2013-03-04 07:34:02 +00001294 ExprResult result;
1295 if (getLangOpts().DebuggerSupport) {
1296 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001297 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001298 } else {
1299 result = DefaultArgumentPromotion(Args[i]);
1300 }
1301 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001302 return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001303 Args[i] = result.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001304 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001305
John McCall31168b02011-06-15 23:02:42 +00001306 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001307 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001308 DiagID = diag::err_arc_method_not_found;
1309 else
1310 DiagID = isClassMessage ? diag::warn_class_method_not_found
1311 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001312 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001313 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001314 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001315 if (getLangOpts().ObjCAutoRefCount)
1316 DiagID = diag::error_method_not_found_with_typo;
1317 else
1318 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1319 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001320 Selector MatchedSel = OMD->getSelector();
1321 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian5ab87502014-08-12 22:16:41 +00001322 if (MatchedSel.isUnarySelector())
1323 Diag(SelLoc, DiagID)
1324 << Sel<< isClassMessage << MatchedSel
1325 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1326 else
1327 Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001328 }
1329 else
1330 Diag(SelLoc, DiagID)
1331 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001332 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001333 // Find the class to which we are sending this message.
1334 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00001335 if (ObjCInterfaceDecl *ThisClass =
1336 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) {
1337 Diag(ThisClass->getLocation(), diag::note_receiver_class_declared);
1338 if (!RecRange.isInvalid())
1339 if (ThisClass->lookupClassMethod(Sel))
1340 Diag(RecRange.getBegin(),diag::note_receiver_expr_here)
1341 << FixItHint::CreateReplacement(RecRange,
1342 ThisClass->getNameAsString());
1343 }
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001344 }
1345 }
John McCall3f4138c2011-07-13 17:56:40 +00001346
1347 // In debuggers, we want to use __unknown_anytype for these
1348 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001349 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001350 ReturnType = Context.UnknownAnyTy;
1351 } else {
1352 ReturnType = Context.getObjCIdType();
1353 }
John McCall7decc9e2010-11-18 06:31:45 +00001354 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001355 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001356 }
Mike Stump11289f42009-09-09 15:08:12 +00001357
Douglas Gregor33823722011-06-11 01:09:30 +00001358 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1359 isSuperMessage);
Alp Toker314cc812014-01-25 16:55:45 +00001360 VK = Expr::getValueKindForType(Method->getReturnType());
Mike Stump11289f42009-09-09 15:08:12 +00001361
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001362 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001363 // Method might have more arguments than selector indicates. This is due
1364 // to addition of c-style arguments in method.
1365 if (Method->param_size() > Sel.getNumArgs())
1366 NumNamedArgs = Method->param_size();
1367 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001368 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001369 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001370 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001371 return false;
1372 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001373
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001374 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001375 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001376 // We can't do any type-checking on a type-dependent argument.
1377 if (Args[i]->isTypeDependent())
1378 continue;
1379
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001380 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001381
Alp Toker03376dc2014-07-07 09:02:20 +00001382 ParmVarDecl *param = Method->parameters()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001383 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001384
John McCall4124c492011-10-17 18:40:02 +00001385 // Strip the unbridged-cast placeholder expression off unless it's
1386 // a consumed argument.
1387 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1388 !param->hasAttr<CFConsumedAttr>())
1389 argExpr = stripARCUnbridgedCast(argExpr);
1390
John McCallea0a39e2012-11-14 00:49:39 +00001391 // If the parameter is __unknown_anytype, infer its type
1392 // from the argument.
1393 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001394 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001395 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001396 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001397 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001398 } else {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001399 Args[i] = argE.get();
John McCallea0a39e2012-11-14 00:49:39 +00001400
John McCallcc5788c2013-03-04 07:34:02 +00001401 // Update the parameter type in-place.
1402 param->setType(paramType);
1403 }
1404 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001405 }
1406
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001407 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001408 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001409 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001410 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001411
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001412 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001413 param);
Fariborz Jahaniana1db7df2014-07-31 17:39:50 +00001414 ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), argExpr);
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001415 if (ArgE.isInvalid())
1416 IsError = true;
1417 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001418 Args[i] = ArgE.getAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001419 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001420
1421 // Promote additional arguments to variadic methods.
1422 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001423 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001424 if (Args[i]->isTypeDependent())
1425 continue;
1426
Jordy Roseaca01f92012-05-12 17:32:52 +00001427 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
Craig Topperc3ec1492014-05-26 06:22:03 +00001428 nullptr);
John Wiegley01296292011-04-08 18:41:53 +00001429 IsError |= Arg.isInvalid();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001430 Args[i] = Arg.get();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001431 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001432 } else {
1433 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001434 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001435 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001436 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001437 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001438 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001439 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001440 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001441 }
1442 }
1443
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001444 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001445
1446 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001447 IsError |= CheckObjCMethodCall(
Craig Topper8c2a2a02014-08-30 16:55:39 +00001448 Method, SelLoc, makeArrayRef(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001449
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001450 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001451}
1452
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001453bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001454 // 'self' is objc 'self' in an objc method only.
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00001455 ObjCMethodDecl *Method =
1456 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1457 return isSelfExpr(RExpr, Method);
1458}
1459
1460bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) {
John McCallfe96e0b2011-11-06 09:01:30 +00001461 if (!method) return false;
1462
John McCall31168b02011-06-15 23:02:42 +00001463 receiver = receiver->IgnoreParenLValueCasts();
1464 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001465 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001466 return true;
1467 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001468}
1469
John McCall526ab472011-10-25 17:37:35 +00001470/// LookupMethodInType - Look up a method in an ObjCObjectType.
1471ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1472 bool isInstance) {
1473 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1474 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1475 // Look it up in the main interface (and categories, etc.)
1476 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1477 return method;
1478
1479 // Okay, look for "private" methods declared in any
1480 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001481 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1482 return method;
John McCall526ab472011-10-25 17:37:35 +00001483 }
1484
1485 // Check qualifiers.
Aaron Ballman1683f7b2014-03-17 15:55:30 +00001486 for (const auto *I : objType->quals())
1487 if (ObjCMethodDecl *method = I->lookupMethod(sel, isInstance))
John McCall526ab472011-10-25 17:37:35 +00001488 return method;
1489
Craig Topperc3ec1492014-05-26 06:22:03 +00001490 return nullptr;
John McCall526ab472011-10-25 17:37:35 +00001491}
1492
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001493/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1494/// list of a qualified objective pointer type.
1495ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1496 const ObjCObjectPointerType *OPT,
1497 bool Instance)
1498{
Craig Topperc3ec1492014-05-26 06:22:03 +00001499 ObjCMethodDecl *MD = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +00001500 for (const auto *PROTO : OPT->quals()) {
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001501 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1502 return MD;
1503 }
1504 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001505 return nullptr;
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001506}
1507
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001508/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1509/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001510ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001511HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001512 Expr *BaseExpr, SourceLocation OpLoc,
1513 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001514 SourceLocation MemberLoc,
1515 SourceLocation SuperLoc, QualType SuperType,
1516 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001517 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1518 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001519
Benjamin Kramer365082d2012-05-19 16:34:46 +00001520 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001521 Diag(MemberLoc, diag::err_invalid_property_name)
1522 << MemberName << QualType(OPT, 0);
1523 return ExprError();
1524 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001525
1526 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001527
Douglas Gregor4123a862011-11-14 22:10:01 +00001528 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1529 : BaseExpr->getSourceRange();
1530 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001531 diag::err_property_not_found_forward_class,
1532 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001533 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001534
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001535 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001536 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001537 // Check whether we can reference this property.
1538 if (DiagnoseUseOfDecl(PD, MemberLoc))
1539 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001540 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001541 return new (Context)
1542 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1543 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001544 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001545 return new (Context)
1546 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1547 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001548 }
1549 // Check protocols on qualified interfaces.
Aaron Ballman83731462014-03-17 16:14:00 +00001550 for (const auto *I : OPT->quals())
1551 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001552 // Check whether we can reference this property.
1553 if (DiagnoseUseOfDecl(PD, MemberLoc))
1554 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001555
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001556 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001557 return new (Context) ObjCPropertyRefExpr(
1558 PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc,
1559 SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001560 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001561 return new (Context)
1562 ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue,
1563 OK_ObjCProperty, MemberLoc, BaseExpr);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001564 }
1565 // If that failed, look for an "implicit" property by seeing if the nullary
1566 // selector is implemented.
1567
1568 // FIXME: The logic for looking up nullary and unary selectors should be
1569 // shared with the code in ActOnInstanceMessage.
1570
1571 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1572 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001573
1574 // May be founf in property's qualified list.
1575 if (!Getter)
1576 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001577
1578 // If this reference is in an @implementation, check for 'private' methods.
1579 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001580 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001581
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001582 if (Getter) {
1583 // Check if we can reference this property.
1584 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1585 return ExprError();
1586 }
1587 // If we found a getter then this may be a valid dot-reference, we
1588 // will look for the matching setter, in case it is needed.
1589 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001590 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1591 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001592 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001593
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001594 // May be founf in property's qualified list.
1595 if (!Setter)
1596 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1597
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001598 if (!Setter) {
1599 // If this reference is in an @implementation, also check for 'private'
1600 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001601 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001602 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001603
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001604 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1605 return ExprError();
1606
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001607 // Special warning if member name used in a property-dot for a setter accessor
1608 // does not use a property with same name; e.g. obj.X = ... for a property with
1609 // name 'x'.
1610 if (Setter && Setter->isImplicit() && Setter->isPropertyAccessor()
1611 && !IFace->FindPropertyDeclaration(Member)) {
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001612 if (const ObjCPropertyDecl *PDecl = Setter->findPropertyDecl()) {
1613 // Do not warn if user is using property-dot syntax to make call to
1614 // user named setter.
1615 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter))
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001616 Diag(MemberLoc,
1617 diag::warn_property_access_suggest)
1618 << MemberName << QualType(OPT, 0) << PDecl->getName()
1619 << FixItHint::CreateReplacement(MemberLoc, PDecl->getName());
Fariborz Jahanian4eda2c02014-08-15 17:39:00 +00001620 }
Fariborz Jahanian0b1d2882014-08-08 22:33:24 +00001621 }
1622
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001623 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001624 if (Super)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001625 return new (Context)
1626 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1627 OK_ObjCProperty, MemberLoc, SuperLoc, SuperType);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001628 else
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001629 return new (Context)
1630 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1631 OK_ObjCProperty, MemberLoc, BaseExpr);
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001632
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001633 }
1634
1635 // Attempt to correct for typos in property names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001636 if (TypoCorrection Corrected =
1637 CorrectTypo(DeclarationNameInfo(MemberName, MemberLoc),
1638 LookupOrdinaryName, nullptr, nullptr,
1639 llvm::make_unique<DeclFilterCCC<ObjCPropertyDecl>>(),
1640 CTK_ErrorRecovery, IFace, false, OPT)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001641 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1642 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001643 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001644 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1645 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001646 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001647 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001648 ObjCInterfaceDecl *ClassDeclared;
1649 if (ObjCIvarDecl *Ivar =
1650 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1651 QualType T = Ivar->getType();
1652 if (const ObjCObjectPointerType * OBJPT =
1653 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001654 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001655 diag::err_property_not_as_forward_class,
1656 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001657 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001658 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001659 Diag(MemberLoc,
1660 diag::err_ivar_access_using_property_syntax_suggest)
1661 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1662 << FixItHint::CreateReplacement(OpLoc, "->");
1663 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001664 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001665
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001666 Diag(MemberLoc, diag::err_property_not_found)
1667 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001668 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001669 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001670 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001671 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001672}
1673
1674
1675
John McCalldadc5752010-08-24 06:29:42 +00001676ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001677ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1678 IdentifierInfo &propertyName,
1679 SourceLocation receiverNameLoc,
1680 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001681
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001682 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001683 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1684 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001685
1686 bool IsSuper = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00001687 if (!IFace) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001688 // If the "receiver" is 'super' in a method, handle it as an expression-like
1689 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001690 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001691 IsSuper = true;
1692
Eli Friedman24af8502012-02-03 22:47:37 +00001693 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001694 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) {
1695 if (CurMethod->isInstanceMethod()) {
1696 ObjCInterfaceDecl *Super = Class->getSuperClass();
1697 if (!Super) {
1698 // The current class does not have a superclass.
1699 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1700 << Class->getIdentifier();
1701 return ExprError();
1702 }
1703 QualType T = Context.getObjCInterfaceType(Super);
1704 T = Context.getObjCObjectPointerType(T);
1705
1706 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
1707 /*BaseExpr*/nullptr,
1708 SourceLocation()/*OpLoc*/,
1709 &propertyName,
1710 propertyNameLoc,
1711 receiverNameLoc, T, true);
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001712 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001713
Fariborz Jahanian86dd4562015-01-20 16:53:34 +00001714 // Otherwise, if this is a class method, try dispatching to our
1715 // superclass.
1716 IFace = Class->getSuperClass();
Chris Lattnera36ec422010-04-11 08:28:14 +00001717 }
Chris Lattnera36ec422010-04-11 08:28:14 +00001718 }
John McCall5f2d5562011-02-03 09:00:02 +00001719 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001720
1721 if (!IFace) {
Alp Tokerec543272013-12-24 09:48:30 +00001722 Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier
1723 << tok::l_paren;
Chris Lattnera36ec422010-04-11 08:28:14 +00001724 return ExprError();
1725 }
1726 }
1727
1728 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001729 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001730 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001731
1732 // If this reference is in an @implementation, check for 'private' methods.
1733 if (!Getter)
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001734 Getter = IFace->lookupPrivateClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001735
1736 if (Getter) {
1737 // FIXME: refactor/share with ActOnMemberReference().
1738 // Check if we can reference this property.
1739 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1740 return ExprError();
1741 }
Mike Stump11289f42009-09-09 15:08:12 +00001742
Steve Naroff9527bbf2009-03-09 21:12:44 +00001743 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001744 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001745 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1746 PP.getSelectorTable(),
1747 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001748
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001749 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001750 if (!Setter) {
1751 // If this reference is in an @implementation, also check for 'private'
1752 // methods.
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +00001753 Setter = IFace->lookupPrivateClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001754 }
1755 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001756 if (!Setter)
1757 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001758
1759 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1760 return ExprError();
1761
1762 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001763 if (IsSuper)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001764 return new (Context)
1765 ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue,
1766 OK_ObjCProperty, propertyNameLoc, receiverNameLoc,
1767 Context.getObjCInterfaceType(IFace));
Douglas Gregor33823722011-06-11 01:09:30 +00001768
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001769 return new (Context) ObjCPropertyRefExpr(
1770 Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty,
1771 propertyNameLoc, receiverNameLoc, IFace);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001772 }
1773 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1774 << &propertyName << Context.getObjCInterfaceType(IFace));
1775}
1776
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001777namespace {
1778
1779class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1780 public:
1781 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1782 // Determine whether "super" is acceptable in the current context.
1783 if (Method && Method->getClassInterface())
1784 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1785 }
1786
Craig Toppere14c0f82014-03-12 04:55:44 +00001787 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001788 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1789 candidate.isKeyword("super");
1790 }
1791};
1792
1793}
1794
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001795Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001796 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001797 SourceLocation NameLoc,
1798 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001799 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001800 ParsedType &ReceiverType) {
1801 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001802
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001803 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001804 // messaging super. If the identifier is "super" and there is a
1805 // trailing dot, it's an instance message.
1806 if (IsSuper && S->isInObjcMethodScope())
1807 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001808
1809 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1810 LookupName(Result, S);
1811
1812 switch (Result.getResultKind()) {
1813 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001814 // Normal name lookup didn't find anything. If we're in an
1815 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001816 // FIXME: This is a hack. Ivar lookup should be part of normal
1817 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001818 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001819 if (!Method->getClassInterface()) {
1820 // Fall back: let the parser try to parse it as an instance message.
1821 return ObjCInstanceMessage;
1822 }
1823
Douglas Gregorca7136b2010-04-19 20:09:36 +00001824 ObjCInterfaceDecl *ClassDeclared;
1825 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1826 ClassDeclared))
1827 return ObjCInstanceMessage;
1828 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001829
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001830 // Break out; we'll perform typo correction below.
1831 break;
1832
1833 case LookupResult::NotFoundInCurrentInstantiation:
1834 case LookupResult::FoundOverloaded:
1835 case LookupResult::FoundUnresolvedValue:
1836 case LookupResult::Ambiguous:
1837 Result.suppressDiagnostics();
1838 return ObjCInstanceMessage;
1839
1840 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001841 // If the identifier is a class or not, and there is a trailing dot,
1842 // it's an instance message.
1843 if (HasTrailingDot)
1844 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001845 // We found something. If it's a type, then we have a class
1846 // message. Otherwise, it's an instance message.
1847 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001848 QualType T;
1849 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1850 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001851 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001852 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001853 DiagnoseUseOfDecl(Type, NameLoc);
1854 }
1855 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001856 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001857
Douglas Gregore5798dc2010-04-21 20:38:13 +00001858 // We have a class message, and T is the type we're
1859 // messaging. Build source-location information for it.
1860 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001861 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001862 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001863 }
1864 }
1865
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001866 if (TypoCorrection Corrected = CorrectTypo(
1867 Result.getLookupNameInfo(), Result.getLookupKind(), S, nullptr,
1868 llvm::make_unique<ObjCInterfaceOrSuperCCC>(getCurMethodDecl()),
1869 CTK_ErrorRecovery, nullptr, false, nullptr, false)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001870 if (Corrected.isKeyword()) {
1871 // If we've found the keyword "super" (the only keyword that would be
1872 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00001873 diagnoseTypo(Corrected,
1874 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001875 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001876 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00001877 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001878 // If we found a declaration, correct when it refers to an Objective-C
1879 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00001880 diagnoseTypo(Corrected,
1881 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001882 QualType T = Context.getObjCInterfaceType(Class);
1883 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1884 ReceiverType = CreateParsedType(T, TSInfo);
1885 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001886 }
1887 }
Richard Smithf9b15102013-08-17 00:46:16 +00001888
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001889 // Fall back: let the parser try to parse it as an instance message.
1890 return ObjCInstanceMessage;
1891}
Steve Naroff9527bbf2009-03-09 21:12:44 +00001892
John McCalldadc5752010-08-24 06:29:42 +00001893ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001894 SourceLocation SuperLoc,
1895 Selector Sel,
1896 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00001897 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001898 SourceLocation RBracLoc,
1899 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001900 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00001901 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00001902 if (!Method) {
1903 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1904 return ExprError();
1905 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001906
Douglas Gregor4fdba132010-04-21 20:01:04 +00001907 ObjCInterfaceDecl *Class = Method->getClassInterface();
1908 if (!Class) {
1909 Diag(SuperLoc, diag::error_no_super_class_message)
1910 << Method->getDeclName();
1911 return ExprError();
1912 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001913
Douglas Gregor4fdba132010-04-21 20:01:04 +00001914 ObjCInterfaceDecl *Super = Class->getSuperClass();
1915 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001916 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00001917 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1918 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001919 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00001920 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001921
Douglas Gregor4fdba132010-04-21 20:01:04 +00001922 // We are in a method whose class has a superclass, so 'super'
1923 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00001924 if (Method->getSelector() == Sel)
1925 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00001926
Jordan Rose2afd6612012-10-19 16:05:26 +00001927 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00001928 // Since we are in an instance method, this is an instance
1929 // message to the superclass instance.
1930 QualType SuperTy = Context.getObjCInterfaceType(Super);
1931 SuperTy = Context.getObjCObjectPointerType(SuperTy);
Craig Topperc3ec1492014-05-26 06:22:03 +00001932 return BuildInstanceMessage(nullptr, SuperTy, SuperLoc,
1933 Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001934 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001935 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00001936
1937 // Since we are in a class method, this is a class message to
1938 // the superclass.
Craig Topperc3ec1492014-05-26 06:22:03 +00001939 return BuildClassMessage(/*ReceiverTypeInfo=*/nullptr,
Douglas Gregor4fdba132010-04-21 20:01:04 +00001940 Context.getObjCInterfaceType(Super),
Craig Topperc3ec1492014-05-26 06:22:03 +00001941 SuperLoc, Sel, /*Method=*/nullptr,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001942 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001943}
1944
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001945
1946ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1947 bool isSuperReceiver,
1948 SourceLocation Loc,
1949 Selector Sel,
1950 ObjCMethodDecl *Method,
1951 MultiExprArg Args) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001952 TypeSourceInfo *receiverTypeInfo = nullptr;
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001953 if (!ReceiverType.isNull())
1954 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1955
1956 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1957 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1958 Sel, Method, Loc, Loc, Loc, Args,
1959 /*isImplicit=*/true);
1960
1961}
1962
Ted Kremeneke65b0862012-03-06 20:05:56 +00001963static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1964 unsigned DiagID,
1965 bool (*refactor)(const ObjCMessageExpr *,
1966 const NSAPI &, edit::Commit &)) {
1967 SourceLocation MsgLoc = Msg->getExprLoc();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001968 if (S.Diags.isIgnored(DiagID, MsgLoc))
Ted Kremeneke65b0862012-03-06 20:05:56 +00001969 return;
1970
1971 SourceManager &SM = S.SourceMgr;
1972 edit::Commit ECommit(SM, S.LangOpts);
1973 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1974 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1975 << Msg->getSelector() << Msg->getSourceRange();
1976 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1977 if (!ECommit.isCommitable())
1978 return;
1979 for (edit::Commit::edit_iterator
1980 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1981 const edit::Commit::Edit &Edit = *I;
1982 switch (Edit.Kind) {
1983 case edit::Commit::Act_Insert:
1984 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1985 Edit.Text,
1986 Edit.BeforePrev));
1987 break;
1988 case edit::Commit::Act_InsertFromRange:
1989 Builder.AddFixItHint(
1990 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1991 Edit.getInsertFromRange(SM),
1992 Edit.BeforePrev));
1993 break;
1994 case edit::Commit::Act_Remove:
1995 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1996 break;
1997 }
1998 }
1999 }
2000}
2001
2002static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
2003 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
2004 edit::rewriteObjCRedundantCallWithLiteral);
2005}
2006
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002007/// \brief Diagnose use of %s directive in an NSString which is being passed
2008/// as formatting string to formatting method.
2009static void
2010DiagnoseCStringFormatDirectiveInObjCAPI(Sema &S,
2011 ObjCMethodDecl *Method,
2012 Selector Sel,
2013 Expr **Args, unsigned NumArgs) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002014 unsigned Idx = 0;
2015 bool Format = false;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002016 ObjCStringFormatFamily SFFamily = Sel.getStringFormatFamily();
2017 if (SFFamily == ObjCStringFormatFamily::SFF_NSString) {
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002018 Idx = 0;
2019 Format = true;
2020 }
2021 else if (Method) {
2022 for (const auto *I : Method->specific_attrs<FormatAttr>()) {
2023 if (S.GetFormatNSStringIdx(I, Idx)) {
2024 Format = true;
2025 break;
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002026 }
2027 }
2028 }
Fariborz Jahanianfba4fe62014-09-11 19:13:23 +00002029 if (!Format || NumArgs <= Idx)
2030 return;
2031
2032 Expr *FormatExpr = Args[Idx];
2033 if (ObjCStringLiteral *OSL =
2034 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) {
2035 StringLiteral *FormatString = OSL->getString();
2036 if (S.FormatStringHasSArg(FormatString)) {
2037 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
2038 << "%s" << 0 << 0;
2039 if (Method)
2040 S.Diag(Method->getLocation(), diag::note_method_declared_at)
2041 << Method->getDeclName();
2042 }
2043 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002044}
2045
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002046/// \brief Build an Objective-C class message expression.
2047///
2048/// This routine takes care of both normal class messages and
2049/// class messages to the superclass.
2050///
2051/// \param ReceiverTypeInfo Type source information that describes the
2052/// receiver of this message. This may be NULL, in which case we are
2053/// sending to the superclass and \p SuperLoc must be a valid source
2054/// location.
2055
2056/// \param ReceiverType The type of the object receiving the
2057/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2058/// type as that refers to. For a superclass send, this is the type of
2059/// the superclass.
2060///
2061/// \param SuperLoc The location of the "super" keyword in a
2062/// superclass message.
2063///
2064/// \param Sel The selector to which the message is being sent.
2065///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002066/// \param Method The method that this class message is invoking, if
2067/// already known.
2068///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002069/// \param LBracLoc The location of the opening square bracket ']'.
2070///
James Dennettffad8b72012-06-22 08:10:18 +00002071/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002072///
James Dennettffad8b72012-06-22 08:10:18 +00002073/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002074ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002075 QualType ReceiverType,
2076 SourceLocation SuperLoc,
2077 Selector Sel,
2078 ObjCMethodDecl *Method,
2079 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002080 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002081 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002082 MultiExprArg ArgsIn,
2083 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002084 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002085 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002086 if (LBracLoc.isInvalid()) {
2087 Diag(Loc, diag::err_missing_open_square_message_send)
2088 << FixItHint::CreateInsertion(Loc, "[");
2089 LBracLoc = Loc;
2090 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002091 SourceLocation SelLoc;
2092 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2093 SelLoc = SelectorLocs.front();
2094 else
2095 SelLoc = Loc;
2096
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002097 if (ReceiverType->isDependentType()) {
2098 // If the receiver type is dependent, we can't type-check anything
2099 // at this point. Build a dependent expression.
2100 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002101 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002102 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002103 return ObjCMessageExpr::Create(
2104 Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel,
2105 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs), RBracLoc,
2106 isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002107 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002108
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002109 // Find the class to which we are sending this message.
Craig Topperc3ec1492014-05-26 06:22:03 +00002110 ObjCInterfaceDecl *Class = nullptr;
John McCall8b07ec22010-05-15 11:32:37 +00002111 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2112 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002113 Diag(Loc, diag::err_invalid_receiver_class_message)
2114 << ReceiverType;
2115 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002116 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002117 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002118 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002119 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002120 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002121 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002122 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002123 SourceRange TypeRange
2124 = SuperLoc.isValid()? SourceRange(SuperLoc)
2125 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002126 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002127 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002128 ? diag::err_arc_receiver_forward_class
2129 : diag::warn_receiver_forward_class),
2130 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002131 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002132 Method = LookupFactoryMethodInGlobalPool(Sel,
2133 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002134 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002135 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2136 << Method->getDeclName();
2137 }
2138 if (!Method)
2139 Method = Class->lookupClassMethod(Sel);
2140
2141 // If we have an implementation in scope, check "private" methods.
2142 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002143 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002144
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002145 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002146 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002147 }
Mike Stump11289f42009-09-09 15:08:12 +00002148
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002149 // Check the argument types and determine the result type.
2150 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002151 ExprValueKind VK = VK_RValue;
2152
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002153 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002154 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002155 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2156 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002157 Method, true,
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002158 SuperLoc.isValid(), LBracLoc, RBracLoc,
2159 SourceRange(),
Douglas Gregor33823722011-06-11 01:09:30 +00002160 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002161 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002162
Alp Toker314cc812014-01-25 16:55:45 +00002163 if (Method && !Method->getReturnType()->isVoidType() &&
2164 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002165 diag::err_illegal_message_expr_incomplete_type))
2166 return ExprError();
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002167
Fariborz Jahaniane8b45502014-08-22 19:52:49 +00002168 // Warn about explicit call of +initialize on its own class. But not on 'super'.
Fariborz Jahanian42292282014-08-25 21:27:38 +00002169 if (Method && Method->getMethodFamily() == OMF_initialize) {
2170 if (!SuperLoc.isValid()) {
2171 const ObjCInterfaceDecl *ID =
2172 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext());
2173 if (ID == Class) {
2174 Diag(Loc, diag::warn_direct_initialize_call);
2175 Diag(Method->getLocation(), diag::note_method_declared_at)
2176 << Method->getDeclName();
2177 }
2178 }
2179 else if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2180 // [super initialize] is allowed only within an +initialize implementation
2181 if (CurMeth->getMethodFamily() != OMF_initialize) {
2182 Diag(Loc, diag::warn_direct_super_initialize_call);
2183 Diag(Method->getLocation(), diag::note_method_declared_at)
2184 << Method->getDeclName();
2185 Diag(CurMeth->getLocation(), diag::note_method_declared_at)
2186 << CurMeth->getDeclName();
2187 }
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002188 }
2189 }
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002190
2191 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2192
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002193 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002194 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002195 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002196 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002197 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002198 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002199 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002200 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002201 else {
John McCall7decc9e2010-11-18 06:31:45 +00002202 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002203 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002204 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002205 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002206 if (!isImplicit)
2207 checkCocoaAPI(*this, Result);
2208 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002209 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002210}
2211
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002212// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002213// ArgExprs is optional - if it is present, the number of expressions
2214// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002215ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002216 ParsedType Receiver,
2217 Selector Sel,
2218 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002219 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002220 SourceLocation RBracLoc,
2221 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002222 TypeSourceInfo *ReceiverTypeInfo;
2223 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2224 if (ReceiverType.isNull())
2225 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002226
Mike Stump11289f42009-09-09 15:08:12 +00002227
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002228 if (!ReceiverTypeInfo)
2229 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2230
2231 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Craig Topperc3ec1492014-05-26 06:22:03 +00002232 /*SuperLoc=*/SourceLocation(), Sel,
2233 /*Method=*/nullptr, LBracLoc, SelectorLocs, RBracLoc,
2234 Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002235}
2236
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002237ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2238 QualType ReceiverType,
2239 SourceLocation Loc,
2240 Selector Sel,
2241 ObjCMethodDecl *Method,
2242 MultiExprArg Args) {
2243 return BuildInstanceMessage(Receiver, ReceiverType,
2244 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2245 Sel, Method, Loc, Loc, Loc, Args,
2246 /*isImplicit=*/true);
2247}
2248
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002249/// \brief Build an Objective-C instance message expression.
2250///
2251/// This routine takes care of both normal instance messages and
2252/// instance messages to the superclass instance.
2253///
2254/// \param Receiver The expression that computes the object that will
2255/// receive this message. This may be empty, in which case we are
2256/// sending to the superclass instance and \p SuperLoc must be a valid
2257/// source location.
2258///
2259/// \param ReceiverType The (static) type of the object receiving the
2260/// message. When a \p Receiver expression is provided, this is the
2261/// same type as that expression. For a superclass instance send, this
2262/// is a pointer to the type of the superclass.
2263///
2264/// \param SuperLoc The location of the "super" keyword in a
2265/// superclass instance message.
2266///
2267/// \param Sel The selector to which the message is being sent.
2268///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002269/// \param Method The method that this instance message is invoking, if
2270/// already known.
2271///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002272/// \param LBracLoc The location of the opening square bracket ']'.
2273///
James Dennettffad8b72012-06-22 08:10:18 +00002274/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002275///
James Dennettffad8b72012-06-22 08:10:18 +00002276/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002277ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002278 QualType ReceiverType,
2279 SourceLocation SuperLoc,
2280 Selector Sel,
2281 ObjCMethodDecl *Method,
2282 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002283 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002284 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002285 MultiExprArg ArgsIn,
2286 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002287 // The location of the receiver.
2288 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002289 SourceRange RecRange =
2290 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2291 SourceLocation SelLoc;
2292 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2293 SelLoc = SelectorLocs.front();
2294 else
2295 SelLoc = Loc;
2296
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002297 if (LBracLoc.isInvalid()) {
2298 Diag(Loc, diag::err_missing_open_square_message_send)
2299 << FixItHint::CreateInsertion(Loc, "[");
2300 LBracLoc = Loc;
2301 }
2302
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002303 // If we have a receiver expression, perform appropriate promotions
2304 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002305 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002306 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002307 ExprResult Result;
2308 if (Receiver->getType() == Context.UnknownAnyTy)
2309 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2310 else
2311 Result = CheckPlaceholderExpr(Receiver);
2312 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002313 Receiver = Result.get();
John McCall4124c492011-10-17 18:40:02 +00002314 }
2315
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002316 if (Receiver->isTypeDependent()) {
2317 // If the receiver is type-dependent, we can't type-check anything
2318 // at this point. Build a dependent expression.
2319 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002320 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002321 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002322 return ObjCMessageExpr::Create(
2323 Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel,
2324 SelectorLocs, /*Method=*/nullptr, makeArrayRef(Args, NumArgs),
2325 RBracLoc, isImplicit);
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002326 }
2327
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002328 // If necessary, apply function/array conversion to the receiver.
2329 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002330 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2331 if (Result.isInvalid())
2332 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002333 Receiver = Result.get();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002334 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002335
2336 // If the receiver is an ObjC pointer, a block pointer, or an
2337 // __attribute__((NSObject)) pointer, we don't need to do any
2338 // special conversion in order to look up a receiver.
2339 if (ReceiverType->isObjCRetainableType()) {
2340 // do nothing
2341 } else if (!getLangOpts().ObjCAutoRefCount &&
2342 !Context.getObjCIdType().isNull() &&
2343 (ReceiverType->isPointerType() ||
2344 ReceiverType->isIntegerType())) {
2345 // Implicitly convert integers and pointers to 'id' but emit a warning.
2346 // But not in ARC.
2347 Diag(Loc, diag::warn_bad_receiver_type)
2348 << ReceiverType
2349 << Receiver->getSourceRange();
2350 if (ReceiverType->isPointerType()) {
2351 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002352 CK_CPointerToObjCPointerCast).get();
John McCall80c93a02013-03-01 09:20:14 +00002353 } else {
2354 // TODO: specialized warning on null receivers?
2355 bool IsNull = Receiver->isNullPointerConstant(Context,
2356 Expr::NPC_ValueDependentIsNull);
2357 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2358 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002359 Kind).get();
John McCall80c93a02013-03-01 09:20:14 +00002360 }
2361 ReceiverType = Receiver->getType();
2362 } else if (getLangOpts().CPlusPlus) {
Douglas Gregor4b60a152013-11-07 22:34:54 +00002363 // The receiver must be a complete type.
2364 if (RequireCompleteType(Loc, Receiver->getType(),
2365 diag::err_incomplete_receiver_type))
2366 return ExprError();
2367
John McCall80c93a02013-03-01 09:20:14 +00002368 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2369 if (result.isUsable()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002370 Receiver = result.get();
John McCall80c93a02013-03-01 09:20:14 +00002371 ReceiverType = Receiver->getType();
2372 }
2373 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002374 }
2375
John McCall80c93a02013-03-01 09:20:14 +00002376 // There's a somewhat weird interaction here where we assume that we
2377 // won't actually have a method unless we also don't need to do some
2378 // of the more detailed type-checking on the receiver.
2379
Douglas Gregorb5186b12010-04-22 17:01:48 +00002380 if (!Method) {
2381 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002382 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002383 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002384 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2385 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002386 SourceRange(LBracLoc, RBracLoc),
2387 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002388 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002389 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002390 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002391 receiverIsId);
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002392 if (Method) {
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002393 if (ObjCMethodDecl *BestMethod =
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002394 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
Fariborz Jahanian0ded4242014-08-13 21:24:14 +00002395 Method = BestMethod;
Sylvestre Ledru30f17082014-11-17 18:26:39 +00002396 if (!AreMultipleMethodsInGlobalPool(Sel, Method->isInstanceMethod()))
2397 DiagnoseUseOfDecl(Method, SelLoc);
Fariborz Jahanian05e77f82014-11-07 23:51:15 +00002398 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002399 } else if (ReceiverType->isObjCClassType() ||
2400 ReceiverType->isObjCQualifiedClassType()) {
2401 // Handle messages to Class.
Nico Weber2e0c8f72014-12-27 03:58:08 +00002402 // We allow sending a message to a qualified Class ("Class<foo>"), which
2403 // is ok as long as one of the protocols implements the selector (if not,
2404 // warn).
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002405 if (const ObjCObjectPointerType *QClassTy
2406 = ReceiverType->getAsObjCQualifiedClassType()) {
2407 // Search protocols for class methods.
2408 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2409 if (!Method) {
2410 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2411 // warn if instance method found for a Class message.
2412 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002413 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002414 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002415 Diag(Method->getLocation(), diag::note_method_declared_at)
2416 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002417 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002418 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002419 } else {
2420 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2421 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2422 // First check the public methods in the class interface.
2423 Method = ClassDecl->lookupClassMethod(Sel);
2424
2425 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002426 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002427 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002428 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002429 return ExprError();
2430 }
2431 if (!Method) {
2432 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002433 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002434 Method = LookupFactoryMethodInGlobalPool(Sel,
2435 SourceRange(LBracLoc, RBracLoc),
2436 true);
2437 if (!Method) {
2438 // If no class (factory) method was found, check if an _instance_
2439 // method of the same name exists in the root class only.
2440 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002441 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002442 true);
2443 if (Method)
2444 if (const ObjCInterfaceDecl *ID =
2445 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2446 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002447 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002448 << Sel << SourceRange(LBracLoc, RBracLoc);
2449 }
2450 }
Fariborz Jahaniand288fad2014-08-13 23:38:04 +00002451 if (Method)
2452 if (ObjCMethodDecl *BestMethod =
2453 SelectBestMethod(Sel, ArgsIn, Method->isInstanceMethod()))
2454 Method = BestMethod;
Douglas Gregor9a129192010-04-21 00:45:42 +00002455 }
2456 }
2457 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002458 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00002459 ObjCInterfaceDecl *ClassDecl = nullptr;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002460
2461 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2462 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002463 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002464 if (const ObjCObjectPointerType *QIdTy
2465 = ReceiverType->getAsObjCQualifiedIdType()) {
2466 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002467 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2468 if (!Method)
2469 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002470 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002471 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002472 } else if (const ObjCObjectPointerType *OCIType
2473 = ReceiverType->getAsObjCInterfacePointerType()) {
2474 // We allow sending a message to a pointer to an interface (an object).
2475 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002476
Douglas Gregor4123a862011-11-14 22:10:01 +00002477 // Try to complete the type. Under ARC, this is a hard error from which
2478 // we don't try to recover.
Craig Topperc3ec1492014-05-26 06:22:03 +00002479 const ObjCInterfaceDecl *forwardClass = nullptr;
Douglas Gregor4123a862011-11-14 22:10:01 +00002480 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002481 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002482 ? diag::err_arc_receiver_forward_instance
2483 : diag::warn_receiver_forward_instance,
2484 Receiver? Receiver->getSourceRange()
2485 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002486 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002487 return ExprError();
2488
2489 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002490 Diag(Receiver ? Receiver->getLocStart()
2491 : SuperLoc, diag::note_receiver_is_id);
Craig Topperc3ec1492014-05-26 06:22:03 +00002492 Method = nullptr;
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002493 } else {
2494 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002495 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002496
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002497 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002498 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002499 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2500
Douglas Gregorb5186b12010-04-22 17:01:48 +00002501 if (!Method) {
2502 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002503 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002504
David Blaikiebbafb8a2012-03-11 07:00:24 +00002505 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002506 Diag(SelLoc, diag::err_arc_may_not_respond)
2507 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002508 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002509 return ExprError();
2510 }
2511
Douglas Gregor486b74e2011-09-27 16:10:05 +00002512 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002513 // If we still haven't found a method, look in the global pool. This
2514 // behavior isn't very desirable, however we need it for GCC
2515 // compatibility. FIXME: should we deviate??
2516 if (OCIType->qual_empty()) {
2517 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002518 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002519 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002520 Diag(SelLoc, diag::warn_maynot_respond)
2521 << OCIType->getInterfaceDecl()->getIdentifier()
2522 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002523 }
2524 }
2525 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002526 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002527 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002528 } else {
John McCall80c93a02013-03-01 09:20:14 +00002529 // Reject other random receiver types (e.g. structs).
2530 Diag(Loc, diag::err_bad_receiver_type)
2531 << ReceiverType << Receiver->getSourceRange();
2532 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002533 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002534 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002535 }
Mike Stump11289f42009-09-09 15:08:12 +00002536
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002537 FunctionScopeInfo *DIFunctionScopeInfo =
2538 (Method && Method->getMethodFamily() == OMF_init)
Craig Topperc3ec1492014-05-26 06:22:03 +00002539 ? getEnclosingFunction() : nullptr;
2540
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002541 if (DIFunctionScopeInfo &&
2542 DIFunctionScopeInfo->ObjCIsDesignatedInit &&
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002543 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2544 bool isDesignatedInitChain = false;
2545 if (SuperLoc.isValid()) {
2546 if (const ObjCObjectPointerType *
2547 OCIType = ReceiverType->getAsObjCInterfacePointerType()) {
2548 if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) {
Argyrios Kyrtzidisd664a342013-12-13 03:48:17 +00002549 // Either we know this is a designated initializer or we
2550 // conservatively assume it because we don't know for sure.
2551 if (!ID->declaresOrInheritsDesignatedInitializers() ||
2552 ID->isDesignatedInitializer(Sel)) {
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002553 isDesignatedInitChain = true;
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002554 DIFunctionScopeInfo->ObjCWarnForNoDesignatedInitChain = false;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002555 }
2556 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002557 }
2558 }
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002559 if (!isDesignatedInitChain) {
Craig Topperc3ec1492014-05-26 06:22:03 +00002560 const ObjCMethodDecl *InitMethod = nullptr;
Argyrios Kyrtzidisfcded9b2013-12-03 21:11:43 +00002561 bool isDesignated =
2562 getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod);
2563 assert(isDesignated && InitMethod);
2564 (void)isDesignated;
2565 Diag(SelLoc, SuperLoc.isValid() ?
2566 diag::warn_objc_designated_init_non_designated_init_call :
2567 diag::warn_objc_designated_init_non_super_designated_init_call);
2568 Diag(InitMethod->getLocation(),
2569 diag::note_objc_designated_init_marked_here);
2570 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +00002571 }
2572
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002573 if (DIFunctionScopeInfo &&
2574 DIFunctionScopeInfo->ObjCIsSecondaryInit &&
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002575 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
2576 if (SuperLoc.isValid()) {
2577 Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call);
2578 } else {
Fariborz Jahanianba419ce2014-03-17 21:41:40 +00002579 DIFunctionScopeInfo->ObjCWarnForNoInitDelegation = false;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +00002580 }
2581 }
2582
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002583 // Check the message arguments.
2584 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002585 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002586 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002587 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002588 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2589 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002590 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2591 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002592 ClassMessage, SuperLoc.isValid(),
Fariborz Jahanian19c2e2f2014-08-19 23:39:17 +00002593 LBracLoc, RBracLoc, RecRange, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002594 return ExprError();
Alp Toker314cc812014-01-25 16:55:45 +00002595
2596 if (Method && !Method->getReturnType()->isVoidType() &&
2597 RequireCompleteType(LBracLoc, Method->getReturnType(),
Douglas Gregoraec93c62011-01-11 03:23:19 +00002598 diag::err_illegal_message_expr_incomplete_type))
2599 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002600
John McCall31168b02011-06-15 23:02:42 +00002601 // In ARC, forbid the user from sending messages to
2602 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002603 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002604 ObjCMethodFamily family =
2605 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2606 switch (family) {
2607 case OMF_init:
2608 if (Method)
2609 checkInitMethod(Method, ReceiverType);
2610
2611 case OMF_None:
2612 case OMF_alloc:
2613 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002614 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002615 case OMF_mutableCopy:
2616 case OMF_new:
2617 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002618 case OMF_initialize:
John McCall31168b02011-06-15 23:02:42 +00002619 break;
2620
2621 case OMF_dealloc:
2622 case OMF_retain:
2623 case OMF_release:
2624 case OMF_autorelease:
2625 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002626 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2627 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002628 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002629
2630 case OMF_performSelector:
2631 if (Method && NumArgs >= 1) {
2632 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2633 Selector ArgSel = SelExp->getSelector();
2634 ObjCMethodDecl *SelMethod =
2635 LookupInstanceMethodInGlobalPool(ArgSel,
2636 SelExp->getSourceRange());
2637 if (!SelMethod)
2638 SelMethod =
2639 LookupFactoryMethodInGlobalPool(ArgSel,
2640 SelExp->getSourceRange());
2641 if (SelMethod) {
2642 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2643 switch (SelFamily) {
2644 case OMF_alloc:
2645 case OMF_copy:
2646 case OMF_mutableCopy:
2647 case OMF_new:
2648 case OMF_self:
2649 case OMF_init:
2650 // Issue error, unless ns_returns_not_retained.
2651 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2652 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002653 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002654 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002655 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2656 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002657 }
2658 break;
2659 default:
2660 // +0 call. OK. unless ns_returns_retained.
2661 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2662 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002663 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002664 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002665 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2666 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002667 }
2668 break;
2669 }
2670 }
2671 } else {
2672 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002673 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002674 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2675 }
2676 }
2677 break;
John McCall31168b02011-06-15 23:02:42 +00002678 }
2679 }
2680
Fariborz Jahanian6485fe42014-09-09 23:10:54 +00002681 DiagnoseCStringFormatDirectiveInObjCAPI(*this, Method, Sel, Args, NumArgs);
2682
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002683 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002684 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002685 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002686 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002687 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002688 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002689 makeArrayRef(Args, NumArgs), RBracLoc,
2690 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002691 else {
John McCall7decc9e2010-11-18 06:31:45 +00002692 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002693 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002694 makeArrayRef(Args, NumArgs), RBracLoc,
2695 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002696 if (!isImplicit)
2697 checkCocoaAPI(*this, Result);
2698 }
John McCall31168b02011-06-15 23:02:42 +00002699
David Blaikiebbafb8a2012-03-11 07:00:24 +00002700 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002701 // In ARC, annotate delegate init calls.
2702 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002703 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002704 // Only consider init calls *directly* in init implementations,
2705 // not within blocks.
2706 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2707 if (method && method->getMethodFamily() == OMF_init) {
2708 // The implicit assignment to self means we also don't want to
2709 // consume the result.
2710 Result->setDelegateInitCall(true);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002711 return Result;
John McCall31168b02011-06-15 23:02:42 +00002712 }
2713 }
2714
2715 // In ARC, check for message sends which are likely to introduce
2716 // retain cycles.
2717 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002718
2719 if (!isImplicit && Method) {
2720 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2721 bool IsWeak =
2722 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2723 if (!IsWeak && Sel.isUnarySelector())
2724 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002725 if (IsWeak &&
2726 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, LBracLoc))
2727 getCurFunction()->recordUseOfWeak(Result, Prop);
Jordan Rose22487652012-10-11 16:06:21 +00002728 }
2729 }
John McCall31168b02011-06-15 23:02:42 +00002730 }
Alex Denisove1d882c2015-03-04 17:55:52 +00002731
2732 CheckObjCCircularContainer(Result);
2733
Douglas Gregoraae38d62010-05-22 05:17:18 +00002734 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002735}
2736
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002737static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2738 if (ObjCSelectorExpr *OSE =
2739 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2740 Selector Sel = OSE->getSelector();
2741 SourceLocation Loc = OSE->getAtLoc();
Chandler Carruth12c8f652015-03-27 00:55:05 +00002742 auto Pos = S.ReferencedSelectors.find(Sel);
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002743 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2744 S.ReferencedSelectors.erase(Pos);
2745 }
2746}
2747
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002748// ActOnInstanceMessage - used for both unary and keyword messages.
2749// ArgExprs is optional - if it is present, the number of expressions
2750// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002751ExprResult Sema::ActOnInstanceMessage(Scope *S,
2752 Expr *Receiver,
2753 Selector Sel,
2754 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002755 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002756 SourceLocation RBracLoc,
2757 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002758 if (!Receiver)
2759 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002760
2761 // A ParenListExpr can show up while doing error recovery with invalid code.
2762 if (isa<ParenListExpr>(Receiver)) {
2763 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2764 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002765 Receiver = Result.get();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002766 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002767
2768 if (RespondsToSelectorSel.isNull()) {
2769 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2770 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2771 }
2772 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002773 RemoveSelectorFromWarningCache(*this, Args[0]);
Craig Topperc3ec1492014-05-26 06:22:03 +00002774
John McCallb268a282010-08-23 23:25:46 +00002775 return BuildInstanceMessage(Receiver, Receiver->getType(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002776 /*SuperLoc=*/SourceLocation(), Sel,
2777 /*Method=*/nullptr, LBracLoc, SelectorLocs,
2778 RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002779}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002780
John McCall31168b02011-06-15 23:02:42 +00002781enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002782 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002783 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002784
2785 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002786 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002787
2788 /// id*, id***, void (^*)(),
2789 ACTC_indirectRetainable,
2790
2791 /// void* might be a normal C type, or it might a CF type.
2792 ACTC_voidPtr,
2793
2794 /// struct A*
2795 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002796};
John McCalle4fe2452011-10-01 01:01:08 +00002797static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2798 return (ACTC == ACTC_retainable ||
2799 ACTC == ACTC_coreFoundation ||
2800 ACTC == ACTC_voidPtr);
2801}
2802static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2803 return ACTC == ACTC_none ||
2804 ACTC == ACTC_voidPtr ||
2805 ACTC == ACTC_coreFoundation;
2806}
2807
John McCall31168b02011-06-15 23:02:42 +00002808static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002809 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002810
2811 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002812 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002813 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002814 isIndirect = true;
2815 }
John McCall31168b02011-06-15 23:02:42 +00002816
2817 // Drill through pointers and arrays recursively.
2818 while (true) {
2819 if (const PointerType *ptr = type->getAs<PointerType>()) {
2820 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002821
2822 // The first level of pointer may be the innermost pointer on a CF type.
2823 if (!isIndirect) {
2824 if (type->isVoidType()) return ACTC_voidPtr;
2825 if (type->isRecordType()) return ACTC_coreFoundation;
2826 }
John McCall31168b02011-06-15 23:02:42 +00002827 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2828 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2829 } else {
2830 break;
2831 }
John McCalle4fe2452011-10-01 01:01:08 +00002832 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002833 }
2834
John McCalle4fe2452011-10-01 01:01:08 +00002835 if (isIndirect) {
2836 if (type->isObjCARCBridgableType())
2837 return ACTC_indirectRetainable;
2838 return ACTC_none;
2839 }
2840
2841 if (type->isObjCARCBridgableType())
2842 return ACTC_retainable;
2843
2844 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002845}
2846
2847namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002848 /// A result from the cast checker.
2849 enum ACCResult {
2850 /// Cannot be casted.
2851 ACC_invalid,
2852
2853 /// Can be safely retained or not retained.
2854 ACC_bottom,
2855
2856 /// Can be casted at +0.
2857 ACC_plusZero,
2858
2859 /// Can be casted at +1.
2860 ACC_plusOne
2861 };
2862 ACCResult merge(ACCResult left, ACCResult right) {
2863 if (left == right) return left;
2864 if (left == ACC_bottom) return right;
2865 if (right == ACC_bottom) return left;
2866 return ACC_invalid;
2867 }
2868
2869 /// A checker which white-lists certain expressions whose conversion
2870 /// to or from retainable type would otherwise be forbidden in ARC.
2871 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2872 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2873
John McCall31168b02011-06-15 23:02:42 +00002874 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002875 ARCConversionTypeClass SourceClass;
2876 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002877 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002878
2879 static bool isCFType(QualType type) {
2880 // Someday this can use ns_bridged. For now, it has to do this.
2881 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002882 }
John McCalle4fe2452011-10-01 01:01:08 +00002883
2884 public:
2885 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002886 ARCConversionTypeClass target, bool diagnose)
2887 : Context(Context), SourceClass(source), TargetClass(target),
2888 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00002889
2890 using super::Visit;
2891 ACCResult Visit(Expr *e) {
2892 return super::Visit(e->IgnoreParens());
2893 }
2894
2895 ACCResult VisitStmt(Stmt *s) {
2896 return ACC_invalid;
2897 }
2898
2899 /// Null pointer constants can be casted however you please.
2900 ACCResult VisitExpr(Expr *e) {
2901 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2902 return ACC_bottom;
2903 return ACC_invalid;
2904 }
2905
2906 /// Objective-C string literals can be safely casted.
2907 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2908 // If we're casting to any retainable type, go ahead. Global
2909 // strings are immune to retains, so this is bottom.
2910 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2911
2912 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002913 }
2914
John McCalle4fe2452011-10-01 01:01:08 +00002915 /// Look through certain implicit and explicit casts.
2916 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002917 switch (e->getCastKind()) {
2918 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00002919 return ACC_bottom;
2920
John McCall31168b02011-06-15 23:02:42 +00002921 case CK_NoOp:
2922 case CK_LValueToRValue:
2923 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002924 case CK_CPointerToObjCPointerCast:
2925 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002926 case CK_AnyPointerToBlockPointerCast:
2927 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00002928
John McCall31168b02011-06-15 23:02:42 +00002929 default:
John McCalle4fe2452011-10-01 01:01:08 +00002930 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002931 }
2932 }
John McCalle4fe2452011-10-01 01:01:08 +00002933
2934 /// Look through unary extension.
2935 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002936 return Visit(e->getSubExpr());
2937 }
John McCalle4fe2452011-10-01 01:01:08 +00002938
2939 /// Ignore the LHS of a comma operator.
2940 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002941 return Visit(e->getRHS());
2942 }
John McCalle4fe2452011-10-01 01:01:08 +00002943
2944 /// Conditional operators are okay if both sides are okay.
2945 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2946 ACCResult left = Visit(e->getTrueExpr());
2947 if (left == ACC_invalid) return ACC_invalid;
2948 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00002949 }
John McCalle4fe2452011-10-01 01:01:08 +00002950
John McCallfe96e0b2011-11-06 09:01:30 +00002951 /// Look through pseudo-objects.
2952 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2953 // If we're getting here, we should always have a result.
2954 return Visit(e->getResultExpr());
2955 }
2956
John McCalle4fe2452011-10-01 01:01:08 +00002957 /// Statement expressions are okay if their result expression is okay.
2958 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002959 return Visit(e->getSubStmt()->body_back());
2960 }
John McCall31168b02011-06-15 23:02:42 +00002961
John McCalle4fe2452011-10-01 01:01:08 +00002962 /// Some declaration references are okay.
2963 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
John McCalle4fe2452011-10-01 01:01:08 +00002964 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
Ben Langmuir443aa4b2015-02-25 20:09:06 +00002965 // References to global constants are okay.
John McCalle4fe2452011-10-01 01:01:08 +00002966 if (isAnyRetainable(TargetClass) &&
2967 isAnyRetainable(SourceClass) &&
2968 var &&
2969 var->getStorageClass() == SC_Extern &&
Ben Langmuir443aa4b2015-02-25 20:09:06 +00002970 var->getType().isConstQualified()) {
2971
2972 // In system headers, they can also be assumed to be immune to retains.
2973 // These are things like 'kCFStringTransformToLatin'.
2974 if (Context.getSourceManager().isInSystemHeader(var->getLocation()))
2975 return ACC_bottom;
2976
2977 return ACC_plusZero;
John McCalle4fe2452011-10-01 01:01:08 +00002978 }
2979
2980 // Nothing else.
2981 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00002982 }
John McCalle4fe2452011-10-01 01:01:08 +00002983
2984 /// Some calls are okay.
2985 ACCResult VisitCallExpr(CallExpr *e) {
2986 if (FunctionDecl *fn = e->getDirectCallee())
2987 if (ACCResult result = checkCallToFunction(fn))
2988 return result;
2989
2990 return super::VisitCallExpr(e);
2991 }
2992
2993 ACCResult checkCallToFunction(FunctionDecl *fn) {
2994 // Require a CF*Ref return type.
Alp Toker314cc812014-01-25 16:55:45 +00002995 if (!isCFType(fn->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00002996 return ACC_invalid;
2997
2998 if (!isAnyRetainable(TargetClass))
2999 return ACC_invalid;
3000
3001 // Honor an explicit 'not retained' attribute.
3002 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
3003 return ACC_plusZero;
3004
3005 // Honor an explicit 'retained' attribute, except that for
3006 // now we're not going to permit implicit handling of +1 results,
3007 // because it's a bit frightening.
3008 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003009 return Diagnose ? ACC_plusOne
3010 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003011
3012 // Recognize this specific builtin function, which is used by CFSTR.
3013 unsigned builtinID = fn->getBuiltinID();
3014 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
3015 return ACC_bottom;
3016
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003017 // Otherwise, don't do anything implicit with an unaudited function.
3018 if (!fn->hasAttr<CFAuditedTransferAttr>())
3019 return ACC_invalid;
3020
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003021 // Otherwise, it's +0 unless it follows the create convention.
3022 if (ento::coreFoundation::followsCreateRule(fn))
3023 return Diagnose ? ACC_plusOne
3024 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00003025
John McCalle4fe2452011-10-01 01:01:08 +00003026 return ACC_plusZero;
3027 }
3028
3029 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
3030 return checkCallToMethod(e->getMethodDecl());
3031 }
3032
3033 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
3034 ObjCMethodDecl *method;
3035 if (e->isExplicitProperty())
3036 method = e->getExplicitProperty()->getGetterMethodDecl();
3037 else
3038 method = e->getImplicitPropertyGetter();
3039 return checkCallToMethod(method);
3040 }
3041
3042 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
3043 if (!method) return ACC_invalid;
3044
3045 // Check for message sends to functions returning CF types. We
3046 // just obey the Cocoa conventions with these, even though the
3047 // return type is CF.
Alp Toker314cc812014-01-25 16:55:45 +00003048 if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType()))
John McCalle4fe2452011-10-01 01:01:08 +00003049 return ACC_invalid;
3050
3051 // If the method is explicitly marked not-retained, it's +0.
3052 if (method->hasAttr<CFReturnsNotRetainedAttr>())
3053 return ACC_plusZero;
3054
3055 // If the method is explicitly marked as returning retained, or its
3056 // selector follows a +1 Cocoa convention, treat it as +1.
3057 if (method->hasAttr<CFReturnsRetainedAttr>())
3058 return ACC_plusOne;
3059
3060 switch (method->getSelector().getMethodFamily()) {
3061 case OMF_alloc:
3062 case OMF_copy:
3063 case OMF_mutableCopy:
3064 case OMF_new:
3065 return ACC_plusOne;
3066
3067 default:
3068 // Otherwise, treat it as +0.
3069 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00003070 }
3071 }
John McCalle4fe2452011-10-01 01:01:08 +00003072 };
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00003073}
3074
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003075bool Sema::isKnownName(StringRef name) {
3076 if (name.empty())
3077 return false;
3078 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003079 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003080 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003081}
3082
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003083static void addFixitForObjCARCConversion(Sema &S,
3084 DiagnosticBuilder &DiagB,
3085 Sema::CheckedConversionKind CCK,
3086 SourceLocation afterLParen,
3087 QualType castType,
3088 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003089 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003090 const char *bridgeKeyword,
3091 const char *CFBridgeName) {
3092 // We handle C-style and implicit casts here.
3093 switch (CCK) {
3094 case Sema::CCK_ImplicitConversion:
3095 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003096 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003097 break;
3098 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003099 return;
3100 }
3101
3102 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003103 if (CCK == Sema::CCK_OtherCast) {
3104 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3105 SourceRange range(NCE->getOperatorLoc(),
3106 NCE->getAngleBrackets().getEnd());
3107 SmallString<32> BridgeCall;
3108
3109 SourceManager &SM = S.getSourceManager();
3110 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3111 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3112 BridgeCall += ' ';
3113
3114 BridgeCall += CFBridgeName;
3115 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
3116 }
3117 return;
3118 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003119 Expr *castedE = castExpr;
3120 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
3121 castedE = CCE->getSubExpr();
3122 castedE = castedE->IgnoreImpCasts();
3123 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00003124
3125 SmallString<32> BridgeCall;
3126
3127 SourceManager &SM = S.getSourceManager();
3128 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
3129 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
3130 BridgeCall += ' ';
3131
3132 BridgeCall += CFBridgeName;
3133
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003134 if (isa<ParenExpr>(castedE)) {
3135 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003136 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003137 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003138 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003139 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003140 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003141 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3142 S.PP.getLocForEndOfToken(range.getEnd()),
3143 ")"));
3144 }
3145 return;
3146 }
3147
3148 if (CCK == Sema::CCK_CStyleCast) {
3149 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003150 } else if (CCK == Sema::CCK_OtherCast) {
3151 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3152 std::string castCode = "(";
3153 castCode += bridgeKeyword;
3154 castCode += castType.getAsString();
3155 castCode += ")";
3156 SourceRange Range(NCE->getOperatorLoc(),
3157 NCE->getAngleBrackets().getEnd());
3158 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3159 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003160 } else {
3161 std::string castCode = "(";
3162 castCode += bridgeKeyword;
3163 castCode += castType.getAsString();
3164 castCode += ")";
3165 Expr *castedE = castExpr->IgnoreImpCasts();
3166 SourceRange range = castedE->getSourceRange();
3167 if (isa<ParenExpr>(castedE)) {
3168 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3169 castCode));
3170 } else {
3171 castCode += "(";
3172 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3173 castCode));
3174 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3175 S.PP.getLocForEndOfToken(range.getEnd()),
3176 ")"));
3177 }
3178 }
3179}
3180
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003181template <typename T>
3182static inline T *getObjCBridgeAttr(const TypedefType *TD) {
3183 TypedefNameDecl *TDNDecl = TD->getDecl();
3184 QualType QT = TDNDecl->getUnderlyingType();
3185 if (QT->isPointerType()) {
3186 QT = QT->getPointeeType();
3187 if (const RecordType *RT = QT->getAs<RecordType>())
Fariborz Jahanian9af6a782014-06-11 19:10:46 +00003188 if (RecordDecl *RD = RT->getDecl()->getMostRecentDecl())
Aaron Ballman2084f8f2013-12-19 13:20:36 +00003189 return RD->getAttr<T>();
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003190 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003191 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003192}
3193
3194static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T,
3195 TypedefNameDecl *&TDNDecl) {
3196 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3197 TDNDecl = TD->getDecl();
3198 if (ObjCBridgeRelatedAttr *ObjCBAttr =
3199 getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD))
3200 return ObjCBAttr;
3201 T = TDNDecl->getUnderlyingType();
3202 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003203 return nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003204}
3205
John McCall4124c492011-10-17 18:40:02 +00003206static void
3207diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3208 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003209 Expr *castExpr, Expr *realCast,
3210 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003211 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003212 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003213 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003214
John McCall4124c492011-10-17 18:40:02 +00003215 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003216 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003217 return;
John McCall4124c492011-10-17 18:40:02 +00003218
3219 QualType castExprType = castExpr->getType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003220 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003221 if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable &&
3222 ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) ||
3223 (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable &&
Fariborz Jahanian1ad83a32014-06-18 23:22:38 +00003224 ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl)))
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003225 return;
John McCall31168b02011-06-15 23:02:42 +00003226
John McCall640767f2011-06-17 06:50:50 +00003227 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003228 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003229 case ACTC_none:
3230 case ACTC_coreFoundation:
3231 case ACTC_voidPtr:
3232 srcKind = (castExprType->isPointerType() ? 1 : 0);
3233 break;
3234 case ACTC_retainable:
3235 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3236 break;
3237 case ACTC_indirectRetainable:
3238 srcKind = 4;
3239 break;
John McCall31168b02011-06-15 23:02:42 +00003240 }
3241
John McCall4124c492011-10-17 18:40:02 +00003242 // Check whether this could be fixed with a bridge cast.
3243 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3244 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003245
John McCall4124c492011-10-17 18:40:02 +00003246 // Bridge from an ARC type to a CF type.
3247 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003248
John McCall4124c492011-10-17 18:40:02 +00003249 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3250 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3251 << 2 // of C pointer type
3252 << castExprType
3253 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3254 << castType
3255 << castRange
3256 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003257 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003258 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003259 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003260 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003261 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003262 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003263 DiagnosticBuilder DiagB =
3264 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3265 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Craig Topperc3ec1492014-05-26 06:22:03 +00003266
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003267 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003268 castType, castExpr, realCast, "__bridge ",
3269 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003270 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003271 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003272 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003273 DiagnosticBuilder DiagB =
3274 (CCK == Sema::CCK_OtherCast && !br) ?
3275 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3276 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3277 diag::note_arc_bridge_transfer)
3278 << castExprType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003279
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003280 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003281 castType, castExpr, realCast, "__bridge_transfer ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003282 br ? "CFBridgingRelease" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003283 }
John McCall4124c492011-10-17 18:40:02 +00003284
3285 return;
3286 }
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003287
John McCall4124c492011-10-17 18:40:02 +00003288 // Bridge from a CF type to an ARC type.
3289 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003290 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003291 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3292 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3293 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3294 << castExprType
3295 << 2 // to C pointer type
3296 << castType
3297 << castRange
3298 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003299 ACCResult CreateRule =
3300 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003301 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003302 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003303 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003304 DiagnosticBuilder DiagB =
3305 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3306 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003307 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Craig Topperc3ec1492014-05-26 06:22:03 +00003308 castType, castExpr, realCast, "__bridge ",
3309 nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003310 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003311 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003312 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003313 DiagnosticBuilder DiagB =
3314 (CCK == Sema::CCK_OtherCast && !br) ?
3315 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3316 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3317 diag::note_arc_bridge_retained)
3318 << castType << br;
Craig Topperc3ec1492014-05-26 06:22:03 +00003319
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003320 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003321 castType, castExpr, realCast, "__bridge_retained ",
Craig Topperc3ec1492014-05-26 06:22:03 +00003322 br ? "CFBridgingRetain" : nullptr);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003323 }
John McCall4124c492011-10-17 18:40:02 +00003324
3325 return;
John McCall31168b02011-06-15 23:02:42 +00003326 }
3327
John McCall4124c492011-10-17 18:40:02 +00003328 S.Diag(loc, diag::err_arc_mismatched_cast)
3329 << (CCK != Sema::CCK_ImplicitConversion)
3330 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003331 << castRange << castExpr->getSourceRange();
3332}
3333
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003334template <typename TB>
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003335static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr,
3336 bool &HadTheAttribute, bool warn) {
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003337 QualType T = castExpr->getType();
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003338 HadTheAttribute = false;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003339 while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) {
3340 TypedefNameDecl *TDNDecl = TD->getDecl();
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003341 if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) {
Fariborz Jahaniandb3d8552013-11-19 00:09:48 +00003342 if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003343 HadTheAttribute = true;
Fariborz Jahanianc9e266b2014-12-11 22:56:26 +00003344 if (Parm->isStr("id"))
3345 return true;
3346
Craig Topperc3ec1492014-05-26 06:22:03 +00003347 NamedDecl *Target = nullptr;
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003348 // Check for an existing type with this name.
3349 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3350 Sema::LookupOrdinaryName);
3351 if (S.LookupName(R, S.TUScope)) {
Fariborz Jahanianf07183c2013-11-16 01:45:25 +00003352 Target = R.getFoundDecl();
3353 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3354 ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target);
3355 if (const ObjCObjectPointerType *InterfacePointerType =
3356 castType->getAsObjCInterfacePointerType()) {
3357 ObjCInterfaceDecl *CastClass
3358 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003359 if ((CastClass == ExprClass) ||
Fariborz Jahanian27aa9b42015-04-10 22:07:47 +00003360 (CastClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003361 return true;
3362 if (warn)
3363 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3364 << T << Target->getName() << castType->getPointeeType();
3365 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003366 } else if (castType->isObjCIdType() ||
3367 (S.Context.ObjCObjectAdoptsQTypeProtocols(
3368 castType, ExprClass)))
3369 // ok to cast to 'id'.
3370 // casting to id<p-list> is ok if bridge type adopts all of
3371 // p-list protocols.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003372 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003373 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003374 if (warn) {
3375 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge)
3376 << T << Target->getName() << castType;
3377 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3378 S.Diag(Target->getLocStart(), diag::note_declared_at);
3379 }
3380 return false;
Fariborz Jahanian2c312122013-11-16 23:22:37 +00003381 }
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003382 }
Fariborz Jahanian696c8872015-04-09 23:39:53 +00003383 } else if (!castType->isObjCIdType()) {
3384 S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface)
3385 << castExpr->getType() << Parm;
3386 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3387 if (Target)
3388 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahaniana649c822013-11-15 22:18:17 +00003389 }
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;
John McCallaf6b3f82015-03-10 18:41:23 +00003409 if (Parm->isStr("id"))
3410 return true;
3411
Craig Topperc3ec1492014-05-26 06:22:03 +00003412 NamedDecl *Target = nullptr;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003413 // Check for an existing type with this name.
3414 LookupResult R(S, DeclarationName(Parm), SourceLocation(),
3415 Sema::LookupOrdinaryName);
3416 if (S.LookupName(R, S.TUScope)) {
3417 Target = R.getFoundDecl();
3418 if (Target && isa<ObjCInterfaceDecl>(Target)) {
3419 ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target);
3420 if (const ObjCObjectPointerType *InterfacePointerType =
3421 castExpr->getType()->getAsObjCInterfacePointerType()) {
3422 ObjCInterfaceDecl *ExprClass
3423 = InterfacePointerType->getObjectType()->getInterface();
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003424 if ((CastClass == ExprClass) ||
3425 (ExprClass && CastClass->isSuperClassOf(ExprClass)))
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003426 return true;
3427 if (warn) {
3428 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3429 << castExpr->getType()->getPointeeType() << T;
3430 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3431 }
3432 return false;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003433 } else if (castExpr->getType()->isObjCIdType() ||
3434 (S.Context.QIdProtocolsAdoptObjCObjectProtocols(
3435 castExpr->getType(), CastClass)))
3436 // ok to cast an 'id' expression to a CFtype.
3437 // ok to cast an 'id<plist>' expression to CFtype provided plist
3438 // adopts all of CFtype's ObjetiveC's class plist.
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003439 return true;
Fariborz Jahanian92ab2982013-11-20 00:32:12 +00003440 else {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003441 if (warn) {
3442 S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf)
3443 << castExpr->getType() << castType;
3444 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3445 S.Diag(Target->getLocStart(), diag::note_declared_at);
3446 }
3447 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003448 }
3449 }
3450 }
3451 S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject)
3452 << castExpr->getType() << castType;
3453 S.Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3454 if (Target)
3455 S.Diag(Target->getLocStart(), diag::note_declared_at);
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003456 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003457 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003458 return false;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003459 }
3460 T = TDNDecl->getUnderlyingType();
3461 }
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003462 return true;
Fariborz Jahanian8a0210e2013-11-16 19:16:32 +00003463}
3464
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003465void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) {
Fariborz Jahanianf1a22f42014-04-29 16:12:56 +00003466 if (!getLangOpts().ObjC1)
3467 return;
Alp Tokerf6a24ce2013-12-05 16:25:25 +00003468 // warn in presence of __bridge casting to or from a toll free bridge cast.
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003469 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType());
3470 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003471 if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003472 bool HasObjCBridgeAttr;
3473 bool ObjCBridgeAttrWillNotWarn =
3474 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3475 false);
3476 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3477 return;
3478 bool HasObjCBridgeMutableAttr;
3479 bool ObjCBridgeMutableAttrWillNotWarn =
3480 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3481 HasObjCBridgeMutableAttr, false);
3482 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3483 return;
3484
3485 if (HasObjCBridgeAttr)
3486 CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3487 true);
3488 else if (HasObjCBridgeMutableAttr)
3489 CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3490 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003491 }
3492 else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) {
Fariborz Jahanian5cbbb1be2014-06-11 16:52:44 +00003493 bool HasObjCBridgeAttr;
3494 bool ObjCBridgeAttrWillNotWarn =
3495 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3496 false);
3497 if (ObjCBridgeAttrWillNotWarn && HasObjCBridgeAttr)
3498 return;
3499 bool HasObjCBridgeMutableAttr;
3500 bool ObjCBridgeMutableAttrWillNotWarn =
3501 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3502 HasObjCBridgeMutableAttr, false);
3503 if (ObjCBridgeMutableAttrWillNotWarn && HasObjCBridgeMutableAttr)
3504 return;
3505
3506 if (HasObjCBridgeAttr)
3507 CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr, HasObjCBridgeAttr,
3508 true);
3509 else if (HasObjCBridgeMutableAttr)
3510 CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr,
3511 HasObjCBridgeMutableAttr, true);
Fariborz Jahanian87c77912013-11-21 20:50:32 +00003512 }
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00003513}
3514
Fariborz Jahanian53f867a2014-06-26 21:22:16 +00003515void Sema::CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr) {
3516 QualType SrcType = castExpr->getType();
3517 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(castExpr)) {
3518 if (PRE->isExplicitProperty()) {
3519 if (ObjCPropertyDecl *PDecl = PRE->getExplicitProperty())
3520 SrcType = PDecl->getType();
3521 }
3522 else if (PRE->isImplicitProperty()) {
3523 if (ObjCMethodDecl *Getter = PRE->getImplicitPropertyGetter())
3524 SrcType = Getter->getReturnType();
3525
3526 }
3527 }
3528
3529 ARCConversionTypeClass srcExprACTC = classifyTypeForARCConversion(SrcType);
3530 ARCConversionTypeClass castExprACTC = classifyTypeForARCConversion(castType);
3531 if (srcExprACTC != ACTC_retainable || castExprACTC != ACTC_coreFoundation)
3532 return;
3533 CheckObjCBridgeRelatedConversions(castExpr->getLocStart(),
3534 castType, SrcType, castExpr);
3535 return;
3536}
3537
Fariborz Jahanianc70a5432014-05-10 17:40:11 +00003538bool Sema::CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr,
3539 CastKind &Kind) {
3540 if (!getLangOpts().ObjC1)
3541 return false;
3542 ARCConversionTypeClass exprACTC =
3543 classifyTypeForARCConversion(castExpr->getType());
3544 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
3545 if ((castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) ||
3546 (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable)) {
3547 CheckTollFreeBridgeCast(castType, castExpr);
3548 Kind = (castACTC == ACTC_coreFoundation) ? CK_BitCast
3549 : CK_CPointerToObjCPointerCast;
3550 return true;
3551 }
3552 return false;
3553}
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003554
3555bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc,
3556 QualType DestType, QualType SrcType,
3557 ObjCInterfaceDecl *&RelatedClass,
3558 ObjCMethodDecl *&ClassMethod,
3559 ObjCMethodDecl *&InstanceMethod,
3560 TypedefNameDecl *&TDNDecl,
3561 bool CfToNs) {
3562 QualType T = CfToNs ? SrcType : DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003563 ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl);
3564 if (!ObjCBAttr)
3565 return false;
3566
3567 IdentifierInfo *RCId = ObjCBAttr->getRelatedClass();
3568 IdentifierInfo *CMId = ObjCBAttr->getClassMethod();
3569 IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod();
3570 if (!RCId)
3571 return false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003572 NamedDecl *Target = nullptr;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003573 // Check for an existing type with this name.
3574 LookupResult R(*this, DeclarationName(RCId), SourceLocation(),
3575 Sema::LookupOrdinaryName);
3576 if (!LookupName(R, TUScope)) {
3577 Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003578 << SrcType << DestType;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003579 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3580 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003581 }
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003582 Target = R.getFoundDecl();
3583 if (Target && isa<ObjCInterfaceDecl>(Target))
3584 RelatedClass = cast<ObjCInterfaceDecl>(Target);
3585 else {
3586 Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId
3587 << SrcType << DestType;
3588 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3589 if (Target)
3590 Diag(Target->getLocStart(), diag::note_declared_at);
3591 return false;
3592 }
3593
3594 // Check for an existing class method with the given selector name.
3595 if (CfToNs && CMId) {
3596 Selector Sel = Context.Selectors.getUnarySelector(CMId);
3597 ClassMethod = RelatedClass->lookupMethod(Sel, false);
3598 if (!ClassMethod) {
3599 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003600 << SrcType << DestType << Sel << false;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003601 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3602 return false;
3603 }
3604 }
3605
3606 // Check for an existing instance method with the given selector name.
3607 if (!CfToNs && IMId) {
3608 Selector Sel = Context.Selectors.getNullarySelector(IMId);
3609 InstanceMethod = RelatedClass->lookupMethod(Sel, true);
3610 if (!InstanceMethod) {
3611 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003612 << SrcType << DestType << Sel << true;
Fariborz Jahanian67379e22013-12-09 22:04:26 +00003613 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3614 return false;
3615 }
3616 }
3617 return true;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003618}
3619
3620bool
3621Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc,
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003622 QualType DestType, QualType SrcType,
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003623 Expr *&SrcExpr) {
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003624 ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType);
3625 ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType);
3626 bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable);
3627 bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation);
3628 if (!CfToNs && !NsToCf)
3629 return false;
3630
3631 ObjCInterfaceDecl *RelatedClass;
Craig Topperc3ec1492014-05-26 06:22:03 +00003632 ObjCMethodDecl *ClassMethod = nullptr;
3633 ObjCMethodDecl *InstanceMethod = nullptr;
3634 TypedefNameDecl *TDNDecl = nullptr;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003635 if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass,
3636 ClassMethod, InstanceMethod, TDNDecl, CfToNs))
3637 return false;
3638
3639 if (CfToNs) {
3640 // Implicit conversion from CF to ObjC object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003641 if (ClassMethod) {
3642 std::string ExpressionString = "[";
3643 ExpressionString += RelatedClass->getNameAsString();
3644 ExpressionString += " ";
3645 ExpressionString += ClassMethod->getSelector().getAsString();
3646 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
3647 // Provide a fixit: [RelatedClass ClassMethod SrcExpr]
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003648 Diag(Loc, diag::err_objc_bridged_related_known_method)
Fariborz Jahanian7c04a552013-12-10 19:22:41 +00003649 << SrcType << DestType << ClassMethod->getSelector() << false
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003650 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString)
3651 << FixItHint::CreateInsertion(SrcExprEndLoc, "]");
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003652 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3653 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3654
3655 QualType receiverType =
3656 Context.getObjCInterfaceType(RelatedClass);
3657 // Argument.
3658 Expr *args[] = { SrcExpr };
3659 ExprResult msg = BuildClassMessageImplicit(receiverType, false,
3660 ClassMethod->getLocation(),
3661 ClassMethod->getSelector(), ClassMethod,
3662 MultiExprArg(args, 1));
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003663 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003664 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003665 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003666 }
3667 else {
3668 // Implicit conversion from ObjC type to CF object is needed.
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003669 if (InstanceMethod) {
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003670 std::string ExpressionString;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003671 SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd());
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003672 if (InstanceMethod->isPropertyAccessor())
3673 if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) {
3674 // fixit: ObjectExpr.propertyname when it is aproperty accessor.
3675 ExpressionString = ".";
3676 ExpressionString += PDecl->getNameAsString();
3677 Diag(Loc, diag::err_objc_bridged_related_known_method)
3678 << SrcType << DestType << InstanceMethod->getSelector() << true
3679 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3680 }
3681 if (ExpressionString.empty()) {
3682 // Provide a fixit: [ObjectExpr InstanceMethod]
3683 ExpressionString = " ";
3684 ExpressionString += InstanceMethod->getSelector().getAsString();
3685 ExpressionString += "]";
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003686
Fariborz Jahanian88b68982013-12-10 23:18:06 +00003687 Diag(Loc, diag::err_objc_bridged_related_known_method)
3688 << SrcType << DestType << InstanceMethod->getSelector() << true
3689 << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[")
3690 << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString);
3691 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003692 Diag(RelatedClass->getLocStart(), diag::note_declared_at);
3693 Diag(TDNDecl->getLocStart(), diag::note_declared_at);
3694
3695 ExprResult msg =
3696 BuildInstanceMessageImplicit(SrcExpr, SrcType,
3697 InstanceMethod->getLocation(),
3698 InstanceMethod->getSelector(),
3699 InstanceMethod, None);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003700 SrcExpr = msg.get();
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003701 return true;
Fariborz Jahaniandb765772013-12-10 17:08:13 +00003702 }
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003703 }
Fariborz Jahanian381edf52013-12-16 22:54:37 +00003704 return false;
Fariborz Jahanian1f0b3bf2013-12-07 00:34:23 +00003705}
3706
John McCall4124c492011-10-17 18:40:02 +00003707Sema::ARCConversionResult
3708Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003709 Expr *&castExpr, CheckedConversionKind CCK,
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003710 bool DiagnoseCFAudited,
3711 BinaryOperatorKind Opc) {
John McCall4124c492011-10-17 18:40:02 +00003712 QualType castExprType = castExpr->getType();
3713
3714 // For the purposes of the classification, we assume reference types
3715 // will bind to temporaries.
3716 QualType effCastType = castType;
3717 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3718 effCastType = ref->getPointeeType();
3719
3720 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3721 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003722 if (exprACTC == castACTC) {
3723 // check for viablity and report error if casting an rvalue to a
3724 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003725 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003726 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003727 (castType != castExprType)) {
3728 const Type *DT = castType.getTypePtr();
3729 QualType QDT = castType;
3730 // We desugar some types but not others. We ignore those
3731 // that cannot happen in a cast; i.e. auto, and those which
3732 // should not be de-sugared; i.e typedef.
3733 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3734 QDT = PT->desugar();
3735 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3736 QDT = TP->desugar();
3737 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3738 QDT = AT->desugar();
3739 if (QDT != castType &&
3740 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3741 SourceLocation loc =
3742 (castRange.isValid() ? castRange.getBegin()
3743 : castExpr->getExprLoc());
3744 Diag(loc, diag::err_arc_nolifetime_behavior);
3745 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003746 }
3747 return ACR_okay;
3748 }
3749
John McCall4124c492011-10-17 18:40:02 +00003750 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3751
3752 // Allow all of these types to be cast to integer types (but not
3753 // vice-versa).
3754 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3755 return ACR_okay;
3756
3757 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3758 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3759 // must be explicit.
3760 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3761 return ACR_okay;
3762 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3763 CCK != CCK_ImplicitConversion)
3764 return ACR_okay;
3765
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003766 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003767 // For invalid casts, fall through.
3768 case ACC_invalid:
3769 break;
3770
3771 // Do nothing for both bottom and +0.
3772 case ACC_bottom:
3773 case ACC_plusZero:
3774 return ACR_okay;
3775
3776 // If the result is +1, consume it here.
3777 case ACC_plusOne:
3778 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3779 CK_ARCConsumeObject, castExpr,
Craig Topperc3ec1492014-05-26 06:22:03 +00003780 nullptr, VK_RValue);
John McCall4124c492011-10-17 18:40:02 +00003781 ExprNeedsCleanups = true;
3782 return ACR_okay;
3783 }
3784
3785 // If this is a non-implicit cast from id or block type to a
3786 // CoreFoundation type, delay complaining in case the cast is used
3787 // in an acceptable context.
3788 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3789 CCK != CCK_ImplicitConversion)
3790 return ACR_unbridged;
3791
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003792 // Do not issue bridge cast" diagnostic when implicit casting a cstring
3793 // to 'NSString *'. Let caller issue a normal mismatched diagnostic with
3794 // suitable fix-it.
Fariborz Jahanian283bf892013-12-18 21:04:43 +00003795 if (castACTC == ACTC_retainable && exprACTC == ACTC_none &&
3796 ConversionToObjCStringLiteralCheck(castType, castExpr))
3797 return ACR_okay;
Fariborz Jahanianbd714e92013-12-17 19:33:43 +00003798
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003799 // Do not issue "bridge cast" diagnostic when implicit casting
3800 // a retainable object to a CF type parameter belonging to an audited
3801 // CF API function. Let caller issue a normal type mismatched diagnostic
3802 // instead.
3803 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3804 castACTC != ACTC_coreFoundation)
Fariborz Jahanianc03ef572014-06-18 23:52:49 +00003805 if (!(exprACTC == ACTC_voidPtr && castACTC == ACTC_retainable &&
3806 (Opc == BO_NE || Opc == BO_EQ)))
3807 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3808 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003809 return ACR_okay;
3810}
3811
3812/// Given that we saw an expression with the ARCUnbridgedCastTy
3813/// placeholder type, complain bitterly.
3814void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3815 // We expect the spurious ImplicitCastExpr to already have been stripped.
3816 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3817 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3818
3819 SourceRange castRange;
3820 QualType castType;
3821 CheckedConversionKind CCK;
3822
3823 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3824 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3825 castType = cast->getTypeAsWritten();
3826 CCK = CCK_CStyleCast;
3827 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3828 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3829 castType = cast->getTypeAsWritten();
3830 CCK = CCK_OtherCast;
3831 } else {
3832 castType = cast->getType();
3833 CCK = CCK_ImplicitConversion;
3834 }
3835
3836 ARCConversionTypeClass castACTC =
3837 classifyTypeForARCConversion(castType.getNonReferenceType());
3838
3839 Expr *castExpr = realCast->getSubExpr();
3840 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3841
3842 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003843 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003844}
3845
3846/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3847/// type, remove the placeholder cast.
3848Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3849 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3850
3851 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3852 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3853 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3854 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3855 assert(uo->getOpcode() == UO_Extension);
3856 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3857 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3858 sub->getValueKind(), sub->getObjectKind(),
3859 uo->getOperatorLoc());
3860 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3861 assert(!gse->isResultDependent());
3862
3863 unsigned n = gse->getNumAssocs();
3864 SmallVector<Expr*, 4> subExprs(n);
3865 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3866 for (unsigned i = 0; i != n; ++i) {
3867 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3868 Expr *sub = gse->getAssocExpr(i);
3869 if (i == gse->getResultIndex())
3870 sub = stripARCUnbridgedCast(sub);
3871 subExprs[i] = sub;
3872 }
3873
3874 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3875 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003876 subTypes, subExprs,
3877 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003878 gse->getRParenLoc(),
3879 gse->containsUnexpandedParameterPack(),
3880 gse->getResultIndex());
3881 } else {
3882 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3883 return cast<ImplicitCastExpr>(e)->getSubExpr();
3884 }
3885}
3886
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003887bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3888 QualType exprType) {
3889 QualType canCastType =
3890 Context.getCanonicalType(castType).getUnqualifiedType();
3891 QualType canExprType =
3892 Context.getCanonicalType(exprType).getUnqualifiedType();
3893 if (isa<ObjCObjectPointerType>(canCastType) &&
3894 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3895 canExprType->isObjCObjectPointerType()) {
3896 if (const ObjCObjectPointerType *ObjT =
3897 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00003898 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3899 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003900 }
3901 return true;
3902}
3903
John McCall4db5c3c2011-07-07 06:58:02 +00003904/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3905static Expr *maybeUndoReclaimObject(Expr *e) {
3906 // For now, we just undo operands that are *immediately* reclaim
3907 // expressions, which prevents the vast majority of potential
3908 // problems here. To catch them all, we'd need to rebuild arbitrary
3909 // value-propagating subexpressions --- we can't reliably rebuild
3910 // in-place because of expression sharing.
3911 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00003912 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00003913 return ice->getSubExpr();
3914
3915 return e;
3916}
3917
John McCall31168b02011-06-15 23:02:42 +00003918ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3919 ObjCBridgeCastKind Kind,
3920 SourceLocation BridgeKeywordLoc,
3921 TypeSourceInfo *TSInfo,
3922 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00003923 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3924 if (SubResult.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003925 SubExpr = SubResult.get();
John McCalleb075542011-08-26 00:48:42 +00003926
John McCall31168b02011-06-15 23:02:42 +00003927 QualType T = TSInfo->getType();
3928 QualType FromType = SubExpr->getType();
3929
John McCall9320b872011-09-09 05:25:32 +00003930 CastKind CK;
3931
John McCall31168b02011-06-15 23:02:42 +00003932 bool MustConsume = false;
3933 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3934 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00003935 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00003936 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3937 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00003938 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3939 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00003940 switch (Kind) {
3941 case OBC_Bridge:
3942 break;
3943
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003944 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003945 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00003946 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3947 << 2
3948 << FromType
3949 << (T->isBlockPointerType()? 1 : 0)
3950 << T
3951 << SubExpr->getSourceRange()
3952 << Kind;
3953 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3954 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3955 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003956 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00003957 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003958 br ? "CFBridgingRelease "
3959 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00003960
3961 Kind = OBC_Bridge;
3962 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003963 }
John McCall31168b02011-06-15 23:02:42 +00003964
3965 case OBC_BridgeTransfer:
3966 // We must consume the Objective-C object produced by the cast.
3967 MustConsume = true;
3968 break;
3969 }
3970 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3971 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00003972 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00003973 switch (Kind) {
Fariborz Jahanian214567c2014-10-28 17:26:21 +00003974 case OBC_Bridge:
3975 // Reclaiming a value that's going to be __bridge-casted to CF
3976 // is very dangerous, so we don't do it.
3977 SubExpr = maybeUndoReclaimObject(SubExpr);
3978 break;
John McCall31168b02011-06-15 23:02:42 +00003979
3980 case OBC_BridgeRetained:
3981 // Produce the object before casting it.
3982 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00003983 CK_ARCProduceObject,
Craig Topperc3ec1492014-05-26 06:22:03 +00003984 SubExpr, nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00003985 break;
3986
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003987 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003988 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00003989 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3990 << (FromType->isBlockPointerType()? 1 : 0)
3991 << FromType
3992 << 2
3993 << T
3994 << SubExpr->getSourceRange()
3995 << Kind;
3996
3997 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3998 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3999 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004000 << T << br
4001 << FixItHint::CreateReplacement(BridgeKeywordLoc,
4002 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00004003
4004 Kind = OBC_Bridge;
4005 break;
4006 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00004007 }
John McCall31168b02011-06-15 23:02:42 +00004008 } else {
4009 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
4010 << FromType << T << Kind
4011 << SubExpr->getSourceRange()
4012 << TSInfo->getTypeLoc().getSourceRange();
4013 return ExprError();
4014 }
4015
John McCall9320b872011-09-09 05:25:32 +00004016 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00004017 BridgeKeywordLoc,
4018 TSInfo, SubExpr);
4019
4020 if (MustConsume) {
4021 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00004022 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
Craig Topperc3ec1492014-05-26 06:22:03 +00004023 nullptr, VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00004024 }
4025
4026 return Result;
4027}
4028
4029ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
4030 SourceLocation LParenLoc,
4031 ObjCBridgeCastKind Kind,
4032 SourceLocation BridgeKeywordLoc,
4033 ParsedType Type,
4034 SourceLocation RParenLoc,
4035 Expr *SubExpr) {
Craig Topperc3ec1492014-05-26 06:22:03 +00004036 TypeSourceInfo *TSInfo = nullptr;
John McCall31168b02011-06-15 23:02:42 +00004037 QualType T = GetTypeFromParser(Type, &TSInfo);
Fariborz Jahanian8c5b4be2013-11-21 00:39:36 +00004038 if (Kind == OBC_Bridge)
4039 CheckTollFreeBridgeCast(T, SubExpr);
John McCall31168b02011-06-15 23:02:42 +00004040 if (!TSInfo)
4041 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
4042 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
4043 SubExpr);
4044}