blob: 39c2ec41863c5e4468af38d51497d359907588fe [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.
Jay Foad9a6b0982011-06-21 15:13:30 +000070 S = StringLiteral::Create(Context, StrBuf,
Douglas Gregorfb65e592011-07-27 05:40:30 +000071 StringLiteral::Ascii, /*Pascal=*/false,
Chris Lattnerf83b5af2009-02-18 06:40:38 +000072 Context.getPointerType(Context.CharTy),
Chris Lattner163ffd22009-02-18 06:48:40 +000073 &StrLocs[0], StrLocs.size());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000074 }
Ted Kremeneke65b0862012-03-06 20:05:56 +000075
76 return BuildObjCStringLiteral(AtLocs[0], S);
77}
Mike Stump11289f42009-09-09 15:08:12 +000078
Ted Kremeneke65b0862012-03-06 20:05:56 +000079ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner6436fb62009-02-18 06:01:06 +000080 // Verify that this composite string is acceptable for ObjC strings.
81 if (CheckObjCString(S))
Chris Lattnera3fc41d2008-01-04 22:32:30 +000082 return true;
Chris Lattnerfffd6a72009-02-18 06:06:56 +000083
84 // Initialize the constant string interface lazily. This assumes
Steve Naroff54e59452009-04-07 14:18:33 +000085 // the NSString interface is seen in this translation unit. Note: We
86 // don't use NSConstantString, since the runtime team considers this
87 // interface private (even though it appears in the header files).
Chris Lattnerfffd6a72009-02-18 06:06:56 +000088 QualType Ty = Context.getObjCConstantStringInterface();
89 if (!Ty.isNull()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +000090 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikiebbafb8a2012-03-11 07:00:24 +000091 } else if (getLangOpts().NoConstantCFStrings) {
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000092 IdentifierInfo *NSIdent=0;
David Blaikiebbafb8a2012-03-11 07:00:24 +000093 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000094
95 if (StringClass.empty())
96 NSIdent = &Context.Idents.get("NSConstantString");
97 else
98 NSIdent = &Context.Idents.get(StringClass);
99
Ted Kremeneke65b0862012-03-06 20:05:56 +0000100 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian07317632010-04-23 23:19:04 +0000101 LookupOrdinaryName);
102 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
103 Context.setObjCConstantStringInterface(StrIF);
104 Ty = Context.getObjCConstantStringInterface();
105 Ty = Context.getObjCObjectPointerType(Ty);
106 } else {
107 // If there is no NSConstantString interface defined then treat this
108 // as error and recover from it.
109 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
110 << S->getSourceRange();
111 Ty = Context.getObjCIdType();
112 }
Chris Lattner091f6982008-06-21 21:44:18 +0000113 } else {
Patrick Beard0caa3942012-04-19 00:25:12 +0000114 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000115 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000116 LookupOrdinaryName);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000117 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
118 Context.setObjCConstantStringInterface(StrIF);
119 Ty = Context.getObjCConstantStringInterface();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000120 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000121 } else {
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000122 // If there is no NSString interface defined, implicitly declare
123 // a @class NSString; and use that instead. This is to make sure
124 // type of an NSString literal is represented correctly, instead of
125 // being an 'id' type.
126 Ty = Context.getObjCNSStringType();
127 if (Ty.isNull()) {
128 ObjCInterfaceDecl *NSStringIDecl =
129 ObjCInterfaceDecl::Create (Context,
130 Context.getTranslationUnitDecl(),
131 SourceLocation(), NSIdent,
132 0, SourceLocation());
133 Ty = Context.getObjCInterfaceType(NSStringIDecl);
134 Context.setObjCNSStringType(Ty);
135 }
136 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000137 }
Chris Lattner091f6982008-06-21 21:44:18 +0000138 }
Mike Stump11289f42009-09-09 15:08:12 +0000139
Ted Kremeneke65b0862012-03-06 20:05:56 +0000140 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
141}
142
Jordy Rose08e500c2012-05-12 17:32:44 +0000143/// \brief Emits an error if the given method does not exist, or if the return
144/// type is not an Objective-C object.
145static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
146 const ObjCInterfaceDecl *Class,
147 Selector Sel, const ObjCMethodDecl *Method) {
148 if (!Method) {
149 // FIXME: Is there a better way to avoid quotes than using getName()?
150 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
151 return false;
152 }
153
154 // Make sure the return type is reasonable.
155 QualType ReturnType = Method->getResultType();
156 if (!ReturnType->isObjCObjectPointerType()) {
157 S.Diag(Loc, diag::err_objc_literal_method_sig)
158 << Sel;
159 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
160 << ReturnType;
161 return false;
162 }
163
164 return true;
165}
166
Ted Kremeneke65b0862012-03-06 20:05:56 +0000167/// \brief Retrieve the NSNumber factory method that should be used to create
168/// an Objective-C literal for the given type.
169static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000170 QualType NumberType,
171 bool isLiteral = false,
172 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000173 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
174 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
175
Ted Kremeneke65b0862012-03-06 20:05:56 +0000176 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000177 if (isLiteral) {
178 S.Diag(Loc, diag::err_invalid_nsnumber_type)
179 << NumberType << R;
180 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000181 return 0;
182 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000183
Ted Kremeneke65b0862012-03-06 20:05:56 +0000184 // If we already looked up this method, we're done.
185 if (S.NSNumberLiteralMethods[*Kind])
186 return S.NSNumberLiteralMethods[*Kind];
187
188 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
189 /*Instance=*/false);
190
Patrick Beard0caa3942012-04-19 00:25:12 +0000191 ASTContext &CX = S.Context;
192
193 // Look up the NSNumber class, if we haven't done so already. It's cached
194 // in the Sema instance.
195 if (!S.NSNumberDecl) {
Jordy Roseaca01f92012-05-12 17:32:52 +0000196 IdentifierInfo *NSNumberId =
197 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
Patrick Beard0caa3942012-04-19 00:25:12 +0000198 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
199 Loc, Sema::LookupOrdinaryName);
200 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
201 if (!S.NSNumberDecl) {
202 if (S.getLangOpts().DebuggerObjCLiteral) {
203 // Create a stub definition of NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000204 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
205 CX.getTranslationUnitDecl(),
206 SourceLocation(), NSNumberId,
207 0, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000208 } else {
209 // Otherwise, require a declaration of NSNumber.
210 S.Diag(Loc, diag::err_undeclared_nsnumber);
211 return 0;
212 }
213 } else if (!S.NSNumberDecl->hasDefinition()) {
214 S.Diag(Loc, diag::err_undeclared_nsnumber);
215 return 0;
216 }
217
218 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000219 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
220 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000221 }
222
Ted Kremeneke65b0862012-03-06 20:05:56 +0000223 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000224 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000225 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000226 // create a stub definition this NSNumber factory method.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000227 TypeSourceInfo *ResultTInfo = 0;
Patrick Beard0caa3942012-04-19 00:25:12 +0000228 Method = ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +0000229 S.NSNumberPointer, ResultTInfo,
230 S.NSNumberDecl,
Patrick Beard0caa3942012-04-19 00:25:12 +0000231 /*isInstance=*/false, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000232 /*isPropertyAccessor=*/false,
Patrick Beard0caa3942012-04-19 00:25:12 +0000233 /*isImplicitlyDeclared=*/true,
Jordy Roseaca01f92012-05-12 17:32:52 +0000234 /*isDefined=*/false,
235 ObjCMethodDecl::Required,
Patrick Beard0caa3942012-04-19 00:25:12 +0000236 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000237 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
238 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000239 &CX.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000240 NumberType, /*TInfo=*/0, SC_None,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000241 0);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000242 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000243 }
244
Jordy Rose08e500c2012-05-12 17:32:44 +0000245 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000246 return 0;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000247
248 // Note: if the parameter type is out-of-line, we'll catch it later in the
249 // implicit conversion.
250
251 S.NSNumberLiteralMethods[*Kind] = Method;
252 return Method;
253}
254
Patrick Beard0caa3942012-04-19 00:25:12 +0000255/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
256/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000257ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000258 // Determine the type of the literal.
259 QualType NumberType = Number->getType();
260 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
261 // In C, character literals have type 'int'. That's not the type we want
262 // to use to determine the Objective-c literal kind.
263 switch (Char->getKind()) {
264 case CharacterLiteral::Ascii:
265 NumberType = Context.CharTy;
266 break;
267
268 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000269 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000270 break;
271
272 case CharacterLiteral::UTF16:
273 NumberType = Context.Char16Ty;
274 break;
275
276 case CharacterLiteral::UTF32:
277 NumberType = Context.Char32Ty;
278 break;
279 }
280 }
281
Ted Kremeneke65b0862012-03-06 20:05:56 +0000282 // Look for the appropriate method within NSNumber.
283 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000284 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000285 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000286 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000287 if (!Method)
288 return ExprError();
289
290 // Convert the number to the type that the parameter expects.
Patrick Beard2565c592012-05-01 21:47:19 +0000291 ParmVarDecl *ParamDecl = Method->param_begin()[0];
292 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
293 ParamDecl);
294 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
295 SourceLocation(),
296 Owned(Number));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000297 if (ConvertedNumber.isInvalid())
298 return ExprError();
299 Number = ConvertedNumber.get();
300
Patrick Beard2565c592012-05-01 21:47:19 +0000301 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000302 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000303 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
304 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000305}
306
307ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
308 SourceLocation ValueLoc,
309 bool Value) {
310 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000311 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000312 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
313 } else {
314 // C doesn't actually have a way to represent literal values of type
315 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
316 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
317 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
318 CK_IntegralToBoolean);
319 }
320
321 return BuildObjCNumericLiteral(AtLoc, Inner.get());
322}
323
324/// \brief Check that the given expression is a valid element of an Objective-C
325/// collection literal.
326static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000327 QualType T,
328 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000329 // If the expression is type-dependent, there's nothing for us to do.
330 if (Element->isTypeDependent())
331 return Element;
332
333 ExprResult Result = S.CheckPlaceholderExpr(Element);
334 if (Result.isInvalid())
335 return ExprError();
336 Element = Result.get();
337
338 // In C++, check for an implicit conversion to an Objective-C object pointer
339 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000340 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000341 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000342 = InitializedEntity::InitializeParameter(S.Context, T,
343 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000344 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000345 = InitializationKind::CreateCopy(Element->getLocStart(),
346 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000347 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000348 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000349 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000350 }
351
352 Expr *OrigElement = Element;
353
354 // Perform lvalue-to-rvalue conversion.
355 Result = S.DefaultLvalueConversion(Element);
356 if (Result.isInvalid())
357 return ExprError();
358 Element = Result.get();
359
360 // Make sure that we have an Objective-C pointer type or block.
361 if (!Element->getType()->isObjCObjectPointerType() &&
362 !Element->getType()->isBlockPointerType()) {
363 bool Recovered = false;
364
365 // If this is potentially an Objective-C numeric literal, add the '@'.
366 if (isa<IntegerLiteral>(OrigElement) ||
367 isa<CharacterLiteral>(OrigElement) ||
368 isa<FloatingLiteral>(OrigElement) ||
369 isa<ObjCBoolLiteralExpr>(OrigElement) ||
370 isa<CXXBoolLiteralExpr>(OrigElement)) {
371 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
372 int Which = isa<CharacterLiteral>(OrigElement) ? 1
373 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
374 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
375 : 3;
376
377 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
378 << Which << OrigElement->getSourceRange()
379 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
380
381 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
382 OrigElement);
383 if (Result.isInvalid())
384 return ExprError();
385
386 Element = Result.get();
387 Recovered = true;
388 }
389 }
390 // If this is potentially an Objective-C string literal, add the '@'.
391 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
392 if (String->isAscii()) {
393 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
394 << 0 << OrigElement->getSourceRange()
395 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
396
397 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
398 if (Result.isInvalid())
399 return ExprError();
400
401 Element = Result.get();
402 Recovered = true;
403 }
404 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000405
Ted Kremeneke65b0862012-03-06 20:05:56 +0000406 if (!Recovered) {
407 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
408 << Element->getType();
409 return ExprError();
410 }
411 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000412 if (ArrayLiteral)
413 if (ObjCStringLiteral *getString = dyn_cast<ObjCStringLiteral>(OrigElement)) {
414 if (getString->getString() && getString->getString()->getNumConcatenated() > 1)
415 S.Diag(Element->getLocStart(), diag::warn_concatenated_nsarray_literal)
416 << Element->getType();
417 }
418
Ted Kremeneke65b0862012-03-06 20:05:56 +0000419 // Make sure that the element has the type that the container factory
420 // function expects.
421 return S.PerformCopyInitialization(
422 InitializedEntity::InitializeParameter(S.Context, T,
423 /*Consumed=*/false),
424 Element->getLocStart(), Element);
425}
426
Patrick Beard0caa3942012-04-19 00:25:12 +0000427ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
428 if (ValueExpr->isTypeDependent()) {
429 ObjCBoxedExpr *BoxedExpr =
430 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR);
431 return Owned(BoxedExpr);
432 }
433 ObjCMethodDecl *BoxingMethod = NULL;
434 QualType BoxedType;
435 // Convert the expression to an RValue, so we can check for pointer types...
436 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
437 if (RValue.isInvalid()) {
438 return ExprError();
439 }
440 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000441 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000442 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
443 QualType PointeeType = PT->getPointeeType();
444 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
445
446 if (!NSStringDecl) {
447 IdentifierInfo *NSStringId =
448 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
449 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
450 SR.getBegin(), LookupOrdinaryName);
451 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
452 if (!NSStringDecl) {
453 if (getLangOpts().DebuggerObjCLiteral) {
454 // Support boxed expressions in the debugger w/o NSString declaration.
Jordy Roseaca01f92012-05-12 17:32:52 +0000455 DeclContext *TU = Context.getTranslationUnitDecl();
456 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
457 SourceLocation(),
458 NSStringId,
Patrick Beard0caa3942012-04-19 00:25:12 +0000459 0, SourceLocation());
460 } else {
461 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
462 return ExprError();
463 }
464 } else if (!NSStringDecl->hasDefinition()) {
465 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
466 return ExprError();
467 }
468 assert(NSStringDecl && "NSStringDecl should not be NULL");
Jordy Roseaca01f92012-05-12 17:32:52 +0000469 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
470 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000471 }
472
473 if (!StringWithUTF8StringMethod) {
474 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
475 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
476
477 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000478 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
479 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000480 // Debugger needs to work even if NSString hasn't been defined.
481 TypeSourceInfo *ResultTInfo = 0;
482 ObjCMethodDecl *M =
483 ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(),
484 stringWithUTF8String, NSStringPointer,
485 ResultTInfo, NSStringDecl,
486 /*isInstance=*/false, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000487 /*isPropertyAccessor=*/false,
Patrick Beard0caa3942012-04-19 00:25:12 +0000488 /*isImplicitlyDeclared=*/true,
489 /*isDefined=*/false,
490 ObjCMethodDecl::Required,
491 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000492 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000493 ParmVarDecl *value =
494 ParmVarDecl::Create(Context, M,
495 SourceLocation(), SourceLocation(),
496 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000497 Context.getPointerType(ConstCharType),
Patrick Beard0caa3942012-04-19 00:25:12 +0000498 /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000499 SC_None, 0);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000500 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000501 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000502 }
Jordy Rose890f4572012-05-12 15:53:41 +0000503
Jordy Rose08e500c2012-05-12 17:32:44 +0000504 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
505 stringWithUTF8String, BoxingMethod))
506 return ExprError();
507
508 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000509 }
510
511 BoxingMethod = StringWithUTF8StringMethod;
512 BoxedType = NSStringPointer;
513 }
Patrick Beard2565c592012-05-01 21:47:19 +0000514 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000515 // The other types we support are numeric, char and BOOL/bool. We could also
516 // provide limited support for structure types, such as NSRange, NSRect, and
517 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
518 // for more details.
519
520 // Check for a top-level character literal.
521 if (const CharacterLiteral *Char =
522 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
523 // In C, character literals have type 'int'. That's not the type we want
524 // to use to determine the Objective-c literal kind.
525 switch (Char->getKind()) {
526 case CharacterLiteral::Ascii:
527 ValueType = Context.CharTy;
528 break;
529
530 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000531 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000532 break;
533
534 case CharacterLiteral::UTF16:
535 ValueType = Context.Char16Ty;
536 break;
537
538 case CharacterLiteral::UTF32:
539 ValueType = Context.Char32Ty;
540 break;
541 }
542 }
543
544 // FIXME: Do I need to do anything special with BoolTy expressions?
545
546 // Look for the appropriate method within NSNumber.
547 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
548 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000549
550 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
551 if (!ET->getDecl()->isComplete()) {
552 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
553 << ValueType << ValueExpr->getSourceRange();
554 return ExprError();
555 }
556
557 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
558 ET->getDecl()->getIntegerType());
559 BoxedType = NSNumberPointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000560 }
561
562 if (!BoxingMethod) {
563 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
564 << ValueType << ValueExpr->getSourceRange();
565 return ExprError();
566 }
567
568 // Convert the expression to the type that the parameter requires.
Patrick Beard2565c592012-05-01 21:47:19 +0000569 ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0];
570 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
571 ParamDecl);
572 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
573 SourceLocation(),
574 Owned(ValueExpr));
Patrick Beard0caa3942012-04-19 00:25:12 +0000575 if (ConvertedValueExpr.isInvalid())
576 return ExprError();
577 ValueExpr = ConvertedValueExpr.get();
578
579 ObjCBoxedExpr *BoxedExpr =
580 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
581 BoxingMethod, SR);
582 return MaybeBindToTemporary(BoxedExpr);
583}
584
John McCallf2538342012-07-31 05:14:30 +0000585/// Build an ObjC subscript pseudo-object expression, given that
586/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000587ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
588 Expr *IndexExpr,
589 ObjCMethodDecl *getterMethod,
590 ObjCMethodDecl *setterMethod) {
John McCallf2538342012-07-31 05:14:30 +0000591 assert(!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000592
John McCallf2538342012-07-31 05:14:30 +0000593 // We can't get dependent types here; our callers should have
594 // filtered them out.
595 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
596 "base or index cannot have dependent type here");
597
598 // Filter out placeholders in the index. In theory, overloads could
599 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000600 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
601 if (Result.isInvalid())
602 return ExprError();
603 IndexExpr = Result.get();
604
John McCallf2538342012-07-31 05:14:30 +0000605 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000606 Result = DefaultLvalueConversion(BaseExpr);
607 if (Result.isInvalid())
608 return ExprError();
609 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000610
611 // Build the pseudo-object expression.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000612 return Owned(ObjCSubscriptRefExpr::Create(Context,
613 BaseExpr,
614 IndexExpr,
615 Context.PseudoObjectTy,
616 getterMethod,
617 setterMethod, RB));
618
619}
620
621ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
622 // Look up the NSArray class, if we haven't done so already.
623 if (!NSArrayDecl) {
624 NamedDecl *IF = LookupSingleName(TUScope,
625 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
626 SR.getBegin(),
627 LookupOrdinaryName);
628 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000629 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000630 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
631 Context.getTranslationUnitDecl(),
632 SourceLocation(),
633 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
634 0, SourceLocation());
635
636 if (!NSArrayDecl) {
637 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
638 return ExprError();
639 }
640 }
641
642 // Find the arrayWithObjects:count: method, if we haven't done so already.
643 QualType IdT = Context.getObjCIdType();
644 if (!ArrayWithObjectsMethod) {
645 Selector
646 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
Jordy Rose08e500c2012-05-12 17:32:44 +0000647 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
648 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000649 TypeSourceInfo *ResultTInfo = 0;
Jordy Rose08e500c2012-05-12 17:32:44 +0000650 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000651 SourceLocation(), SourceLocation(), Sel,
652 IdT,
653 ResultTInfo,
654 Context.getTranslationUnitDecl(),
655 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000656 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000657 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
658 ObjCMethodDecl::Required,
659 false);
660 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000661 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000662 SourceLocation(),
663 SourceLocation(),
664 &Context.Idents.get("objects"),
665 Context.getPointerType(IdT),
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000666 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000667 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000668 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000669 SourceLocation(),
670 SourceLocation(),
671 &Context.Idents.get("cnt"),
672 Context.UnsignedLongTy,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000673 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000674 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000675 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000676 }
677
Jordy Rose08e500c2012-05-12 17:32:44 +0000678 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000679 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000680
Jordy Rose4af44872012-05-12 17:32:56 +0000681 // Dig out the type that all elements should be converted to.
682 QualType T = Method->param_begin()[0]->getType();
683 const PointerType *PtrT = T->getAs<PointerType>();
684 if (!PtrT ||
685 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
686 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
687 << Sel;
688 Diag(Method->param_begin()[0]->getLocation(),
689 diag::note_objc_literal_method_param)
690 << 0 << T
691 << Context.getPointerType(IdT.withConst());
692 return ExprError();
693 }
694
695 // Check that the 'count' parameter is integral.
696 if (!Method->param_begin()[1]->getType()->isIntegerType()) {
697 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
698 << Sel;
699 Diag(Method->param_begin()[1]->getLocation(),
700 diag::note_objc_literal_method_param)
701 << 1
702 << Method->param_begin()[1]->getType()
703 << "integral";
704 return ExprError();
705 }
706
707 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000708 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000709 }
710
Jordy Rose4af44872012-05-12 17:32:56 +0000711 QualType ObjectsType = ArrayWithObjectsMethod->param_begin()[0]->getType();
712 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000713
714 // Check that each of the elements provided is valid in a collection literal,
715 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000716 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000717 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
718 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
719 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000720 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000721 if (Converted.isInvalid())
722 return ExprError();
723
724 ElementsBuffer[I] = Converted.get();
725 }
726
727 QualType Ty
728 = Context.getObjCObjectPointerType(
729 Context.getObjCInterfaceType(NSArrayDecl));
730
731 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000732 ObjCArrayLiteral::Create(Context, Elements, Ty,
733 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000734}
735
736ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
737 ObjCDictionaryElement *Elements,
738 unsigned NumElements) {
739 // Look up the NSDictionary class, if we haven't done so already.
740 if (!NSDictionaryDecl) {
741 NamedDecl *IF = LookupSingleName(TUScope,
742 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
743 SR.getBegin(), LookupOrdinaryName);
744 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000745 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000746 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
747 Context.getTranslationUnitDecl(),
748 SourceLocation(),
749 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
750 0, SourceLocation());
751
752 if (!NSDictionaryDecl) {
753 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
754 return ExprError();
755 }
756 }
757
758 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
759 // so already.
760 QualType IdT = Context.getObjCIdType();
761 if (!DictionaryWithObjectsMethod) {
762 Selector Sel = NSAPIObj->getNSDictionarySelector(
Jordy Roseaca01f92012-05-12 17:32:52 +0000763 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
Jordy Rose08e500c2012-05-12 17:32:44 +0000764 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
765 if (!Method && getLangOpts().DebuggerObjCLiteral) {
766 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000767 SourceLocation(), SourceLocation(), Sel,
768 IdT,
769 0 /*TypeSourceInfo */,
770 Context.getTranslationUnitDecl(),
771 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000772 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000773 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
774 ObjCMethodDecl::Required,
775 false);
776 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000777 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000778 SourceLocation(),
779 SourceLocation(),
780 &Context.Idents.get("objects"),
781 Context.getPointerType(IdT),
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000782 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000783 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000784 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000785 SourceLocation(),
786 SourceLocation(),
787 &Context.Idents.get("keys"),
788 Context.getPointerType(IdT),
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000789 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000790 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000791 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000792 SourceLocation(),
793 SourceLocation(),
794 &Context.Idents.get("cnt"),
795 Context.UnsignedLongTy,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000796 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000797 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000798 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000799 }
800
Jordy Rose08e500c2012-05-12 17:32:44 +0000801 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
802 Method))
803 return ExprError();
804
Jordy Rose4af44872012-05-12 17:32:56 +0000805 // Dig out the type that all values should be converted to.
806 QualType ValueT = Method->param_begin()[0]->getType();
807 const PointerType *PtrValue = ValueT->getAs<PointerType>();
808 if (!PtrValue ||
809 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000810 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000811 << Sel;
812 Diag(Method->param_begin()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000813 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000814 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000815 << Context.getPointerType(IdT.withConst());
816 return ExprError();
817 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000818
Jordy Rose4af44872012-05-12 17:32:56 +0000819 // Dig out the type that all keys should be converted to.
820 QualType KeyT = Method->param_begin()[1]->getType();
821 const PointerType *PtrKey = KeyT->getAs<PointerType>();
822 if (!PtrKey ||
823 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
824 IdT)) {
825 bool err = true;
826 if (PtrKey) {
827 if (QIDNSCopying.isNull()) {
828 // key argument of selector is id<NSCopying>?
829 if (ObjCProtocolDecl *NSCopyingPDecl =
830 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
831 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
832 QIDNSCopying =
833 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
834 (ObjCProtocolDecl**) PQ,1);
835 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
836 }
837 }
838 if (!QIDNSCopying.isNull())
839 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
840 QIDNSCopying);
841 }
842
843 if (err) {
844 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
845 << Sel;
846 Diag(Method->param_begin()[1]->getLocation(),
847 diag::note_objc_literal_method_param)
848 << 1 << KeyT
849 << Context.getPointerType(IdT.withConst());
850 return ExprError();
851 }
852 }
853
854 // Check that the 'count' parameter is integral.
855 QualType CountType = Method->param_begin()[2]->getType();
856 if (!CountType->isIntegerType()) {
857 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
858 << Sel;
859 Diag(Method->param_begin()[2]->getLocation(),
860 diag::note_objc_literal_method_param)
861 << 2 << CountType
862 << "integral";
863 return ExprError();
864 }
865
866 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
867 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000868 }
869
Jordy Rose4af44872012-05-12 17:32:56 +0000870 QualType ValuesT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
871 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
872 QualType KeysT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
873 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
874
Ted Kremeneke65b0862012-03-06 20:05:56 +0000875 // Check that each of the keys and values provided is valid in a collection
876 // literal, performing conversions as necessary.
877 bool HasPackExpansions = false;
878 for (unsigned I = 0, N = NumElements; I != N; ++I) {
879 // Check the key.
880 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
881 KeyT);
882 if (Key.isInvalid())
883 return ExprError();
884
885 // Check the value.
886 ExprResult Value
887 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
888 if (Value.isInvalid())
889 return ExprError();
890
891 Elements[I].Key = Key.get();
892 Elements[I].Value = Value.get();
893
894 if (Elements[I].EllipsisLoc.isInvalid())
895 continue;
896
897 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
898 !Elements[I].Value->containsUnexpandedParameterPack()) {
899 Diag(Elements[I].EllipsisLoc,
900 diag::err_pack_expansion_without_parameter_packs)
901 << SourceRange(Elements[I].Key->getLocStart(),
902 Elements[I].Value->getLocEnd());
903 return ExprError();
904 }
905
906 HasPackExpansions = true;
907 }
908
909
910 QualType Ty
911 = Context.getObjCObjectPointerType(
912 Context.getObjCInterfaceType(NSDictionaryDecl));
913 return MaybeBindToTemporary(
914 ObjCDictionaryLiteral::Create(Context,
915 llvm::makeArrayRef(Elements,
916 NumElements),
917 HasPackExpansions,
918 Ty,
919 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000920}
921
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000922ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +0000923 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +0000924 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +0000925 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +0000926 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +0000927 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +0000928 StrTy = Context.DependentTy;
929 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +0000930 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
931 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000932 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000933 diag::err_incomplete_type_objc_at_encode,
934 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000935 return ExprError();
936
Anders Carlsson315d2292009-06-07 18:45:35 +0000937 std::string Str;
938 Context.getObjCEncodingForType(EncodedType, Str);
939
940 // The type of @encode is the same as the type of the corresponding string,
941 // which is an array type.
942 StrTy = Context.CharTy;
943 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000944 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +0000945 StrTy.addConst();
946 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
947 ArrayType::Normal, 0);
948 }
Mike Stump11289f42009-09-09 15:08:12 +0000949
Douglas Gregorabd9e962010-04-20 15:39:42 +0000950 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +0000951}
952
John McCallfaf5fb42010-08-26 23:41:50 +0000953ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
954 SourceLocation EncodeLoc,
955 SourceLocation LParenLoc,
956 ParsedType ty,
957 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000958 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +0000959 TypeSourceInfo *TInfo;
960 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
961 if (!TInfo)
962 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
963 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000964
Douglas Gregorabd9e962010-04-20 15:39:42 +0000965 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000966}
967
John McCallfaf5fb42010-08-26 23:41:50 +0000968ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
969 SourceLocation AtLoc,
970 SourceLocation SelLoc,
971 SourceLocation LParenLoc,
Fariborz Jahanian02447d82013-01-22 18:35:43 +0000972 SourceLocation RParenLoc) {
973 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
974 SourceRange(LParenLoc, RParenLoc), false, false);
975 if (!Method)
976 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +0000977 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +0000978 if (!Method) {
979 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
980 Selector MatchedSel = OM->getSelector();
981 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
982 RParenLoc.getLocWithOffset(-1));
983 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
984 << Sel << MatchedSel
985 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
986
987 } else
988 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
989 }
Fariborz Jahanian9a881012011-07-13 19:05:43 +0000990
Fariborz Jahanian02447d82013-01-22 18:35:43 +0000991 if (!Method ||
992 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
993 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
994 = ReferencedSelectors.find(Sel);
995 if (Pos == ReferencedSelectors.end())
996 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian9a881012011-07-13 19:05:43 +0000997 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +0000998
Fariborz Jahanian02447d82013-01-22 18:35:43 +0000999 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001000 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001001 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001002 switch (Sel.getMethodFamily()) {
1003 case OMF_retain:
1004 case OMF_release:
1005 case OMF_autorelease:
1006 case OMF_retainCount:
1007 case OMF_dealloc:
1008 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1009 Sel << SourceRange(LParenLoc, RParenLoc);
1010 break;
1011
1012 case OMF_None:
1013 case OMF_alloc:
1014 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001015 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001016 case OMF_init:
1017 case OMF_mutableCopy:
1018 case OMF_new:
1019 case OMF_self:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001020 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001021 break;
1022 }
1023 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001024 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001025 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001026}
1027
John McCallfaf5fb42010-08-26 23:41:50 +00001028ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1029 SourceLocation AtLoc,
1030 SourceLocation ProtoLoc,
1031 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001032 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001033 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001034 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001035 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001036 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001037 return true;
1038 }
Mike Stump11289f42009-09-09 15:08:12 +00001039
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001040 QualType Ty = Context.getObjCProtoType();
1041 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001042 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001043 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001044 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001045}
1046
John McCall5f2d5562011-02-03 09:00:02 +00001047/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001048ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1049 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001050
1051 // If we're not in an ObjC method, error out. Note that, unlike the
1052 // C++ case, we don't require an instance method --- class methods
1053 // still have a 'self', and we really do still need to capture it!
1054 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1055 if (!method)
1056 return 0;
1057
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001058 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001059
1060 return method;
1061}
1062
Douglas Gregor64910ca2011-09-09 20:05:21 +00001063static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1064 if (T == Context.getObjCInstanceType())
1065 return Context.getObjCIdType();
1066
1067 return T;
1068}
1069
Douglas Gregor33823722011-06-11 01:09:30 +00001070QualType Sema::getMessageSendResultType(QualType ReceiverType,
1071 ObjCMethodDecl *Method,
1072 bool isClassMessage, bool isSuperMessage) {
1073 assert(Method && "Must have a method");
1074 if (!Method->hasRelatedResultType())
1075 return Method->getSendResultType();
1076
1077 // If a method has a related return type:
1078 // - if the method found is an instance method, but the message send
1079 // was a class message send, T is the declared return type of the method
1080 // found
1081 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001082 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001083
1084 // - if the receiver is super, T is a pointer to the class of the
1085 // enclosing method definition
1086 if (isSuperMessage) {
1087 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1088 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1089 return Context.getObjCObjectPointerType(
1090 Context.getObjCInterfaceType(Class));
1091 }
1092
1093 // - if the receiver is the name of a class U, T is a pointer to U
1094 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1095 ReceiverType->isObjCQualifiedInterfaceType())
1096 return Context.getObjCObjectPointerType(ReceiverType);
1097 // - if the receiver is of type Class or qualified Class type,
1098 // T is the declared return type of the method.
1099 if (ReceiverType->isObjCClassType() ||
1100 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001101 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001102
1103 // - if the receiver is id, qualified id, Class, or qualified Class, T
1104 // is the receiver type, otherwise
1105 // - T is the type of the receiver expression.
1106 return ReceiverType;
1107}
John McCall5f2d5562011-02-03 09:00:02 +00001108
John McCall5ec7e7d2013-03-19 07:04:25 +00001109/// Look for an ObjC method whose result type exactly matches the given type.
1110static const ObjCMethodDecl *
1111findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1112 QualType instancetype) {
1113 if (MD->getResultType() == instancetype) return MD;
1114
1115 // For these purposes, a method in an @implementation overrides a
1116 // declaration in the @interface.
1117 if (const ObjCImplDecl *impl =
1118 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1119 const ObjCContainerDecl *iface;
1120 if (const ObjCCategoryImplDecl *catImpl =
1121 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1122 iface = catImpl->getCategoryDecl();
1123 } else {
1124 iface = impl->getClassInterface();
1125 }
1126
1127 const ObjCMethodDecl *ifaceMD =
1128 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1129 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1130 }
1131
1132 SmallVector<const ObjCMethodDecl *, 4> overrides;
1133 MD->getOverriddenMethods(overrides);
1134 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1135 if (const ObjCMethodDecl *result =
1136 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1137 return result;
1138 }
1139
1140 return 0;
1141}
1142
1143void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1144 // Only complain if we're in an ObjC method and the required return
1145 // type doesn't match the method's declared return type.
1146 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1147 if (!MD || !MD->hasRelatedResultType() ||
1148 Context.hasSameUnqualifiedType(destType, MD->getResultType()))
1149 return;
1150
1151 // Look for a method overridden by this method which explicitly uses
1152 // 'instancetype'.
1153 if (const ObjCMethodDecl *overridden =
1154 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1155 SourceLocation loc;
1156 SourceRange range;
1157 if (TypeSourceInfo *TSI = overridden->getResultTypeSourceInfo()) {
1158 range = TSI->getTypeLoc().getSourceRange();
1159 loc = range.getBegin();
1160 }
1161 if (loc.isInvalid())
1162 loc = overridden->getLocation();
1163 Diag(loc, diag::note_related_result_type_explicit)
1164 << /*current method*/ 1 << range;
1165 return;
1166 }
1167
1168 // Otherwise, if we have an interesting method family, note that.
1169 // This should always trigger if the above didn't.
1170 if (ObjCMethodFamily family = MD->getMethodFamily())
1171 Diag(MD->getLocation(), diag::note_related_result_type_family)
1172 << /*current method*/ 1
1173 << family;
1174}
1175
Douglas Gregor33823722011-06-11 01:09:30 +00001176void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1177 E = E->IgnoreParenImpCasts();
1178 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1179 if (!MsgSend)
1180 return;
1181
1182 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1183 if (!Method)
1184 return;
1185
1186 if (!Method->hasRelatedResultType())
1187 return;
1188
1189 if (Context.hasSameUnqualifiedType(Method->getResultType()
1190 .getNonReferenceType(),
1191 MsgSend->getType()))
1192 return;
1193
Douglas Gregorbab8a962011-09-08 01:46:34 +00001194 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
1195 Context.getObjCInstanceType()))
1196 return;
1197
Douglas Gregor33823722011-06-11 01:09:30 +00001198 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1199 << Method->isInstanceMethod() << Method->getSelector()
1200 << MsgSend->getType();
1201}
1202
1203bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001204 MultiExprArg Args,
1205 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001206 ArrayRef<SourceLocation> SelectorLocs,
1207 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001208 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001209 SourceLocation lbrac, SourceLocation rbrac,
John McCall7decc9e2010-11-18 06:31:45 +00001210 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001211 SourceLocation SelLoc;
1212 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1213 SelLoc = SelectorLocs.front();
1214 else
1215 SelLoc = lbrac;
1216
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001217 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001218 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001219 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001220 if (Args[i]->isTypeDependent())
1221 continue;
1222
John McCallcc5788c2013-03-04 07:34:02 +00001223 ExprResult result;
1224 if (getLangOpts().DebuggerSupport) {
1225 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001226 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001227 } else {
1228 result = DefaultArgumentPromotion(Args[i]);
1229 }
1230 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001231 return true;
John McCallcc5788c2013-03-04 07:34:02 +00001232 Args[i] = result.take();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001233 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001234
John McCall31168b02011-06-15 23:02:42 +00001235 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001236 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001237 DiagID = diag::err_arc_method_not_found;
1238 else
1239 DiagID = isClassMessage ? diag::warn_class_method_not_found
1240 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001241 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001242 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001243 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001244 if (getLangOpts().ObjCAutoRefCount)
1245 DiagID = diag::error_method_not_found_with_typo;
1246 else
1247 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1248 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001249 Selector MatchedSel = OMD->getSelector();
1250 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001251 Diag(SelLoc, DiagID)
1252 << Sel<< isClassMessage << MatchedSel
Fariborz Jahanian75481672013-06-17 17:10:54 +00001253 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1254 }
1255 else
1256 Diag(SelLoc, DiagID)
1257 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001258 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001259 // Find the class to which we are sending this message.
1260 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian478536b2013-05-15 15:27:35 +00001261 if (ObjCInterfaceDecl *Class =
1262 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl())
1263 Diag(Class->getLocation(), diag::note_receiver_class_declared);
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001264 }
1265 }
John McCall3f4138c2011-07-13 17:56:40 +00001266
1267 // In debuggers, we want to use __unknown_anytype for these
1268 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001269 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001270 ReturnType = Context.UnknownAnyTy;
1271 } else {
1272 ReturnType = Context.getObjCIdType();
1273 }
John McCall7decc9e2010-11-18 06:31:45 +00001274 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001275 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001276 }
Mike Stump11289f42009-09-09 15:08:12 +00001277
Douglas Gregor33823722011-06-11 01:09:30 +00001278 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1279 isSuperMessage);
John McCall7decc9e2010-11-18 06:31:45 +00001280 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump11289f42009-09-09 15:08:12 +00001281
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001282 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001283 // Method might have more arguments than selector indicates. This is due
1284 // to addition of c-style arguments in method.
1285 if (Method->param_size() > Sel.getNumArgs())
1286 NumNamedArgs = Method->param_size();
1287 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001288 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001289 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001290 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001291 return false;
1292 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001293
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001294 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001295 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001296 // We can't do any type-checking on a type-dependent argument.
1297 if (Args[i]->isTypeDependent())
1298 continue;
1299
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001300 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001301
John McCall4124c492011-10-17 18:40:02 +00001302 ParmVarDecl *param = Method->param_begin()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001303 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001304
John McCall4124c492011-10-17 18:40:02 +00001305 // Strip the unbridged-cast placeholder expression off unless it's
1306 // a consumed argument.
1307 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1308 !param->hasAttr<CFConsumedAttr>())
1309 argExpr = stripARCUnbridgedCast(argExpr);
1310
John McCallea0a39e2012-11-14 00:49:39 +00001311 // If the parameter is __unknown_anytype, infer its type
1312 // from the argument.
1313 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001314 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001315 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001316 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001317 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001318 } else {
1319 Args[i] = argE.take();
John McCallea0a39e2012-11-14 00:49:39 +00001320
John McCallcc5788c2013-03-04 07:34:02 +00001321 // Update the parameter type in-place.
1322 param->setType(paramType);
1323 }
1324 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001325 }
1326
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001327 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001328 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001329 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001330 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001331
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001332 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001333 param);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001334 ExprResult ArgE = PerformCopyInitialization(Entity, SelLoc, Owned(argExpr));
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001335 if (ArgE.isInvalid())
1336 IsError = true;
1337 else
1338 Args[i] = ArgE.takeAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001339 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001340
1341 // Promote additional arguments to variadic methods.
1342 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001343 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001344 if (Args[i]->isTypeDependent())
1345 continue;
1346
Jordy Roseaca01f92012-05-12 17:32:52 +00001347 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1348 0);
John Wiegley01296292011-04-08 18:41:53 +00001349 IsError |= Arg.isInvalid();
1350 Args[i] = Arg.take();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001351 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001352 } else {
1353 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001354 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001355 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001356 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001357 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001358 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001359 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001360 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001361 }
1362 }
1363
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001364 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001365
1366 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001367 IsError |= CheckObjCMethodCall(
1368 Method, SelLoc,
1369 llvm::makeArrayRef<const Expr *>(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001370
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001371 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001372}
1373
Douglas Gregor486b74e2011-09-27 16:10:05 +00001374bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001375 // 'self' is objc 'self' in an objc method only.
John McCallfe96e0b2011-11-06 09:01:30 +00001376 ObjCMethodDecl *method =
John McCalldec348f72013-05-03 07:33:41 +00001377 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
John McCallfe96e0b2011-11-06 09:01:30 +00001378 if (!method) return false;
1379
John McCall31168b02011-06-15 23:02:42 +00001380 receiver = receiver->IgnoreParenLValueCasts();
1381 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001382 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001383 return true;
1384 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001385}
1386
John McCall526ab472011-10-25 17:37:35 +00001387/// LookupMethodInType - Look up a method in an ObjCObjectType.
1388ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1389 bool isInstance) {
1390 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1391 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1392 // Look it up in the main interface (and categories, etc.)
1393 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1394 return method;
1395
1396 // Okay, look for "private" methods declared in any
1397 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001398 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1399 return method;
John McCall526ab472011-10-25 17:37:35 +00001400 }
1401
1402 // Check qualifiers.
1403 for (ObjCObjectType::qual_iterator
1404 i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
1405 if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
1406 return method;
1407
1408 return 0;
1409}
1410
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001411/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1412/// list of a qualified objective pointer type.
1413ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1414 const ObjCObjectPointerType *OPT,
1415 bool Instance)
1416{
1417 ObjCMethodDecl *MD = 0;
1418 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1419 E = OPT->qual_end(); I != E; ++I) {
1420 ObjCProtocolDecl *PROTO = (*I);
1421 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1422 return MD;
1423 }
1424 }
1425 return 0;
1426}
1427
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001428static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1429 if (!Receiver)
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001430 return;
1431
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001432 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1433 Receiver = OVE->getSourceExpr();
1434
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001435 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1436 SourceLocation Loc = RExpr->getLocStart();
1437 QualType T = RExpr->getType();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001438 const ObjCPropertyDecl *PDecl = 0;
1439 const ObjCMethodDecl *GDecl = 0;
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001440 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1441 RExpr = POE->getSyntacticForm();
1442 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1443 if (PRE->isImplicitProperty()) {
1444 GDecl = PRE->getImplicitPropertyGetter();
1445 if (GDecl) {
1446 T = GDecl->getResultType();
1447 }
1448 }
1449 else {
1450 PDecl = PRE->getExplicitProperty();
1451 if (PDecl) {
1452 T = PDecl->getType();
1453 }
1454 }
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001455 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001456 }
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001457 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1458 // See if receiver is a method which envokes a synthesized getter
1459 // backing a 'weak' property.
1460 ObjCMethodDecl *Method = ME->getMethodDecl();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001461 if (Method && Method->getSelector().getNumArgs() == 0) {
1462 PDecl = Method->findPropertyDecl();
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001463 if (PDecl)
1464 T = PDecl->getType();
1465 }
1466 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001467
Jordan Rose13d6b712012-09-28 22:21:42 +00001468 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1469 if (!PDecl)
1470 return;
1471 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1472 return;
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001473 }
Jordan Rose13d6b712012-09-28 22:21:42 +00001474
1475 S.Diag(Loc, diag::warn_receiver_is_weak)
1476 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1477
1478 if (PDecl)
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001479 S.Diag(PDecl->getLocation(), diag::note_property_declare);
Jordan Rose13d6b712012-09-28 22:21:42 +00001480 else if (GDecl)
1481 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1482
1483 S.Diag(Loc, diag::note_arc_assign_to_strong);
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001484}
1485
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001486/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1487/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001488ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001489HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001490 Expr *BaseExpr, SourceLocation OpLoc,
1491 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001492 SourceLocation MemberLoc,
1493 SourceLocation SuperLoc, QualType SuperType,
1494 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001495 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1496 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001497
Benjamin Kramer365082d2012-05-19 16:34:46 +00001498 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001499 Diag(MemberLoc, diag::err_invalid_property_name)
1500 << MemberName << QualType(OPT, 0);
1501 return ExprError();
1502 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001503
1504 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001505
Douglas Gregor4123a862011-11-14 22:10:01 +00001506 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1507 : BaseExpr->getSourceRange();
1508 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001509 diag::err_property_not_found_forward_class,
1510 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001511 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001512
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001513 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001514 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001515 // Check whether we can reference this property.
1516 if (DiagnoseUseOfDecl(PD, MemberLoc))
1517 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001518 if (Super)
John McCall526ab472011-10-25 17:37:35 +00001519 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001520 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001521 MemberLoc,
1522 SuperLoc, SuperType));
1523 else
John McCall526ab472011-10-25 17:37:35 +00001524 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001525 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001526 MemberLoc, BaseExpr));
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001527 }
1528 // Check protocols on qualified interfaces.
1529 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1530 E = OPT->qual_end(); I != E; ++I)
1531 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1532 // Check whether we can reference this property.
1533 if (DiagnoseUseOfDecl(PD, MemberLoc))
1534 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001535
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001536 if (Super)
John McCall526ab472011-10-25 17:37:35 +00001537 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1538 Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001539 VK_LValue,
1540 OK_ObjCProperty,
1541 MemberLoc,
1542 SuperLoc, SuperType));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001543 else
John McCall526ab472011-10-25 17:37:35 +00001544 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1545 Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001546 VK_LValue,
1547 OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001548 MemberLoc,
1549 BaseExpr));
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001550 }
1551 // If that failed, look for an "implicit" property by seeing if the nullary
1552 // selector is implemented.
1553
1554 // FIXME: The logic for looking up nullary and unary selectors should be
1555 // shared with the code in ActOnInstanceMessage.
1556
1557 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1558 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001559
1560 // May be founf in property's qualified list.
1561 if (!Getter)
1562 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001563
1564 // If this reference is in an @implementation, check for 'private' methods.
1565 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001566 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001567
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001568 if (Getter) {
1569 // Check if we can reference this property.
1570 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1571 return ExprError();
1572 }
1573 // If we found a getter then this may be a valid dot-reference, we
1574 // will look for the matching setter, in case it is needed.
1575 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001576 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1577 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001578 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001579
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001580 // May be founf in property's qualified list.
1581 if (!Setter)
1582 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1583
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001584 if (!Setter) {
1585 // If this reference is in an @implementation, also check for 'private'
1586 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001587 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001588 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001589
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001590 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1591 return ExprError();
1592
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001593 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001594 if (Super)
John McCallb7bd14f2010-12-02 01:19:52 +00001595 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001596 Context.PseudoObjectTy,
1597 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001598 MemberLoc,
1599 SuperLoc, SuperType));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001600 else
John McCallb7bd14f2010-12-02 01:19:52 +00001601 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001602 Context.PseudoObjectTy,
1603 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001604 MemberLoc, BaseExpr));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001605
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001606 }
1607
1608 // Attempt to correct for typos in property names.
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001609 DeclFilterCCC<ObjCPropertyDecl> Validator;
1610 if (TypoCorrection Corrected = CorrectTypo(
Richard Smithf9b15102013-08-17 00:46:16 +00001611 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
1612 NULL, Validator, IFace, false, OPT)) {
1613 diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest)
1614 << MemberName << QualType(OPT, 0));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001615 DeclarationName TypoResult = Corrected.getCorrection();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001616 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1617 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001618 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001619 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001620 ObjCInterfaceDecl *ClassDeclared;
1621 if (ObjCIvarDecl *Ivar =
1622 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1623 QualType T = Ivar->getType();
1624 if (const ObjCObjectPointerType * OBJPT =
1625 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001626 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001627 diag::err_property_not_as_forward_class,
1628 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001629 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001630 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001631 Diag(MemberLoc,
1632 diag::err_ivar_access_using_property_syntax_suggest)
1633 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1634 << FixItHint::CreateReplacement(OpLoc, "->");
1635 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001636 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001637
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001638 Diag(MemberLoc, diag::err_property_not_found)
1639 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001640 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001641 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001642 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001643 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001644}
1645
1646
1647
John McCalldadc5752010-08-24 06:29:42 +00001648ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001649ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1650 IdentifierInfo &propertyName,
1651 SourceLocation receiverNameLoc,
1652 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001653
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001654 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001655 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1656 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001657
1658 bool IsSuper = false;
Chris Lattnera36ec422010-04-11 08:28:14 +00001659 if (IFace == 0) {
1660 // If the "receiver" is 'super' in a method, handle it as an expression-like
1661 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001662 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001663 IsSuper = true;
1664
Eli Friedman24af8502012-02-03 22:47:37 +00001665 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001666 if (CurMethod->isInstanceMethod()) {
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001667 ObjCInterfaceDecl *Super =
1668 CurMethod->getClassInterface()->getSuperClass();
1669 if (!Super) {
1670 // The current class does not have a superclass.
1671 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1672 << CurMethod->getClassInterface()->getIdentifier();
1673 return ExprError();
1674 }
1675 QualType T = Context.getObjCInterfaceType(Super);
Chris Lattnera36ec422010-04-11 08:28:14 +00001676 T = Context.getObjCObjectPointerType(T);
Chris Lattnera36ec422010-04-11 08:28:14 +00001677
1678 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001679 /*BaseExpr*/0,
1680 SourceLocation()/*OpLoc*/,
1681 &propertyName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001682 propertyNameLoc,
1683 receiverNameLoc, T, true);
Chris Lattnera36ec422010-04-11 08:28:14 +00001684 }
Mike Stump11289f42009-09-09 15:08:12 +00001685
Chris Lattnera36ec422010-04-11 08:28:14 +00001686 // Otherwise, if this is a class method, try dispatching to our
1687 // superclass.
1688 IFace = CurMethod->getClassInterface()->getSuperClass();
1689 }
John McCall5f2d5562011-02-03 09:00:02 +00001690 }
Chris Lattnera36ec422010-04-11 08:28:14 +00001691
1692 if (IFace == 0) {
1693 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1694 return ExprError();
1695 }
1696 }
1697
1698 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001699 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001700 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001701
1702 // If this reference is in an @implementation, check for 'private' methods.
1703 if (!Getter)
1704 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1705 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001706 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001707 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001708
1709 if (Getter) {
1710 // FIXME: refactor/share with ActOnMemberReference().
1711 // Check if we can reference this property.
1712 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1713 return ExprError();
1714 }
Mike Stump11289f42009-09-09 15:08:12 +00001715
Steve Naroff9527bbf2009-03-09 21:12:44 +00001716 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001717 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001718 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1719 PP.getSelectorTable(),
1720 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001721
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001722 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001723 if (!Setter) {
1724 // If this reference is in an @implementation, also check for 'private'
1725 // methods.
1726 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1727 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001728 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001729 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001730 }
1731 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001732 if (!Setter)
1733 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001734
1735 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1736 return ExprError();
1737
1738 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001739 if (IsSuper)
1740 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001741 Context.PseudoObjectTy,
1742 VK_LValue, OK_ObjCProperty,
Douglas Gregor33823722011-06-11 01:09:30 +00001743 propertyNameLoc,
1744 receiverNameLoc,
1745 Context.getObjCInterfaceType(IFace)));
1746
John McCallb7bd14f2010-12-02 01:19:52 +00001747 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001748 Context.PseudoObjectTy,
1749 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001750 propertyNameLoc,
1751 receiverNameLoc, IFace));
Steve Naroff9527bbf2009-03-09 21:12:44 +00001752 }
1753 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1754 << &propertyName << Context.getObjCInterfaceType(IFace));
1755}
1756
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001757namespace {
1758
1759class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1760 public:
1761 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1762 // Determine whether "super" is acceptable in the current context.
1763 if (Method && Method->getClassInterface())
1764 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1765 }
1766
1767 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1768 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1769 candidate.isKeyword("super");
1770 }
1771};
1772
1773}
1774
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001775Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001776 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001777 SourceLocation NameLoc,
1778 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001779 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001780 ParsedType &ReceiverType) {
1781 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001782
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001783 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001784 // messaging super. If the identifier is "super" and there is a
1785 // trailing dot, it's an instance message.
1786 if (IsSuper && S->isInObjcMethodScope())
1787 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001788
1789 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1790 LookupName(Result, S);
1791
1792 switch (Result.getResultKind()) {
1793 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001794 // Normal name lookup didn't find anything. If we're in an
1795 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001796 // FIXME: This is a hack. Ivar lookup should be part of normal
1797 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001798 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001799 if (!Method->getClassInterface()) {
1800 // Fall back: let the parser try to parse it as an instance message.
1801 return ObjCInstanceMessage;
1802 }
1803
Douglas Gregorca7136b2010-04-19 20:09:36 +00001804 ObjCInterfaceDecl *ClassDeclared;
1805 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1806 ClassDeclared))
1807 return ObjCInstanceMessage;
1808 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001809
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001810 // Break out; we'll perform typo correction below.
1811 break;
1812
1813 case LookupResult::NotFoundInCurrentInstantiation:
1814 case LookupResult::FoundOverloaded:
1815 case LookupResult::FoundUnresolvedValue:
1816 case LookupResult::Ambiguous:
1817 Result.suppressDiagnostics();
1818 return ObjCInstanceMessage;
1819
1820 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001821 // If the identifier is a class or not, and there is a trailing dot,
1822 // it's an instance message.
1823 if (HasTrailingDot)
1824 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001825 // We found something. If it's a type, then we have a class
1826 // message. Otherwise, it's an instance message.
1827 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001828 QualType T;
1829 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1830 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001831 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001832 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001833 DiagnoseUseOfDecl(Type, NameLoc);
1834 }
1835 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001836 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001837
Douglas Gregore5798dc2010-04-21 20:38:13 +00001838 // We have a class message, and T is the type we're
1839 // messaging. Build source-location information for it.
1840 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001841 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001842 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001843 }
1844 }
1845
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001846 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001847 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1848 Result.getLookupKind(), S, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001849 Validator)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001850 if (Corrected.isKeyword()) {
1851 // If we've found the keyword "super" (the only keyword that would be
1852 // returned by CorrectTypo), this is a send to super.
Richard Smithf9b15102013-08-17 00:46:16 +00001853 diagnoseTypo(Corrected,
1854 PDiag(diag::err_unknown_receiver_suggest) << Name);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001855 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001856 } else if (ObjCInterfaceDecl *Class =
Richard Smithf9b15102013-08-17 00:46:16 +00001857 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001858 // If we found a declaration, correct when it refers to an Objective-C
1859 // class.
Richard Smithf9b15102013-08-17 00:46:16 +00001860 diagnoseTypo(Corrected,
1861 PDiag(diag::err_unknown_receiver_suggest) << Name);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001862 QualType T = Context.getObjCInterfaceType(Class);
1863 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1864 ReceiverType = CreateParsedType(T, TSInfo);
1865 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001866 }
1867 }
Richard Smithf9b15102013-08-17 00:46:16 +00001868
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001869 // Fall back: let the parser try to parse it as an instance message.
1870 return ObjCInstanceMessage;
1871}
Steve Naroff9527bbf2009-03-09 21:12:44 +00001872
John McCalldadc5752010-08-24 06:29:42 +00001873ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001874 SourceLocation SuperLoc,
1875 Selector Sel,
1876 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00001877 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001878 SourceLocation RBracLoc,
1879 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001880 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00001881 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00001882 if (!Method) {
1883 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1884 return ExprError();
1885 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001886
Douglas Gregor4fdba132010-04-21 20:01:04 +00001887 ObjCInterfaceDecl *Class = Method->getClassInterface();
1888 if (!Class) {
1889 Diag(SuperLoc, diag::error_no_super_class_message)
1890 << Method->getDeclName();
1891 return ExprError();
1892 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001893
Douglas Gregor4fdba132010-04-21 20:01:04 +00001894 ObjCInterfaceDecl *Super = Class->getSuperClass();
1895 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001896 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00001897 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1898 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001899 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00001900 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001901
Douglas Gregor4fdba132010-04-21 20:01:04 +00001902 // We are in a method whose class has a superclass, so 'super'
1903 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00001904 if (Method->getSelector() == Sel)
1905 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00001906
Jordan Rose2afd6612012-10-19 16:05:26 +00001907 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00001908 // Since we are in an instance method, this is an instance
1909 // message to the superclass instance.
1910 QualType SuperTy = Context.getObjCInterfaceType(Super);
1911 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCallb268a282010-08-23 23:25:46 +00001912 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001913 Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001914 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001915 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00001916
1917 // Since we are in a class method, this is a class message to
1918 // the superclass.
1919 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1920 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001921 SuperLoc, Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001922 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001923}
1924
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001925
1926ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1927 bool isSuperReceiver,
1928 SourceLocation Loc,
1929 Selector Sel,
1930 ObjCMethodDecl *Method,
1931 MultiExprArg Args) {
1932 TypeSourceInfo *receiverTypeInfo = 0;
1933 if (!ReceiverType.isNull())
1934 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1935
1936 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1937 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1938 Sel, Method, Loc, Loc, Loc, Args,
1939 /*isImplicit=*/true);
1940
1941}
1942
Ted Kremeneke65b0862012-03-06 20:05:56 +00001943static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1944 unsigned DiagID,
1945 bool (*refactor)(const ObjCMessageExpr *,
1946 const NSAPI &, edit::Commit &)) {
1947 SourceLocation MsgLoc = Msg->getExprLoc();
1948 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
1949 return;
1950
1951 SourceManager &SM = S.SourceMgr;
1952 edit::Commit ECommit(SM, S.LangOpts);
1953 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1954 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1955 << Msg->getSelector() << Msg->getSourceRange();
1956 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1957 if (!ECommit.isCommitable())
1958 return;
1959 for (edit::Commit::edit_iterator
1960 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1961 const edit::Commit::Edit &Edit = *I;
1962 switch (Edit.Kind) {
1963 case edit::Commit::Act_Insert:
1964 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1965 Edit.Text,
1966 Edit.BeforePrev));
1967 break;
1968 case edit::Commit::Act_InsertFromRange:
1969 Builder.AddFixItHint(
1970 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1971 Edit.getInsertFromRange(SM),
1972 Edit.BeforePrev));
1973 break;
1974 case edit::Commit::Act_Remove:
1975 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1976 break;
1977 }
1978 }
1979 }
1980}
1981
1982static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1983 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1984 edit::rewriteObjCRedundantCallWithLiteral);
1985}
1986
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001987/// \brief Build an Objective-C class message expression.
1988///
1989/// This routine takes care of both normal class messages and
1990/// class messages to the superclass.
1991///
1992/// \param ReceiverTypeInfo Type source information that describes the
1993/// receiver of this message. This may be NULL, in which case we are
1994/// sending to the superclass and \p SuperLoc must be a valid source
1995/// location.
1996
1997/// \param ReceiverType The type of the object receiving the
1998/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1999/// type as that refers to. For a superclass send, this is the type of
2000/// the superclass.
2001///
2002/// \param SuperLoc The location of the "super" keyword in a
2003/// superclass message.
2004///
2005/// \param Sel The selector to which the message is being sent.
2006///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002007/// \param Method The method that this class message is invoking, if
2008/// already known.
2009///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002010/// \param LBracLoc The location of the opening square bracket ']'.
2011///
James Dennettffad8b72012-06-22 08:10:18 +00002012/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002013///
James Dennettffad8b72012-06-22 08:10:18 +00002014/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002015ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002016 QualType ReceiverType,
2017 SourceLocation SuperLoc,
2018 Selector Sel,
2019 ObjCMethodDecl *Method,
2020 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002021 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002022 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002023 MultiExprArg ArgsIn,
2024 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002025 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002026 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002027 if (LBracLoc.isInvalid()) {
2028 Diag(Loc, diag::err_missing_open_square_message_send)
2029 << FixItHint::CreateInsertion(Loc, "[");
2030 LBracLoc = Loc;
2031 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002032 SourceLocation SelLoc;
2033 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2034 SelLoc = SelectorLocs.front();
2035 else
2036 SelLoc = Loc;
2037
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002038 if (ReceiverType->isDependentType()) {
2039 // If the receiver type is dependent, we can't type-check anything
2040 // at this point. Build a dependent expression.
2041 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002042 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002043 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCall7decc9e2010-11-18 06:31:45 +00002044 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
2045 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002046 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002047 makeArrayRef(Args, NumArgs),RBracLoc,
2048 isImplicit));
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002049 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002050
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002051 // Find the class to which we are sending this message.
2052 ObjCInterfaceDecl *Class = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002053 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2054 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002055 Diag(Loc, diag::err_invalid_receiver_class_message)
2056 << ReceiverType;
2057 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002058 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002059 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002060 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002061 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002062 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002063 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002064 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002065 SourceRange TypeRange
2066 = SuperLoc.isValid()? SourceRange(SuperLoc)
2067 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002068 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002069 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002070 ? diag::err_arc_receiver_forward_class
2071 : diag::warn_receiver_forward_class),
2072 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002073 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002074 Method = LookupFactoryMethodInGlobalPool(Sel,
2075 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002076 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002077 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2078 << Method->getDeclName();
2079 }
2080 if (!Method)
2081 Method = Class->lookupClassMethod(Sel);
2082
2083 // If we have an implementation in scope, check "private" methods.
2084 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002085 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002086
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002087 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002088 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002089 }
Mike Stump11289f42009-09-09 15:08:12 +00002090
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002091 // Check the argument types and determine the result type.
2092 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002093 ExprValueKind VK = VK_RValue;
2094
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002095 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002096 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002097 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2098 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002099 Method, true,
Douglas Gregor33823722011-06-11 01:09:30 +00002100 SuperLoc.isValid(), LBracLoc, RBracLoc,
2101 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002102 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002103
Douglas Gregoraec93c62011-01-11 03:23:19 +00002104 if (Method && !Method->getResultType()->isVoidType() &&
2105 RequireCompleteType(LBracLoc, Method->getResultType(),
2106 diag::err_illegal_message_expr_incomplete_type))
2107 return ExprError();
2108
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002109 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002110 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002111 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002112 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002113 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002114 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002115 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002116 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002117 else {
John McCall7decc9e2010-11-18 06:31:45 +00002118 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002119 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002120 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002121 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002122 if (!isImplicit)
2123 checkCocoaAPI(*this, Result);
2124 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002125 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002126}
2127
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002128// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002129// ArgExprs is optional - if it is present, the number of expressions
2130// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002131ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002132 ParsedType Receiver,
2133 Selector Sel,
2134 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002135 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002136 SourceLocation RBracLoc,
2137 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002138 TypeSourceInfo *ReceiverTypeInfo;
2139 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2140 if (ReceiverType.isNull())
2141 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002142
Mike Stump11289f42009-09-09 15:08:12 +00002143
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002144 if (!ReceiverTypeInfo)
2145 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2146
2147 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorb5186b12010-04-22 17:01:48 +00002148 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002149 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002150}
2151
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002152ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2153 QualType ReceiverType,
2154 SourceLocation Loc,
2155 Selector Sel,
2156 ObjCMethodDecl *Method,
2157 MultiExprArg Args) {
2158 return BuildInstanceMessage(Receiver, ReceiverType,
2159 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2160 Sel, Method, Loc, Loc, Loc, Args,
2161 /*isImplicit=*/true);
2162}
2163
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002164/// \brief Build an Objective-C instance message expression.
2165///
2166/// This routine takes care of both normal instance messages and
2167/// instance messages to the superclass instance.
2168///
2169/// \param Receiver The expression that computes the object that will
2170/// receive this message. This may be empty, in which case we are
2171/// sending to the superclass instance and \p SuperLoc must be a valid
2172/// source location.
2173///
2174/// \param ReceiverType The (static) type of the object receiving the
2175/// message. When a \p Receiver expression is provided, this is the
2176/// same type as that expression. For a superclass instance send, this
2177/// is a pointer to the type of the superclass.
2178///
2179/// \param SuperLoc The location of the "super" keyword in a
2180/// superclass instance message.
2181///
2182/// \param Sel The selector to which the message is being sent.
2183///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002184/// \param Method The method that this instance message is invoking, if
2185/// already known.
2186///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002187/// \param LBracLoc The location of the opening square bracket ']'.
2188///
James Dennettffad8b72012-06-22 08:10:18 +00002189/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002190///
James Dennettffad8b72012-06-22 08:10:18 +00002191/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002192ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002193 QualType ReceiverType,
2194 SourceLocation SuperLoc,
2195 Selector Sel,
2196 ObjCMethodDecl *Method,
2197 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002198 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002199 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002200 MultiExprArg ArgsIn,
2201 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002202 // The location of the receiver.
2203 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002204 SourceRange RecRange =
2205 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2206 SourceLocation SelLoc;
2207 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2208 SelLoc = SelectorLocs.front();
2209 else
2210 SelLoc = Loc;
2211
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002212 if (LBracLoc.isInvalid()) {
2213 Diag(Loc, diag::err_missing_open_square_message_send)
2214 << FixItHint::CreateInsertion(Loc, "[");
2215 LBracLoc = Loc;
2216 }
2217
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002218 // If we have a receiver expression, perform appropriate promotions
2219 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002220 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002221 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002222 ExprResult Result;
2223 if (Receiver->getType() == Context.UnknownAnyTy)
2224 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2225 else
2226 Result = CheckPlaceholderExpr(Receiver);
2227 if (Result.isInvalid()) return ExprError();
2228 Receiver = Result.take();
John McCall4124c492011-10-17 18:40:02 +00002229 }
2230
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002231 if (Receiver->isTypeDependent()) {
2232 // If the receiver is type-dependent, we can't type-check anything
2233 // at this point. Build a dependent expression.
2234 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002235 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002236 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2237 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00002238 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002239 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002240 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002241 RBracLoc, isImplicit));
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002242 }
2243
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002244 // If necessary, apply function/array conversion to the receiver.
2245 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002246 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2247 if (Result.isInvalid())
2248 return ExprError();
2249 Receiver = Result.take();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002250 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002251
2252 // If the receiver is an ObjC pointer, a block pointer, or an
2253 // __attribute__((NSObject)) pointer, we don't need to do any
2254 // special conversion in order to look up a receiver.
2255 if (ReceiverType->isObjCRetainableType()) {
2256 // do nothing
2257 } else if (!getLangOpts().ObjCAutoRefCount &&
2258 !Context.getObjCIdType().isNull() &&
2259 (ReceiverType->isPointerType() ||
2260 ReceiverType->isIntegerType())) {
2261 // Implicitly convert integers and pointers to 'id' but emit a warning.
2262 // But not in ARC.
2263 Diag(Loc, diag::warn_bad_receiver_type)
2264 << ReceiverType
2265 << Receiver->getSourceRange();
2266 if (ReceiverType->isPointerType()) {
2267 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2268 CK_CPointerToObjCPointerCast).take();
2269 } else {
2270 // TODO: specialized warning on null receivers?
2271 bool IsNull = Receiver->isNullPointerConstant(Context,
2272 Expr::NPC_ValueDependentIsNull);
2273 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2274 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2275 Kind).take();
2276 }
2277 ReceiverType = Receiver->getType();
2278 } else if (getLangOpts().CPlusPlus) {
2279 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2280 if (result.isUsable()) {
2281 Receiver = result.take();
2282 ReceiverType = Receiver->getType();
2283 }
2284 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002285 }
2286
John McCall80c93a02013-03-01 09:20:14 +00002287 // There's a somewhat weird interaction here where we assume that we
2288 // won't actually have a method unless we also don't need to do some
2289 // of the more detailed type-checking on the receiver.
2290
Douglas Gregorb5186b12010-04-22 17:01:48 +00002291 if (!Method) {
2292 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002293 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002294 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002295 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2296 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002297 SourceRange(LBracLoc, RBracLoc),
2298 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002299 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002300 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002301 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002302 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002303 } else if (ReceiverType->isObjCClassType() ||
2304 ReceiverType->isObjCQualifiedClassType()) {
2305 // Handle messages to Class.
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002306 // We allow sending a message to a qualified Class ("Class<foo>"), which
2307 // is ok as long as one of the protocols implements the selector (if not, warn).
2308 if (const ObjCObjectPointerType *QClassTy
2309 = ReceiverType->getAsObjCQualifiedClassType()) {
2310 // Search protocols for class methods.
2311 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2312 if (!Method) {
2313 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2314 // warn if instance method found for a Class message.
2315 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002316 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002317 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002318 Diag(Method->getLocation(), diag::note_method_declared_at)
2319 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002320 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002321 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002322 } else {
2323 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2324 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2325 // First check the public methods in the class interface.
2326 Method = ClassDecl->lookupClassMethod(Sel);
2327
2328 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002329 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002330 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002331 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002332 return ExprError();
2333 }
2334 if (!Method) {
2335 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002336 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002337 Method = LookupFactoryMethodInGlobalPool(Sel,
2338 SourceRange(LBracLoc, RBracLoc),
2339 true);
2340 if (!Method) {
2341 // If no class (factory) method was found, check if an _instance_
2342 // method of the same name exists in the root class only.
2343 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002344 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002345 true);
2346 if (Method)
2347 if (const ObjCInterfaceDecl *ID =
2348 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2349 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002350 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002351 << Sel << SourceRange(LBracLoc, RBracLoc);
2352 }
2353 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002354 }
2355 }
2356 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002357 } else {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002358 ObjCInterfaceDecl* ClassDecl = 0;
2359
2360 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2361 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002362 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002363 if (const ObjCObjectPointerType *QIdTy
2364 = ReceiverType->getAsObjCQualifiedIdType()) {
2365 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002366 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2367 if (!Method)
2368 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002369 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002370 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002371 } else if (const ObjCObjectPointerType *OCIType
2372 = ReceiverType->getAsObjCInterfacePointerType()) {
2373 // We allow sending a message to a pointer to an interface (an object).
2374 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002375
Douglas Gregor4123a862011-11-14 22:10:01 +00002376 // Try to complete the type. Under ARC, this is a hard error from which
2377 // we don't try to recover.
2378 const ObjCInterfaceDecl *forwardClass = 0;
2379 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002380 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002381 ? diag::err_arc_receiver_forward_instance
2382 : diag::warn_receiver_forward_instance,
2383 Receiver? Receiver->getSourceRange()
2384 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002385 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002386 return ExprError();
2387
2388 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002389 Diag(Receiver ? Receiver->getLocStart()
2390 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002391 Method = 0;
2392 } else {
2393 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002394 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002395
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002396 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002397 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002398 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2399
Douglas Gregorb5186b12010-04-22 17:01:48 +00002400 if (!Method) {
2401 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002402 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002403
David Blaikiebbafb8a2012-03-11 07:00:24 +00002404 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002405 Diag(SelLoc, diag::err_arc_may_not_respond)
2406 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002407 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002408 return ExprError();
2409 }
2410
Douglas Gregor486b74e2011-09-27 16:10:05 +00002411 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002412 // If we still haven't found a method, look in the global pool. This
2413 // behavior isn't very desirable, however we need it for GCC
2414 // compatibility. FIXME: should we deviate??
2415 if (OCIType->qual_empty()) {
2416 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002417 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002418 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002419 Diag(SelLoc, diag::warn_maynot_respond)
2420 << OCIType->getInterfaceDecl()->getIdentifier()
2421 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002422 }
2423 }
2424 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002425 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002426 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002427 } else {
John McCall80c93a02013-03-01 09:20:14 +00002428 // Reject other random receiver types (e.g. structs).
2429 Diag(Loc, diag::err_bad_receiver_type)
2430 << ReceiverType << Receiver->getSourceRange();
2431 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002432 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002433 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002434 }
Mike Stump11289f42009-09-09 15:08:12 +00002435
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002436 // Check the message arguments.
2437 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002438 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002439 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002440 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002441 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2442 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002443 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2444 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002445 ClassMessage, SuperLoc.isValid(),
John McCall7decc9e2010-11-18 06:31:45 +00002446 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002447 return ExprError();
Fariborz Jahanian18e02752010-06-16 19:56:08 +00002448
Douglas Gregoraec93c62011-01-11 03:23:19 +00002449 if (Method && !Method->getResultType()->isVoidType() &&
2450 RequireCompleteType(LBracLoc, Method->getResultType(),
2451 diag::err_illegal_message_expr_incomplete_type))
2452 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002453
John McCall31168b02011-06-15 23:02:42 +00002454 // In ARC, forbid the user from sending messages to
2455 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002456 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002457 ObjCMethodFamily family =
2458 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2459 switch (family) {
2460 case OMF_init:
2461 if (Method)
2462 checkInitMethod(Method, ReceiverType);
2463
2464 case OMF_None:
2465 case OMF_alloc:
2466 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002467 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002468 case OMF_mutableCopy:
2469 case OMF_new:
2470 case OMF_self:
2471 break;
2472
2473 case OMF_dealloc:
2474 case OMF_retain:
2475 case OMF_release:
2476 case OMF_autorelease:
2477 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002478 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2479 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002480 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002481
2482 case OMF_performSelector:
2483 if (Method && NumArgs >= 1) {
2484 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2485 Selector ArgSel = SelExp->getSelector();
2486 ObjCMethodDecl *SelMethod =
2487 LookupInstanceMethodInGlobalPool(ArgSel,
2488 SelExp->getSourceRange());
2489 if (!SelMethod)
2490 SelMethod =
2491 LookupFactoryMethodInGlobalPool(ArgSel,
2492 SelExp->getSourceRange());
2493 if (SelMethod) {
2494 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2495 switch (SelFamily) {
2496 case OMF_alloc:
2497 case OMF_copy:
2498 case OMF_mutableCopy:
2499 case OMF_new:
2500 case OMF_self:
2501 case OMF_init:
2502 // Issue error, unless ns_returns_not_retained.
2503 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2504 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002505 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002506 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002507 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2508 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002509 }
2510 break;
2511 default:
2512 // +0 call. OK. unless ns_returns_retained.
2513 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2514 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002515 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002516 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002517 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2518 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002519 }
2520 break;
2521 }
2522 }
2523 } else {
2524 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002525 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002526 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2527 }
2528 }
2529 break;
John McCall31168b02011-06-15 23:02:42 +00002530 }
2531 }
2532
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002533 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002534 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002535 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002536 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002537 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002538 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002539 makeArrayRef(Args, NumArgs), RBracLoc,
2540 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002541 else {
John McCall7decc9e2010-11-18 06:31:45 +00002542 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002543 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002544 makeArrayRef(Args, NumArgs), RBracLoc,
2545 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002546 if (!isImplicit)
2547 checkCocoaAPI(*this, Result);
2548 }
John McCall31168b02011-06-15 23:02:42 +00002549
David Blaikiebbafb8a2012-03-11 07:00:24 +00002550 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahaniand155c782012-04-19 23:49:39 +00002551 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian6bd22262012-04-04 20:05:25 +00002552
John McCall31168b02011-06-15 23:02:42 +00002553 // In ARC, annotate delegate init calls.
2554 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002555 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002556 // Only consider init calls *directly* in init implementations,
2557 // not within blocks.
2558 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2559 if (method && method->getMethodFamily() == OMF_init) {
2560 // The implicit assignment to self means we also don't want to
2561 // consume the result.
2562 Result->setDelegateInitCall(true);
2563 return Owned(Result);
2564 }
2565 }
2566
2567 // In ARC, check for message sends which are likely to introduce
2568 // retain cycles.
2569 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002570
2571 if (!isImplicit && Method) {
2572 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2573 bool IsWeak =
2574 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2575 if (!IsWeak && Sel.isUnarySelector())
2576 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
2577
2578 if (IsWeak) {
2579 DiagnosticsEngine::Level Level =
2580 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
2581 LBracLoc);
2582 if (Level != DiagnosticsEngine::Ignored)
2583 getCurFunction()->recordUseOfWeak(Result, Prop);
2584
2585 }
2586 }
2587 }
John McCall31168b02011-06-15 23:02:42 +00002588 }
2589
Douglas Gregoraae38d62010-05-22 05:17:18 +00002590 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002591}
2592
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002593static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2594 if (ObjCSelectorExpr *OSE =
2595 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2596 Selector Sel = OSE->getSelector();
2597 SourceLocation Loc = OSE->getAtLoc();
2598 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2599 = S.ReferencedSelectors.find(Sel);
2600 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2601 S.ReferencedSelectors.erase(Pos);
2602 }
2603}
2604
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002605// ActOnInstanceMessage - used for both unary and keyword messages.
2606// ArgExprs is optional - if it is present, the number of expressions
2607// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002608ExprResult Sema::ActOnInstanceMessage(Scope *S,
2609 Expr *Receiver,
2610 Selector Sel,
2611 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002612 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002613 SourceLocation RBracLoc,
2614 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002615 if (!Receiver)
2616 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002617
2618 // A ParenListExpr can show up while doing error recovery with invalid code.
2619 if (isa<ParenListExpr>(Receiver)) {
2620 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2621 if (Result.isInvalid()) return ExprError();
2622 Receiver = Result.take();
2623 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002624
2625 if (RespondsToSelectorSel.isNull()) {
2626 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2627 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2628 }
2629 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002630 RemoveSelectorFromWarningCache(*this, Args[0]);
2631
John McCallb268a282010-08-23 23:25:46 +00002632 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorb5186b12010-04-22 17:01:48 +00002633 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002634 LBracLoc, SelectorLocs, RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002635}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002636
John McCall31168b02011-06-15 23:02:42 +00002637enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002638 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002639 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002640
2641 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002642 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002643
2644 /// id*, id***, void (^*)(),
2645 ACTC_indirectRetainable,
2646
2647 /// void* might be a normal C type, or it might a CF type.
2648 ACTC_voidPtr,
2649
2650 /// struct A*
2651 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002652};
John McCalle4fe2452011-10-01 01:01:08 +00002653static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2654 return (ACTC == ACTC_retainable ||
2655 ACTC == ACTC_coreFoundation ||
2656 ACTC == ACTC_voidPtr);
2657}
2658static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2659 return ACTC == ACTC_none ||
2660 ACTC == ACTC_voidPtr ||
2661 ACTC == ACTC_coreFoundation;
2662}
2663
John McCall31168b02011-06-15 23:02:42 +00002664static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002665 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002666
2667 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002668 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002669 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002670 isIndirect = true;
2671 }
John McCall31168b02011-06-15 23:02:42 +00002672
2673 // Drill through pointers and arrays recursively.
2674 while (true) {
2675 if (const PointerType *ptr = type->getAs<PointerType>()) {
2676 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002677
2678 // The first level of pointer may be the innermost pointer on a CF type.
2679 if (!isIndirect) {
2680 if (type->isVoidType()) return ACTC_voidPtr;
2681 if (type->isRecordType()) return ACTC_coreFoundation;
2682 }
John McCall31168b02011-06-15 23:02:42 +00002683 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2684 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2685 } else {
2686 break;
2687 }
John McCalle4fe2452011-10-01 01:01:08 +00002688 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002689 }
2690
John McCalle4fe2452011-10-01 01:01:08 +00002691 if (isIndirect) {
2692 if (type->isObjCARCBridgableType())
2693 return ACTC_indirectRetainable;
2694 return ACTC_none;
2695 }
2696
2697 if (type->isObjCARCBridgableType())
2698 return ACTC_retainable;
2699
2700 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002701}
2702
2703namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002704 /// A result from the cast checker.
2705 enum ACCResult {
2706 /// Cannot be casted.
2707 ACC_invalid,
2708
2709 /// Can be safely retained or not retained.
2710 ACC_bottom,
2711
2712 /// Can be casted at +0.
2713 ACC_plusZero,
2714
2715 /// Can be casted at +1.
2716 ACC_plusOne
2717 };
2718 ACCResult merge(ACCResult left, ACCResult right) {
2719 if (left == right) return left;
2720 if (left == ACC_bottom) return right;
2721 if (right == ACC_bottom) return left;
2722 return ACC_invalid;
2723 }
2724
2725 /// A checker which white-lists certain expressions whose conversion
2726 /// to or from retainable type would otherwise be forbidden in ARC.
2727 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2728 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2729
John McCall31168b02011-06-15 23:02:42 +00002730 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002731 ARCConversionTypeClass SourceClass;
2732 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002733 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002734
2735 static bool isCFType(QualType type) {
2736 // Someday this can use ns_bridged. For now, it has to do this.
2737 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002738 }
John McCalle4fe2452011-10-01 01:01:08 +00002739
2740 public:
2741 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002742 ARCConversionTypeClass target, bool diagnose)
2743 : Context(Context), SourceClass(source), TargetClass(target),
2744 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00002745
2746 using super::Visit;
2747 ACCResult Visit(Expr *e) {
2748 return super::Visit(e->IgnoreParens());
2749 }
2750
2751 ACCResult VisitStmt(Stmt *s) {
2752 return ACC_invalid;
2753 }
2754
2755 /// Null pointer constants can be casted however you please.
2756 ACCResult VisitExpr(Expr *e) {
2757 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2758 return ACC_bottom;
2759 return ACC_invalid;
2760 }
2761
2762 /// Objective-C string literals can be safely casted.
2763 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2764 // If we're casting to any retainable type, go ahead. Global
2765 // strings are immune to retains, so this is bottom.
2766 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2767
2768 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002769 }
2770
John McCalle4fe2452011-10-01 01:01:08 +00002771 /// Look through certain implicit and explicit casts.
2772 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002773 switch (e->getCastKind()) {
2774 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00002775 return ACC_bottom;
2776
John McCall31168b02011-06-15 23:02:42 +00002777 case CK_NoOp:
2778 case CK_LValueToRValue:
2779 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002780 case CK_CPointerToObjCPointerCast:
2781 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002782 case CK_AnyPointerToBlockPointerCast:
2783 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00002784
John McCall31168b02011-06-15 23:02:42 +00002785 default:
John McCalle4fe2452011-10-01 01:01:08 +00002786 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002787 }
2788 }
John McCalle4fe2452011-10-01 01:01:08 +00002789
2790 /// Look through unary extension.
2791 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002792 return Visit(e->getSubExpr());
2793 }
John McCalle4fe2452011-10-01 01:01:08 +00002794
2795 /// Ignore the LHS of a comma operator.
2796 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002797 return Visit(e->getRHS());
2798 }
John McCalle4fe2452011-10-01 01:01:08 +00002799
2800 /// Conditional operators are okay if both sides are okay.
2801 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2802 ACCResult left = Visit(e->getTrueExpr());
2803 if (left == ACC_invalid) return ACC_invalid;
2804 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00002805 }
John McCalle4fe2452011-10-01 01:01:08 +00002806
John McCallfe96e0b2011-11-06 09:01:30 +00002807 /// Look through pseudo-objects.
2808 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2809 // If we're getting here, we should always have a result.
2810 return Visit(e->getResultExpr());
2811 }
2812
John McCalle4fe2452011-10-01 01:01:08 +00002813 /// Statement expressions are okay if their result expression is okay.
2814 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002815 return Visit(e->getSubStmt()->body_back());
2816 }
John McCall31168b02011-06-15 23:02:42 +00002817
John McCalle4fe2452011-10-01 01:01:08 +00002818 /// Some declaration references are okay.
2819 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2820 // References to global constants from system headers are okay.
2821 // These are things like 'kCFStringTransformToLatin'. They are
2822 // can also be assumed to be immune to retains.
2823 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2824 if (isAnyRetainable(TargetClass) &&
2825 isAnyRetainable(SourceClass) &&
2826 var &&
2827 var->getStorageClass() == SC_Extern &&
2828 var->getType().isConstQualified() &&
2829 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2830 return ACC_bottom;
2831 }
2832
2833 // Nothing else.
2834 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00002835 }
John McCalle4fe2452011-10-01 01:01:08 +00002836
2837 /// Some calls are okay.
2838 ACCResult VisitCallExpr(CallExpr *e) {
2839 if (FunctionDecl *fn = e->getDirectCallee())
2840 if (ACCResult result = checkCallToFunction(fn))
2841 return result;
2842
2843 return super::VisitCallExpr(e);
2844 }
2845
2846 ACCResult checkCallToFunction(FunctionDecl *fn) {
2847 // Require a CF*Ref return type.
2848 if (!isCFType(fn->getResultType()))
2849 return ACC_invalid;
2850
2851 if (!isAnyRetainable(TargetClass))
2852 return ACC_invalid;
2853
2854 // Honor an explicit 'not retained' attribute.
2855 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2856 return ACC_plusZero;
2857
2858 // Honor an explicit 'retained' attribute, except that for
2859 // now we're not going to permit implicit handling of +1 results,
2860 // because it's a bit frightening.
2861 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00002862 return Diagnose ? ACC_plusOne
2863 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00002864
2865 // Recognize this specific builtin function, which is used by CFSTR.
2866 unsigned builtinID = fn->getBuiltinID();
2867 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2868 return ACC_bottom;
2869
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00002870 // Otherwise, don't do anything implicit with an unaudited function.
2871 if (!fn->hasAttr<CFAuditedTransferAttr>())
2872 return ACC_invalid;
2873
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002874 // Otherwise, it's +0 unless it follows the create convention.
2875 if (ento::coreFoundation::followsCreateRule(fn))
2876 return Diagnose ? ACC_plusOne
2877 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00002878
John McCalle4fe2452011-10-01 01:01:08 +00002879 return ACC_plusZero;
2880 }
2881
2882 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2883 return checkCallToMethod(e->getMethodDecl());
2884 }
2885
2886 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2887 ObjCMethodDecl *method;
2888 if (e->isExplicitProperty())
2889 method = e->getExplicitProperty()->getGetterMethodDecl();
2890 else
2891 method = e->getImplicitPropertyGetter();
2892 return checkCallToMethod(method);
2893 }
2894
2895 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2896 if (!method) return ACC_invalid;
2897
2898 // Check for message sends to functions returning CF types. We
2899 // just obey the Cocoa conventions with these, even though the
2900 // return type is CF.
2901 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2902 return ACC_invalid;
2903
2904 // If the method is explicitly marked not-retained, it's +0.
2905 if (method->hasAttr<CFReturnsNotRetainedAttr>())
2906 return ACC_plusZero;
2907
2908 // If the method is explicitly marked as returning retained, or its
2909 // selector follows a +1 Cocoa convention, treat it as +1.
2910 if (method->hasAttr<CFReturnsRetainedAttr>())
2911 return ACC_plusOne;
2912
2913 switch (method->getSelector().getMethodFamily()) {
2914 case OMF_alloc:
2915 case OMF_copy:
2916 case OMF_mutableCopy:
2917 case OMF_new:
2918 return ACC_plusOne;
2919
2920 default:
2921 // Otherwise, treat it as +0.
2922 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00002923 }
2924 }
John McCalle4fe2452011-10-01 01:01:08 +00002925 };
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00002926}
2927
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00002928bool Sema::isKnownName(StringRef name) {
2929 if (name.empty())
2930 return false;
2931 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00002932 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00002933 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00002934}
2935
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002936static void addFixitForObjCARCConversion(Sema &S,
2937 DiagnosticBuilder &DiagB,
2938 Sema::CheckedConversionKind CCK,
2939 SourceLocation afterLParen,
2940 QualType castType,
2941 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00002942 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002943 const char *bridgeKeyword,
2944 const char *CFBridgeName) {
2945 // We handle C-style and implicit casts here.
2946 switch (CCK) {
2947 case Sema::CCK_ImplicitConversion:
2948 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00002949 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002950 break;
2951 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002952 return;
2953 }
2954
2955 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00002956 if (CCK == Sema::CCK_OtherCast) {
2957 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
2958 SourceRange range(NCE->getOperatorLoc(),
2959 NCE->getAngleBrackets().getEnd());
2960 SmallString<32> BridgeCall;
2961
2962 SourceManager &SM = S.getSourceManager();
2963 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
2964 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
2965 BridgeCall += ' ';
2966
2967 BridgeCall += CFBridgeName;
2968 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
2969 }
2970 return;
2971 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002972 Expr *castedE = castExpr;
2973 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2974 castedE = CCE->getSubExpr();
2975 castedE = castedE->IgnoreImpCasts();
2976 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00002977
2978 SmallString<32> BridgeCall;
2979
2980 SourceManager &SM = S.getSourceManager();
2981 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
2982 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
2983 BridgeCall += ' ';
2984
2985 BridgeCall += CFBridgeName;
2986
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002987 if (isa<ParenExpr>(castedE)) {
2988 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00002989 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002990 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00002991 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002992 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00002993 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002994 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2995 S.PP.getLocForEndOfToken(range.getEnd()),
2996 ")"));
2997 }
2998 return;
2999 }
3000
3001 if (CCK == Sema::CCK_CStyleCast) {
3002 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003003 } else if (CCK == Sema::CCK_OtherCast) {
3004 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3005 std::string castCode = "(";
3006 castCode += bridgeKeyword;
3007 castCode += castType.getAsString();
3008 castCode += ")";
3009 SourceRange Range(NCE->getOperatorLoc(),
3010 NCE->getAngleBrackets().getEnd());
3011 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3012 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003013 } else {
3014 std::string castCode = "(";
3015 castCode += bridgeKeyword;
3016 castCode += castType.getAsString();
3017 castCode += ")";
3018 Expr *castedE = castExpr->IgnoreImpCasts();
3019 SourceRange range = castedE->getSourceRange();
3020 if (isa<ParenExpr>(castedE)) {
3021 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3022 castCode));
3023 } else {
3024 castCode += "(";
3025 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3026 castCode));
3027 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3028 S.PP.getLocForEndOfToken(range.getEnd()),
3029 ")"));
3030 }
3031 }
3032}
3033
John McCall4124c492011-10-17 18:40:02 +00003034static void
3035diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3036 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003037 Expr *castExpr, Expr *realCast,
3038 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003039 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003040 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003041 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003042
John McCall4124c492011-10-17 18:40:02 +00003043 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003044 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003045 return;
John McCall4124c492011-10-17 18:40:02 +00003046
3047 QualType castExprType = castExpr->getType();
John McCall31168b02011-06-15 23:02:42 +00003048
John McCall640767f2011-06-17 06:50:50 +00003049 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003050 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003051 case ACTC_none:
3052 case ACTC_coreFoundation:
3053 case ACTC_voidPtr:
3054 srcKind = (castExprType->isPointerType() ? 1 : 0);
3055 break;
3056 case ACTC_retainable:
3057 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3058 break;
3059 case ACTC_indirectRetainable:
3060 srcKind = 4;
3061 break;
John McCall31168b02011-06-15 23:02:42 +00003062 }
3063
John McCall4124c492011-10-17 18:40:02 +00003064 // Check whether this could be fixed with a bridge cast.
3065 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3066 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003067
John McCall4124c492011-10-17 18:40:02 +00003068 // Bridge from an ARC type to a CF type.
3069 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003070
John McCall4124c492011-10-17 18:40:02 +00003071 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3072 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3073 << 2 // of C pointer type
3074 << castExprType
3075 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3076 << castType
3077 << castRange
3078 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003079 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003080 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003081 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003082 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003083 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003084 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003085 DiagnosticBuilder DiagB =
3086 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3087 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3088
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003089 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003090 castType, castExpr, realCast, "__bridge ", 0);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003091 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003092 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003093 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003094 DiagnosticBuilder DiagB =
3095 (CCK == Sema::CCK_OtherCast && !br) ?
3096 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3097 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3098 diag::note_arc_bridge_transfer)
3099 << castExprType << br;
3100
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003101 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003102 castType, castExpr, realCast, "__bridge_transfer ",
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003103 br ? "CFBridgingRelease" : 0);
3104 }
John McCall4124c492011-10-17 18:40:02 +00003105
3106 return;
3107 }
3108
3109 // Bridge from a CF type to an ARC type.
3110 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003111 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003112 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3113 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3114 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3115 << castExprType
3116 << 2 // to C pointer type
3117 << castType
3118 << castRange
3119 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003120 ACCResult CreateRule =
3121 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003122 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003123 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003124 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003125 DiagnosticBuilder DiagB =
3126 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3127 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003128 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003129 castType, castExpr, realCast, "__bridge ", 0);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003130 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003131 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003132 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003133 DiagnosticBuilder DiagB =
3134 (CCK == Sema::CCK_OtherCast && !br) ?
3135 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3136 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3137 diag::note_arc_bridge_retained)
3138 << castType << br;
3139
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003140 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003141 castType, castExpr, realCast, "__bridge_retained ",
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003142 br ? "CFBridgingRetain" : 0);
3143 }
John McCall4124c492011-10-17 18:40:02 +00003144
3145 return;
John McCall31168b02011-06-15 23:02:42 +00003146 }
3147
John McCall4124c492011-10-17 18:40:02 +00003148 S.Diag(loc, diag::err_arc_mismatched_cast)
3149 << (CCK != Sema::CCK_ImplicitConversion)
3150 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003151 << castRange << castExpr->getSourceRange();
3152}
3153
John McCall4124c492011-10-17 18:40:02 +00003154Sema::ARCConversionResult
3155Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003156 Expr *&castExpr, CheckedConversionKind CCK,
3157 bool DiagnoseCFAudited) {
John McCall4124c492011-10-17 18:40:02 +00003158 QualType castExprType = castExpr->getType();
3159
3160 // For the purposes of the classification, we assume reference types
3161 // will bind to temporaries.
3162 QualType effCastType = castType;
3163 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3164 effCastType = ref->getPointeeType();
3165
3166 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3167 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003168 if (exprACTC == castACTC) {
3169 // check for viablity and report error if casting an rvalue to a
3170 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003171 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003172 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003173 (castType != castExprType)) {
3174 const Type *DT = castType.getTypePtr();
3175 QualType QDT = castType;
3176 // We desugar some types but not others. We ignore those
3177 // that cannot happen in a cast; i.e. auto, and those which
3178 // should not be de-sugared; i.e typedef.
3179 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3180 QDT = PT->desugar();
3181 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3182 QDT = TP->desugar();
3183 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3184 QDT = AT->desugar();
3185 if (QDT != castType &&
3186 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3187 SourceLocation loc =
3188 (castRange.isValid() ? castRange.getBegin()
3189 : castExpr->getExprLoc());
3190 Diag(loc, diag::err_arc_nolifetime_behavior);
3191 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003192 }
3193 return ACR_okay;
3194 }
3195
John McCall4124c492011-10-17 18:40:02 +00003196 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3197
3198 // Allow all of these types to be cast to integer types (but not
3199 // vice-versa).
3200 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3201 return ACR_okay;
3202
3203 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3204 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3205 // must be explicit.
3206 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3207 return ACR_okay;
3208 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3209 CCK != CCK_ImplicitConversion)
3210 return ACR_okay;
3211
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003212 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003213 // For invalid casts, fall through.
3214 case ACC_invalid:
3215 break;
3216
3217 // Do nothing for both bottom and +0.
3218 case ACC_bottom:
3219 case ACC_plusZero:
3220 return ACR_okay;
3221
3222 // If the result is +1, consume it here.
3223 case ACC_plusOne:
3224 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3225 CK_ARCConsumeObject, castExpr,
3226 0, VK_RValue);
3227 ExprNeedsCleanups = true;
3228 return ACR_okay;
3229 }
3230
3231 // If this is a non-implicit cast from id or block type to a
3232 // CoreFoundation type, delay complaining in case the cast is used
3233 // in an acceptable context.
3234 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3235 CCK != CCK_ImplicitConversion)
3236 return ACR_unbridged;
3237
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003238 // Do not issue "bridge cast" diagnostic when implicit casting
3239 // a retainable object to a CF type parameter belonging to an audited
3240 // CF API function. Let caller issue a normal type mismatched diagnostic
3241 // instead.
3242 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3243 castACTC != ACTC_coreFoundation)
3244 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3245 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003246 return ACR_okay;
3247}
3248
3249/// Given that we saw an expression with the ARCUnbridgedCastTy
3250/// placeholder type, complain bitterly.
3251void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3252 // We expect the spurious ImplicitCastExpr to already have been stripped.
3253 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3254 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3255
3256 SourceRange castRange;
3257 QualType castType;
3258 CheckedConversionKind CCK;
3259
3260 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3261 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3262 castType = cast->getTypeAsWritten();
3263 CCK = CCK_CStyleCast;
3264 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3265 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3266 castType = cast->getTypeAsWritten();
3267 CCK = CCK_OtherCast;
3268 } else {
3269 castType = cast->getType();
3270 CCK = CCK_ImplicitConversion;
3271 }
3272
3273 ARCConversionTypeClass castACTC =
3274 classifyTypeForARCConversion(castType.getNonReferenceType());
3275
3276 Expr *castExpr = realCast->getSubExpr();
3277 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3278
3279 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003280 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003281}
3282
3283/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3284/// type, remove the placeholder cast.
3285Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3286 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3287
3288 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3289 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3290 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3291 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3292 assert(uo->getOpcode() == UO_Extension);
3293 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3294 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3295 sub->getValueKind(), sub->getObjectKind(),
3296 uo->getOperatorLoc());
3297 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3298 assert(!gse->isResultDependent());
3299
3300 unsigned n = gse->getNumAssocs();
3301 SmallVector<Expr*, 4> subExprs(n);
3302 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3303 for (unsigned i = 0; i != n; ++i) {
3304 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3305 Expr *sub = gse->getAssocExpr(i);
3306 if (i == gse->getResultIndex())
3307 sub = stripARCUnbridgedCast(sub);
3308 subExprs[i] = sub;
3309 }
3310
3311 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3312 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003313 subTypes, subExprs,
3314 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003315 gse->getRParenLoc(),
3316 gse->containsUnexpandedParameterPack(),
3317 gse->getResultIndex());
3318 } else {
3319 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3320 return cast<ImplicitCastExpr>(e)->getSubExpr();
3321 }
3322}
3323
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003324bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3325 QualType exprType) {
3326 QualType canCastType =
3327 Context.getCanonicalType(castType).getUnqualifiedType();
3328 QualType canExprType =
3329 Context.getCanonicalType(exprType).getUnqualifiedType();
3330 if (isa<ObjCObjectPointerType>(canCastType) &&
3331 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3332 canExprType->isObjCObjectPointerType()) {
3333 if (const ObjCObjectPointerType *ObjT =
3334 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00003335 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3336 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003337 }
3338 return true;
3339}
3340
John McCall4db5c3c2011-07-07 06:58:02 +00003341/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3342static Expr *maybeUndoReclaimObject(Expr *e) {
3343 // For now, we just undo operands that are *immediately* reclaim
3344 // expressions, which prevents the vast majority of potential
3345 // problems here. To catch them all, we'd need to rebuild arbitrary
3346 // value-propagating subexpressions --- we can't reliably rebuild
3347 // in-place because of expression sharing.
3348 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00003349 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00003350 return ice->getSubExpr();
3351
3352 return e;
3353}
3354
John McCall31168b02011-06-15 23:02:42 +00003355ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3356 ObjCBridgeCastKind Kind,
3357 SourceLocation BridgeKeywordLoc,
3358 TypeSourceInfo *TSInfo,
3359 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00003360 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3361 if (SubResult.isInvalid()) return ExprError();
3362 SubExpr = SubResult.take();
3363
John McCall31168b02011-06-15 23:02:42 +00003364 QualType T = TSInfo->getType();
3365 QualType FromType = SubExpr->getType();
3366
John McCall9320b872011-09-09 05:25:32 +00003367 CastKind CK;
3368
John McCall31168b02011-06-15 23:02:42 +00003369 bool MustConsume = false;
3370 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3371 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00003372 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00003373 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3374 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00003375 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3376 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00003377 switch (Kind) {
3378 case OBC_Bridge:
3379 break;
3380
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003381 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003382 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00003383 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3384 << 2
3385 << FromType
3386 << (T->isBlockPointerType()? 1 : 0)
3387 << T
3388 << SubExpr->getSourceRange()
3389 << Kind;
3390 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3391 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3392 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003393 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00003394 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003395 br ? "CFBridgingRelease "
3396 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00003397
3398 Kind = OBC_Bridge;
3399 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003400 }
John McCall31168b02011-06-15 23:02:42 +00003401
3402 case OBC_BridgeTransfer:
3403 // We must consume the Objective-C object produced by the cast.
3404 MustConsume = true;
3405 break;
3406 }
3407 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3408 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00003409 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00003410 switch (Kind) {
3411 case OBC_Bridge:
John McCall4db5c3c2011-07-07 06:58:02 +00003412 // Reclaiming a value that's going to be __bridge-casted to CF
3413 // is very dangerous, so we don't do it.
3414 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCall31168b02011-06-15 23:02:42 +00003415 break;
3416
3417 case OBC_BridgeRetained:
3418 // Produce the object before casting it.
3419 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00003420 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00003421 SubExpr, 0, VK_RValue);
3422 break;
3423
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003424 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003425 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00003426 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3427 << (FromType->isBlockPointerType()? 1 : 0)
3428 << FromType
3429 << 2
3430 << T
3431 << SubExpr->getSourceRange()
3432 << Kind;
3433
3434 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3435 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3436 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003437 << T << br
3438 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3439 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00003440
3441 Kind = OBC_Bridge;
3442 break;
3443 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003444 }
John McCall31168b02011-06-15 23:02:42 +00003445 } else {
3446 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3447 << FromType << T << Kind
3448 << SubExpr->getSourceRange()
3449 << TSInfo->getTypeLoc().getSourceRange();
3450 return ExprError();
3451 }
3452
John McCall9320b872011-09-09 05:25:32 +00003453 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00003454 BridgeKeywordLoc,
3455 TSInfo, SubExpr);
3456
3457 if (MustConsume) {
3458 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00003459 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCall31168b02011-06-15 23:02:42 +00003460 0, VK_RValue);
3461 }
3462
3463 return Result;
3464}
3465
3466ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3467 SourceLocation LParenLoc,
3468 ObjCBridgeCastKind Kind,
3469 SourceLocation BridgeKeywordLoc,
3470 ParsedType Type,
3471 SourceLocation RParenLoc,
3472 Expr *SubExpr) {
3473 TypeSourceInfo *TSInfo = 0;
3474 QualType T = GetTypeFromParser(Type, &TSInfo);
3475 if (!TSInfo)
3476 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3477 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3478 SubExpr);
3479}