blob: 7c701ea040196923ed7c318105e8b69de1bfa9d9 [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,
327 QualType T) {
328 // If the expression is type-dependent, there's nothing for us to do.
329 if (Element->isTypeDependent())
330 return Element;
331
332 ExprResult Result = S.CheckPlaceholderExpr(Element);
333 if (Result.isInvalid())
334 return ExprError();
335 Element = Result.get();
336
337 // In C++, check for an implicit conversion to an Objective-C object pointer
338 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000339 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000340 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000341 = InitializedEntity::InitializeParameter(S.Context, T,
342 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000343 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000344 = InitializationKind::CreateCopy(Element->getLocStart(),
345 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000346 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000347 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000348 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000349 }
350
351 Expr *OrigElement = Element;
352
353 // Perform lvalue-to-rvalue conversion.
354 Result = S.DefaultLvalueConversion(Element);
355 if (Result.isInvalid())
356 return ExprError();
357 Element = Result.get();
358
359 // Make sure that we have an Objective-C pointer type or block.
360 if (!Element->getType()->isObjCObjectPointerType() &&
361 !Element->getType()->isBlockPointerType()) {
362 bool Recovered = false;
363
364 // If this is potentially an Objective-C numeric literal, add the '@'.
365 if (isa<IntegerLiteral>(OrigElement) ||
366 isa<CharacterLiteral>(OrigElement) ||
367 isa<FloatingLiteral>(OrigElement) ||
368 isa<ObjCBoolLiteralExpr>(OrigElement) ||
369 isa<CXXBoolLiteralExpr>(OrigElement)) {
370 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
371 int Which = isa<CharacterLiteral>(OrigElement) ? 1
372 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
373 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
374 : 3;
375
376 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
377 << Which << OrigElement->getSourceRange()
378 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
379
380 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
381 OrigElement);
382 if (Result.isInvalid())
383 return ExprError();
384
385 Element = Result.get();
386 Recovered = true;
387 }
388 }
389 // If this is potentially an Objective-C string literal, add the '@'.
390 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
391 if (String->isAscii()) {
392 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
393 << 0 << OrigElement->getSourceRange()
394 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
395
396 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
397 if (Result.isInvalid())
398 return ExprError();
399
400 Element = Result.get();
401 Recovered = true;
402 }
403 }
404
405 if (!Recovered) {
406 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
407 << Element->getType();
408 return ExprError();
409 }
410 }
411
412 // Make sure that the element has the type that the container factory
413 // function expects.
414 return S.PerformCopyInitialization(
415 InitializedEntity::InitializeParameter(S.Context, T,
416 /*Consumed=*/false),
417 Element->getLocStart(), Element);
418}
419
Patrick Beard0caa3942012-04-19 00:25:12 +0000420ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
421 if (ValueExpr->isTypeDependent()) {
422 ObjCBoxedExpr *BoxedExpr =
423 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR);
424 return Owned(BoxedExpr);
425 }
426 ObjCMethodDecl *BoxingMethod = NULL;
427 QualType BoxedType;
428 // Convert the expression to an RValue, so we can check for pointer types...
429 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
430 if (RValue.isInvalid()) {
431 return ExprError();
432 }
433 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000434 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000435 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
436 QualType PointeeType = PT->getPointeeType();
437 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
438
439 if (!NSStringDecl) {
440 IdentifierInfo *NSStringId =
441 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
442 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
443 SR.getBegin(), LookupOrdinaryName);
444 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
445 if (!NSStringDecl) {
446 if (getLangOpts().DebuggerObjCLiteral) {
447 // Support boxed expressions in the debugger w/o NSString declaration.
Jordy Roseaca01f92012-05-12 17:32:52 +0000448 DeclContext *TU = Context.getTranslationUnitDecl();
449 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
450 SourceLocation(),
451 NSStringId,
Patrick Beard0caa3942012-04-19 00:25:12 +0000452 0, SourceLocation());
453 } else {
454 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
455 return ExprError();
456 }
457 } else if (!NSStringDecl->hasDefinition()) {
458 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
459 return ExprError();
460 }
461 assert(NSStringDecl && "NSStringDecl should not be NULL");
Jordy Roseaca01f92012-05-12 17:32:52 +0000462 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
463 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000464 }
465
466 if (!StringWithUTF8StringMethod) {
467 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
468 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
469
470 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000471 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
472 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000473 // Debugger needs to work even if NSString hasn't been defined.
474 TypeSourceInfo *ResultTInfo = 0;
475 ObjCMethodDecl *M =
476 ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(),
477 stringWithUTF8String, NSStringPointer,
478 ResultTInfo, NSStringDecl,
479 /*isInstance=*/false, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000480 /*isPropertyAccessor=*/false,
Patrick Beard0caa3942012-04-19 00:25:12 +0000481 /*isImplicitlyDeclared=*/true,
482 /*isDefined=*/false,
483 ObjCMethodDecl::Required,
484 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000485 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000486 ParmVarDecl *value =
487 ParmVarDecl::Create(Context, M,
488 SourceLocation(), SourceLocation(),
489 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000490 Context.getPointerType(ConstCharType),
Patrick Beard0caa3942012-04-19 00:25:12 +0000491 /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000492 SC_None, 0);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000493 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000494 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000495 }
Jordy Rose890f4572012-05-12 15:53:41 +0000496
Jordy Rose08e500c2012-05-12 17:32:44 +0000497 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
498 stringWithUTF8String, BoxingMethod))
499 return ExprError();
500
501 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000502 }
503
504 BoxingMethod = StringWithUTF8StringMethod;
505 BoxedType = NSStringPointer;
506 }
Patrick Beard2565c592012-05-01 21:47:19 +0000507 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000508 // The other types we support are numeric, char and BOOL/bool. We could also
509 // provide limited support for structure types, such as NSRange, NSRect, and
510 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
511 // for more details.
512
513 // Check for a top-level character literal.
514 if (const CharacterLiteral *Char =
515 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
516 // In C, character literals have type 'int'. That's not the type we want
517 // to use to determine the Objective-c literal kind.
518 switch (Char->getKind()) {
519 case CharacterLiteral::Ascii:
520 ValueType = Context.CharTy;
521 break;
522
523 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000524 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000525 break;
526
527 case CharacterLiteral::UTF16:
528 ValueType = Context.Char16Ty;
529 break;
530
531 case CharacterLiteral::UTF32:
532 ValueType = Context.Char32Ty;
533 break;
534 }
535 }
536
537 // FIXME: Do I need to do anything special with BoolTy expressions?
538
539 // Look for the appropriate method within NSNumber.
540 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
541 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000542
543 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
544 if (!ET->getDecl()->isComplete()) {
545 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
546 << ValueType << ValueExpr->getSourceRange();
547 return ExprError();
548 }
549
550 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
551 ET->getDecl()->getIntegerType());
552 BoxedType = NSNumberPointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000553 }
554
555 if (!BoxingMethod) {
556 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
557 << ValueType << ValueExpr->getSourceRange();
558 return ExprError();
559 }
560
561 // Convert the expression to the type that the parameter requires.
Patrick Beard2565c592012-05-01 21:47:19 +0000562 ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0];
563 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
564 ParamDecl);
565 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
566 SourceLocation(),
567 Owned(ValueExpr));
Patrick Beard0caa3942012-04-19 00:25:12 +0000568 if (ConvertedValueExpr.isInvalid())
569 return ExprError();
570 ValueExpr = ConvertedValueExpr.get();
571
572 ObjCBoxedExpr *BoxedExpr =
573 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
574 BoxingMethod, SR);
575 return MaybeBindToTemporary(BoxedExpr);
576}
577
John McCallf2538342012-07-31 05:14:30 +0000578/// Build an ObjC subscript pseudo-object expression, given that
579/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000580ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
581 Expr *IndexExpr,
582 ObjCMethodDecl *getterMethod,
583 ObjCMethodDecl *setterMethod) {
John McCallf2538342012-07-31 05:14:30 +0000584 assert(!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000585
John McCallf2538342012-07-31 05:14:30 +0000586 // We can't get dependent types here; our callers should have
587 // filtered them out.
588 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
589 "base or index cannot have dependent type here");
590
591 // Filter out placeholders in the index. In theory, overloads could
592 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000593 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
594 if (Result.isInvalid())
595 return ExprError();
596 IndexExpr = Result.get();
597
John McCallf2538342012-07-31 05:14:30 +0000598 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000599 Result = DefaultLvalueConversion(BaseExpr);
600 if (Result.isInvalid())
601 return ExprError();
602 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000603
604 // Build the pseudo-object expression.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000605 return Owned(ObjCSubscriptRefExpr::Create(Context,
606 BaseExpr,
607 IndexExpr,
608 Context.PseudoObjectTy,
609 getterMethod,
610 setterMethod, RB));
611
612}
613
614ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
615 // Look up the NSArray class, if we haven't done so already.
616 if (!NSArrayDecl) {
617 NamedDecl *IF = LookupSingleName(TUScope,
618 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
619 SR.getBegin(),
620 LookupOrdinaryName);
621 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000622 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000623 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
624 Context.getTranslationUnitDecl(),
625 SourceLocation(),
626 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
627 0, SourceLocation());
628
629 if (!NSArrayDecl) {
630 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
631 return ExprError();
632 }
633 }
634
635 // Find the arrayWithObjects:count: method, if we haven't done so already.
636 QualType IdT = Context.getObjCIdType();
637 if (!ArrayWithObjectsMethod) {
638 Selector
639 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
Jordy Rose08e500c2012-05-12 17:32:44 +0000640 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
641 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000642 TypeSourceInfo *ResultTInfo = 0;
Jordy Rose08e500c2012-05-12 17:32:44 +0000643 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000644 SourceLocation(), SourceLocation(), Sel,
645 IdT,
646 ResultTInfo,
647 Context.getTranslationUnitDecl(),
648 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000649 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000650 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
651 ObjCMethodDecl::Required,
652 false);
653 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000654 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000655 SourceLocation(),
656 SourceLocation(),
657 &Context.Idents.get("objects"),
658 Context.getPointerType(IdT),
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000659 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000660 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000661 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000662 SourceLocation(),
663 SourceLocation(),
664 &Context.Idents.get("cnt"),
665 Context.UnsignedLongTy,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000666 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000667 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000668 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000669 }
670
Jordy Rose08e500c2012-05-12 17:32:44 +0000671 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000672 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000673
Jordy Rose4af44872012-05-12 17:32:56 +0000674 // Dig out the type that all elements should be converted to.
675 QualType T = Method->param_begin()[0]->getType();
676 const PointerType *PtrT = T->getAs<PointerType>();
677 if (!PtrT ||
678 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
679 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
680 << Sel;
681 Diag(Method->param_begin()[0]->getLocation(),
682 diag::note_objc_literal_method_param)
683 << 0 << T
684 << Context.getPointerType(IdT.withConst());
685 return ExprError();
686 }
687
688 // Check that the 'count' parameter is integral.
689 if (!Method->param_begin()[1]->getType()->isIntegerType()) {
690 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
691 << Sel;
692 Diag(Method->param_begin()[1]->getLocation(),
693 diag::note_objc_literal_method_param)
694 << 1
695 << Method->param_begin()[1]->getType()
696 << "integral";
697 return ExprError();
698 }
699
700 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000701 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000702 }
703
Jordy Rose4af44872012-05-12 17:32:56 +0000704 QualType ObjectsType = ArrayWithObjectsMethod->param_begin()[0]->getType();
705 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000706
707 // Check that each of the elements provided is valid in a collection literal,
708 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000709 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000710 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
711 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
712 ElementsBuffer[I],
Jordy Rose4af44872012-05-12 17:32:56 +0000713 RequiredType);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000714 if (Converted.isInvalid())
715 return ExprError();
716
717 ElementsBuffer[I] = Converted.get();
718 }
719
720 QualType Ty
721 = Context.getObjCObjectPointerType(
722 Context.getObjCInterfaceType(NSArrayDecl));
723
724 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000725 ObjCArrayLiteral::Create(Context, Elements, Ty,
726 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000727}
728
729ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
730 ObjCDictionaryElement *Elements,
731 unsigned NumElements) {
732 // Look up the NSDictionary class, if we haven't done so already.
733 if (!NSDictionaryDecl) {
734 NamedDecl *IF = LookupSingleName(TUScope,
735 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
736 SR.getBegin(), LookupOrdinaryName);
737 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000738 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000739 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
740 Context.getTranslationUnitDecl(),
741 SourceLocation(),
742 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
743 0, SourceLocation());
744
745 if (!NSDictionaryDecl) {
746 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
747 return ExprError();
748 }
749 }
750
751 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
752 // so already.
753 QualType IdT = Context.getObjCIdType();
754 if (!DictionaryWithObjectsMethod) {
755 Selector Sel = NSAPIObj->getNSDictionarySelector(
Jordy Roseaca01f92012-05-12 17:32:52 +0000756 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
Jordy Rose08e500c2012-05-12 17:32:44 +0000757 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
758 if (!Method && getLangOpts().DebuggerObjCLiteral) {
759 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000760 SourceLocation(), SourceLocation(), Sel,
761 IdT,
762 0 /*TypeSourceInfo */,
763 Context.getTranslationUnitDecl(),
764 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000765 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000766 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
767 ObjCMethodDecl::Required,
768 false);
769 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000770 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000771 SourceLocation(),
772 SourceLocation(),
773 &Context.Idents.get("objects"),
774 Context.getPointerType(IdT),
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000775 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000776 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000777 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000778 SourceLocation(),
779 SourceLocation(),
780 &Context.Idents.get("keys"),
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(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000784 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000785 SourceLocation(),
786 SourceLocation(),
787 &Context.Idents.get("cnt"),
788 Context.UnsignedLongTy,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000789 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000790 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000791 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000792 }
793
Jordy Rose08e500c2012-05-12 17:32:44 +0000794 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
795 Method))
796 return ExprError();
797
Jordy Rose4af44872012-05-12 17:32:56 +0000798 // Dig out the type that all values should be converted to.
799 QualType ValueT = Method->param_begin()[0]->getType();
800 const PointerType *PtrValue = ValueT->getAs<PointerType>();
801 if (!PtrValue ||
802 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000803 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000804 << Sel;
805 Diag(Method->param_begin()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000806 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000807 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000808 << Context.getPointerType(IdT.withConst());
809 return ExprError();
810 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000811
Jordy Rose4af44872012-05-12 17:32:56 +0000812 // Dig out the type that all keys should be converted to.
813 QualType KeyT = Method->param_begin()[1]->getType();
814 const PointerType *PtrKey = KeyT->getAs<PointerType>();
815 if (!PtrKey ||
816 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
817 IdT)) {
818 bool err = true;
819 if (PtrKey) {
820 if (QIDNSCopying.isNull()) {
821 // key argument of selector is id<NSCopying>?
822 if (ObjCProtocolDecl *NSCopyingPDecl =
823 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
824 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
825 QIDNSCopying =
826 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
827 (ObjCProtocolDecl**) PQ,1);
828 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
829 }
830 }
831 if (!QIDNSCopying.isNull())
832 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
833 QIDNSCopying);
834 }
835
836 if (err) {
837 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
838 << Sel;
839 Diag(Method->param_begin()[1]->getLocation(),
840 diag::note_objc_literal_method_param)
841 << 1 << KeyT
842 << Context.getPointerType(IdT.withConst());
843 return ExprError();
844 }
845 }
846
847 // Check that the 'count' parameter is integral.
848 QualType CountType = Method->param_begin()[2]->getType();
849 if (!CountType->isIntegerType()) {
850 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
851 << Sel;
852 Diag(Method->param_begin()[2]->getLocation(),
853 diag::note_objc_literal_method_param)
854 << 2 << CountType
855 << "integral";
856 return ExprError();
857 }
858
859 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
860 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000861 }
862
Jordy Rose4af44872012-05-12 17:32:56 +0000863 QualType ValuesT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
864 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
865 QualType KeysT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
866 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
867
Ted Kremeneke65b0862012-03-06 20:05:56 +0000868 // Check that each of the keys and values provided is valid in a collection
869 // literal, performing conversions as necessary.
870 bool HasPackExpansions = false;
871 for (unsigned I = 0, N = NumElements; I != N; ++I) {
872 // Check the key.
873 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
874 KeyT);
875 if (Key.isInvalid())
876 return ExprError();
877
878 // Check the value.
879 ExprResult Value
880 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
881 if (Value.isInvalid())
882 return ExprError();
883
884 Elements[I].Key = Key.get();
885 Elements[I].Value = Value.get();
886
887 if (Elements[I].EllipsisLoc.isInvalid())
888 continue;
889
890 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
891 !Elements[I].Value->containsUnexpandedParameterPack()) {
892 Diag(Elements[I].EllipsisLoc,
893 diag::err_pack_expansion_without_parameter_packs)
894 << SourceRange(Elements[I].Key->getLocStart(),
895 Elements[I].Value->getLocEnd());
896 return ExprError();
897 }
898
899 HasPackExpansions = true;
900 }
901
902
903 QualType Ty
904 = Context.getObjCObjectPointerType(
905 Context.getObjCInterfaceType(NSDictionaryDecl));
906 return MaybeBindToTemporary(
907 ObjCDictionaryLiteral::Create(Context,
908 llvm::makeArrayRef(Elements,
909 NumElements),
910 HasPackExpansions,
911 Ty,
912 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000913}
914
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000915ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +0000916 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +0000917 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +0000918 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +0000919 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +0000920 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +0000921 StrTy = Context.DependentTy;
922 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +0000923 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
924 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000925 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000926 diag::err_incomplete_type_objc_at_encode,
927 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000928 return ExprError();
929
Anders Carlsson315d2292009-06-07 18:45:35 +0000930 std::string Str;
931 Context.getObjCEncodingForType(EncodedType, Str);
932
933 // The type of @encode is the same as the type of the corresponding string,
934 // which is an array type.
935 StrTy = Context.CharTy;
936 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000937 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +0000938 StrTy.addConst();
939 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
940 ArrayType::Normal, 0);
941 }
Mike Stump11289f42009-09-09 15:08:12 +0000942
Douglas Gregorabd9e962010-04-20 15:39:42 +0000943 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +0000944}
945
John McCallfaf5fb42010-08-26 23:41:50 +0000946ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
947 SourceLocation EncodeLoc,
948 SourceLocation LParenLoc,
949 ParsedType ty,
950 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000951 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +0000952 TypeSourceInfo *TInfo;
953 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
954 if (!TInfo)
955 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
956 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000957
Douglas Gregorabd9e962010-04-20 15:39:42 +0000958 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000959}
960
John McCallfaf5fb42010-08-26 23:41:50 +0000961ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
962 SourceLocation AtLoc,
963 SourceLocation SelLoc,
964 SourceLocation LParenLoc,
Fariborz Jahanian02447d82013-01-22 18:35:43 +0000965 SourceLocation RParenLoc) {
966 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
967 SourceRange(LParenLoc, RParenLoc), false, false);
968 if (!Method)
969 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +0000970 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian02447d82013-01-22 18:35:43 +0000971 if (!Method)
972 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian9a881012011-07-13 19:05:43 +0000973
Fariborz Jahanian02447d82013-01-22 18:35:43 +0000974 if (!Method ||
975 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
976 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
977 = ReferencedSelectors.find(Sel);
978 if (Pos == ReferencedSelectors.end())
979 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian9a881012011-07-13 19:05:43 +0000980 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +0000981
Fariborz Jahanian02447d82013-01-22 18:35:43 +0000982 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +0000983 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000984 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +0000985 switch (Sel.getMethodFamily()) {
986 case OMF_retain:
987 case OMF_release:
988 case OMF_autorelease:
989 case OMF_retainCount:
990 case OMF_dealloc:
991 Diag(AtLoc, diag::err_arc_illegal_selector) <<
992 Sel << SourceRange(LParenLoc, RParenLoc);
993 break;
994
995 case OMF_None:
996 case OMF_alloc:
997 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +0000998 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000999 case OMF_init:
1000 case OMF_mutableCopy:
1001 case OMF_new:
1002 case OMF_self:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001003 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001004 break;
1005 }
1006 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001007 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001008 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001009}
1010
John McCallfaf5fb42010-08-26 23:41:50 +00001011ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1012 SourceLocation AtLoc,
1013 SourceLocation ProtoLoc,
1014 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001015 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001016 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001017 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001018 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001019 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001020 return true;
1021 }
Mike Stump11289f42009-09-09 15:08:12 +00001022
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001023 QualType Ty = Context.getObjCProtoType();
1024 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001025 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001026 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001027 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001028}
1029
John McCall5f2d5562011-02-03 09:00:02 +00001030/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001031ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1032 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001033
1034 // If we're not in an ObjC method, error out. Note that, unlike the
1035 // C++ case, we don't require an instance method --- class methods
1036 // still have a 'self', and we really do still need to capture it!
1037 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1038 if (!method)
1039 return 0;
1040
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001041 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001042
1043 return method;
1044}
1045
Douglas Gregor64910ca2011-09-09 20:05:21 +00001046static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1047 if (T == Context.getObjCInstanceType())
1048 return Context.getObjCIdType();
1049
1050 return T;
1051}
1052
Douglas Gregor33823722011-06-11 01:09:30 +00001053QualType Sema::getMessageSendResultType(QualType ReceiverType,
1054 ObjCMethodDecl *Method,
1055 bool isClassMessage, bool isSuperMessage) {
1056 assert(Method && "Must have a method");
1057 if (!Method->hasRelatedResultType())
1058 return Method->getSendResultType();
1059
1060 // If a method has a related return type:
1061 // - if the method found is an instance method, but the message send
1062 // was a class message send, T is the declared return type of the method
1063 // found
1064 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001065 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001066
1067 // - if the receiver is super, T is a pointer to the class of the
1068 // enclosing method definition
1069 if (isSuperMessage) {
1070 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1071 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1072 return Context.getObjCObjectPointerType(
1073 Context.getObjCInterfaceType(Class));
1074 }
1075
1076 // - if the receiver is the name of a class U, T is a pointer to U
1077 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1078 ReceiverType->isObjCQualifiedInterfaceType())
1079 return Context.getObjCObjectPointerType(ReceiverType);
1080 // - if the receiver is of type Class or qualified Class type,
1081 // T is the declared return type of the method.
1082 if (ReceiverType->isObjCClassType() ||
1083 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001084 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001085
1086 // - if the receiver is id, qualified id, Class, or qualified Class, T
1087 // is the receiver type, otherwise
1088 // - T is the type of the receiver expression.
1089 return ReceiverType;
1090}
John McCall5f2d5562011-02-03 09:00:02 +00001091
John McCall5ec7e7d2013-03-19 07:04:25 +00001092/// Look for an ObjC method whose result type exactly matches the given type.
1093static const ObjCMethodDecl *
1094findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1095 QualType instancetype) {
1096 if (MD->getResultType() == instancetype) return MD;
1097
1098 // For these purposes, a method in an @implementation overrides a
1099 // declaration in the @interface.
1100 if (const ObjCImplDecl *impl =
1101 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1102 const ObjCContainerDecl *iface;
1103 if (const ObjCCategoryImplDecl *catImpl =
1104 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1105 iface = catImpl->getCategoryDecl();
1106 } else {
1107 iface = impl->getClassInterface();
1108 }
1109
1110 const ObjCMethodDecl *ifaceMD =
1111 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1112 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1113 }
1114
1115 SmallVector<const ObjCMethodDecl *, 4> overrides;
1116 MD->getOverriddenMethods(overrides);
1117 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1118 if (const ObjCMethodDecl *result =
1119 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1120 return result;
1121 }
1122
1123 return 0;
1124}
1125
1126void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1127 // Only complain if we're in an ObjC method and the required return
1128 // type doesn't match the method's declared return type.
1129 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1130 if (!MD || !MD->hasRelatedResultType() ||
1131 Context.hasSameUnqualifiedType(destType, MD->getResultType()))
1132 return;
1133
1134 // Look for a method overridden by this method which explicitly uses
1135 // 'instancetype'.
1136 if (const ObjCMethodDecl *overridden =
1137 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1138 SourceLocation loc;
1139 SourceRange range;
1140 if (TypeSourceInfo *TSI = overridden->getResultTypeSourceInfo()) {
1141 range = TSI->getTypeLoc().getSourceRange();
1142 loc = range.getBegin();
1143 }
1144 if (loc.isInvalid())
1145 loc = overridden->getLocation();
1146 Diag(loc, diag::note_related_result_type_explicit)
1147 << /*current method*/ 1 << range;
1148 return;
1149 }
1150
1151 // Otherwise, if we have an interesting method family, note that.
1152 // This should always trigger if the above didn't.
1153 if (ObjCMethodFamily family = MD->getMethodFamily())
1154 Diag(MD->getLocation(), diag::note_related_result_type_family)
1155 << /*current method*/ 1
1156 << family;
1157}
1158
Douglas Gregor33823722011-06-11 01:09:30 +00001159void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1160 E = E->IgnoreParenImpCasts();
1161 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1162 if (!MsgSend)
1163 return;
1164
1165 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1166 if (!Method)
1167 return;
1168
1169 if (!Method->hasRelatedResultType())
1170 return;
1171
1172 if (Context.hasSameUnqualifiedType(Method->getResultType()
1173 .getNonReferenceType(),
1174 MsgSend->getType()))
1175 return;
1176
Douglas Gregorbab8a962011-09-08 01:46:34 +00001177 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
1178 Context.getObjCInstanceType()))
1179 return;
1180
Douglas Gregor33823722011-06-11 01:09:30 +00001181 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1182 << Method->isInstanceMethod() << Method->getSelector()
1183 << MsgSend->getType();
1184}
1185
1186bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001187 MultiExprArg Args,
1188 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001189 ArrayRef<SourceLocation> SelectorLocs,
1190 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001191 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001192 SourceLocation lbrac, SourceLocation rbrac,
John McCall7decc9e2010-11-18 06:31:45 +00001193 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001194 SourceLocation SelLoc;
1195 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1196 SelLoc = SelectorLocs.front();
1197 else
1198 SelLoc = lbrac;
1199
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001200 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001201 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001202 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001203 if (Args[i]->isTypeDependent())
1204 continue;
1205
John McCallcc5788c2013-03-04 07:34:02 +00001206 ExprResult result;
1207 if (getLangOpts().DebuggerSupport) {
1208 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001209 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001210 } else {
1211 result = DefaultArgumentPromotion(Args[i]);
1212 }
1213 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001214 return true;
John McCallcc5788c2013-03-04 07:34:02 +00001215 Args[i] = result.take();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001216 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001217
John McCall31168b02011-06-15 23:02:42 +00001218 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001219 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001220 DiagID = diag::err_arc_method_not_found;
1221 else
1222 DiagID = isClassMessage ? diag::warn_class_method_not_found
1223 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001224 if (!getLangOpts().DebuggerSupport) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001225 Diag(SelLoc, DiagID)
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001226 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
1227 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001228 // Find the class to which we are sending this message.
1229 if (ReceiverType->isObjCObjectPointerType()) {
1230 QualType ClassType =
1231 ReceiverType->getAs<ObjCObjectPointerType>()->getPointeeType();
1232 if (const ObjCObjectType *ClassTPtr = ClassType->getAs<ObjCObjectType>())
1233 if (ObjCInterfaceDecl *Class = ClassTPtr->getInterface())
1234 Diag(Class->getLocation(), diag::note_receiver_class_declared);
1235 }
1236 }
John McCall3f4138c2011-07-13 17:56:40 +00001237
1238 // In debuggers, we want to use __unknown_anytype for these
1239 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001240 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001241 ReturnType = Context.UnknownAnyTy;
1242 } else {
1243 ReturnType = Context.getObjCIdType();
1244 }
John McCall7decc9e2010-11-18 06:31:45 +00001245 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001246 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001247 }
Mike Stump11289f42009-09-09 15:08:12 +00001248
Douglas Gregor33823722011-06-11 01:09:30 +00001249 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1250 isSuperMessage);
John McCall7decc9e2010-11-18 06:31:45 +00001251 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump11289f42009-09-09 15:08:12 +00001252
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001253 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001254 // Method might have more arguments than selector indicates. This is due
1255 // to addition of c-style arguments in method.
1256 if (Method->param_size() > Sel.getNumArgs())
1257 NumNamedArgs = Method->param_size();
1258 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001259 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001260 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001261 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001262 return false;
1263 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001264
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001265 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001266 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001267 // We can't do any type-checking on a type-dependent argument.
1268 if (Args[i]->isTypeDependent())
1269 continue;
1270
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001271 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001272
John McCall4124c492011-10-17 18:40:02 +00001273 ParmVarDecl *param = Method->param_begin()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001274 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001275
John McCall4124c492011-10-17 18:40:02 +00001276 // Strip the unbridged-cast placeholder expression off unless it's
1277 // a consumed argument.
1278 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1279 !param->hasAttr<CFConsumedAttr>())
1280 argExpr = stripARCUnbridgedCast(argExpr);
1281
John McCallea0a39e2012-11-14 00:49:39 +00001282 // If the parameter is __unknown_anytype, infer its type
1283 // from the argument.
1284 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001285 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001286 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001287 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001288 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001289 } else {
1290 Args[i] = argE.take();
John McCallea0a39e2012-11-14 00:49:39 +00001291
John McCallcc5788c2013-03-04 07:34:02 +00001292 // Update the parameter type in-place.
1293 param->setType(paramType);
1294 }
1295 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001296 }
1297
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001298 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001299 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001300 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001301 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001302
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001303 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001304 param);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001305 ExprResult ArgE = PerformCopyInitialization(Entity, SelLoc, Owned(argExpr));
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001306 if (ArgE.isInvalid())
1307 IsError = true;
1308 else
1309 Args[i] = ArgE.takeAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001310 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001311
1312 // Promote additional arguments to variadic methods.
1313 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001314 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001315 if (Args[i]->isTypeDependent())
1316 continue;
1317
Jordy Roseaca01f92012-05-12 17:32:52 +00001318 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1319 0);
John Wiegley01296292011-04-08 18:41:53 +00001320 IsError |= Arg.isInvalid();
1321 Args[i] = Arg.take();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001322 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001323 } else {
1324 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001325 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001326 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001327 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001328 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001329 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001330 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001331 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001332 }
1333 }
1334
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001335 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001336
1337 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001338 IsError |= CheckObjCMethodCall(
1339 Method, SelLoc,
1340 llvm::makeArrayRef<const Expr *>(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001341
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001342 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001343}
1344
Douglas Gregor486b74e2011-09-27 16:10:05 +00001345bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001346 // 'self' is objc 'self' in an objc method only.
John McCallfe96e0b2011-11-06 09:01:30 +00001347 ObjCMethodDecl *method =
John McCalldec348f72013-05-03 07:33:41 +00001348 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
John McCallfe96e0b2011-11-06 09:01:30 +00001349 if (!method) return false;
1350
John McCall31168b02011-06-15 23:02:42 +00001351 receiver = receiver->IgnoreParenLValueCasts();
1352 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001353 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001354 return true;
1355 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001356}
1357
John McCall526ab472011-10-25 17:37:35 +00001358/// LookupMethodInType - Look up a method in an ObjCObjectType.
1359ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1360 bool isInstance) {
1361 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1362 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1363 // Look it up in the main interface (and categories, etc.)
1364 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1365 return method;
1366
1367 // Okay, look for "private" methods declared in any
1368 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001369 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1370 return method;
John McCall526ab472011-10-25 17:37:35 +00001371 }
1372
1373 // Check qualifiers.
1374 for (ObjCObjectType::qual_iterator
1375 i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
1376 if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
1377 return method;
1378
1379 return 0;
1380}
1381
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001382/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1383/// list of a qualified objective pointer type.
1384ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1385 const ObjCObjectPointerType *OPT,
1386 bool Instance)
1387{
1388 ObjCMethodDecl *MD = 0;
1389 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1390 E = OPT->qual_end(); I != E; ++I) {
1391 ObjCProtocolDecl *PROTO = (*I);
1392 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1393 return MD;
1394 }
1395 }
1396 return 0;
1397}
1398
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001399static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1400 if (!Receiver)
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001401 return;
1402
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001403 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1404 Receiver = OVE->getSourceExpr();
1405
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001406 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1407 SourceLocation Loc = RExpr->getLocStart();
1408 QualType T = RExpr->getType();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001409 const ObjCPropertyDecl *PDecl = 0;
1410 const ObjCMethodDecl *GDecl = 0;
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001411 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1412 RExpr = POE->getSyntacticForm();
1413 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1414 if (PRE->isImplicitProperty()) {
1415 GDecl = PRE->getImplicitPropertyGetter();
1416 if (GDecl) {
1417 T = GDecl->getResultType();
1418 }
1419 }
1420 else {
1421 PDecl = PRE->getExplicitProperty();
1422 if (PDecl) {
1423 T = PDecl->getType();
1424 }
1425 }
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001426 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001427 }
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001428 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1429 // See if receiver is a method which envokes a synthesized getter
1430 // backing a 'weak' property.
1431 ObjCMethodDecl *Method = ME->getMethodDecl();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001432 if (Method && Method->getSelector().getNumArgs() == 0) {
1433 PDecl = Method->findPropertyDecl();
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001434 if (PDecl)
1435 T = PDecl->getType();
1436 }
1437 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001438
Jordan Rose13d6b712012-09-28 22:21:42 +00001439 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1440 if (!PDecl)
1441 return;
1442 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1443 return;
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001444 }
Jordan Rose13d6b712012-09-28 22:21:42 +00001445
1446 S.Diag(Loc, diag::warn_receiver_is_weak)
1447 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1448
1449 if (PDecl)
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001450 S.Diag(PDecl->getLocation(), diag::note_property_declare);
Jordan Rose13d6b712012-09-28 22:21:42 +00001451 else if (GDecl)
1452 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1453
1454 S.Diag(Loc, diag::note_arc_assign_to_strong);
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001455}
1456
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001457/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1458/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001459ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001460HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001461 Expr *BaseExpr, SourceLocation OpLoc,
1462 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001463 SourceLocation MemberLoc,
1464 SourceLocation SuperLoc, QualType SuperType,
1465 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001466 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1467 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001468
Benjamin Kramer365082d2012-05-19 16:34:46 +00001469 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001470 Diag(MemberLoc, diag::err_invalid_property_name)
1471 << MemberName << QualType(OPT, 0);
1472 return ExprError();
1473 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001474
1475 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001476
Douglas Gregor4123a862011-11-14 22:10:01 +00001477 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1478 : BaseExpr->getSourceRange();
1479 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001480 diag::err_property_not_found_forward_class,
1481 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001482 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001483
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001484 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001485 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001486 // Check whether we can reference this property.
1487 if (DiagnoseUseOfDecl(PD, MemberLoc))
1488 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001489 if (Super)
John McCall526ab472011-10-25 17:37:35 +00001490 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001491 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001492 MemberLoc,
1493 SuperLoc, SuperType));
1494 else
John McCall526ab472011-10-25 17:37:35 +00001495 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001496 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001497 MemberLoc, BaseExpr));
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001498 }
1499 // Check protocols on qualified interfaces.
1500 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1501 E = OPT->qual_end(); I != E; ++I)
1502 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1503 // Check whether we can reference this property.
1504 if (DiagnoseUseOfDecl(PD, MemberLoc))
1505 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001506
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001507 if (Super)
John McCall526ab472011-10-25 17:37:35 +00001508 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1509 Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001510 VK_LValue,
1511 OK_ObjCProperty,
1512 MemberLoc,
1513 SuperLoc, SuperType));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001514 else
John McCall526ab472011-10-25 17:37:35 +00001515 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1516 Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001517 VK_LValue,
1518 OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001519 MemberLoc,
1520 BaseExpr));
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001521 }
1522 // If that failed, look for an "implicit" property by seeing if the nullary
1523 // selector is implemented.
1524
1525 // FIXME: The logic for looking up nullary and unary selectors should be
1526 // shared with the code in ActOnInstanceMessage.
1527
1528 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1529 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001530
1531 // May be founf in property's qualified list.
1532 if (!Getter)
1533 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001534
1535 // If this reference is in an @implementation, check for 'private' methods.
1536 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001537 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001538
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001539 if (Getter) {
1540 // Check if we can reference this property.
1541 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1542 return ExprError();
1543 }
1544 // If we found a getter then this may be a valid dot-reference, we
1545 // will look for the matching setter, in case it is needed.
1546 Selector SetterSel =
1547 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1548 PP.getSelectorTable(), Member);
1549 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001550
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001551 // May be founf in property's qualified list.
1552 if (!Setter)
1553 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1554
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001555 if (!Setter) {
1556 // If this reference is in an @implementation, also check for 'private'
1557 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001558 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001559 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001560
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001561 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1562 return ExprError();
1563
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001564 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001565 if (Super)
John McCallb7bd14f2010-12-02 01:19:52 +00001566 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001567 Context.PseudoObjectTy,
1568 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001569 MemberLoc,
1570 SuperLoc, SuperType));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001571 else
John McCallb7bd14f2010-12-02 01:19:52 +00001572 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001573 Context.PseudoObjectTy,
1574 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001575 MemberLoc, BaseExpr));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001576
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001577 }
1578
1579 // Attempt to correct for typos in property names.
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001580 DeclFilterCCC<ObjCPropertyDecl> Validator;
1581 if (TypoCorrection Corrected = CorrectTypo(
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001582 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001583 NULL, Validator, IFace, false, OPT)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001584 ObjCPropertyDecl *Property =
1585 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001586 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001587 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattner90c58fa2010-04-11 07:51:10 +00001588 << MemberName << QualType(OPT, 0) << TypoResult
1589 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001590 Diag(Property->getLocation(), diag::note_previous_decl)
1591 << Property->getDeclName();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001592 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1593 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001594 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001595 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001596 ObjCInterfaceDecl *ClassDeclared;
1597 if (ObjCIvarDecl *Ivar =
1598 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1599 QualType T = Ivar->getType();
1600 if (const ObjCObjectPointerType * OBJPT =
1601 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001602 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001603 diag::err_property_not_as_forward_class,
1604 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001605 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001606 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001607 Diag(MemberLoc,
1608 diag::err_ivar_access_using_property_syntax_suggest)
1609 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1610 << FixItHint::CreateReplacement(OpLoc, "->");
1611 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001612 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001613
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001614 Diag(MemberLoc, diag::err_property_not_found)
1615 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001616 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001617 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001618 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001619 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001620}
1621
1622
1623
John McCalldadc5752010-08-24 06:29:42 +00001624ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001625ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1626 IdentifierInfo &propertyName,
1627 SourceLocation receiverNameLoc,
1628 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001629
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001630 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001631 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1632 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001633
1634 bool IsSuper = false;
Chris Lattnera36ec422010-04-11 08:28:14 +00001635 if (IFace == 0) {
1636 // If the "receiver" is 'super' in a method, handle it as an expression-like
1637 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001638 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001639 IsSuper = true;
1640
Eli Friedman24af8502012-02-03 22:47:37 +00001641 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001642 if (CurMethod->isInstanceMethod()) {
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001643 ObjCInterfaceDecl *Super =
1644 CurMethod->getClassInterface()->getSuperClass();
1645 if (!Super) {
1646 // The current class does not have a superclass.
1647 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1648 << CurMethod->getClassInterface()->getIdentifier();
1649 return ExprError();
1650 }
1651 QualType T = Context.getObjCInterfaceType(Super);
Chris Lattnera36ec422010-04-11 08:28:14 +00001652 T = Context.getObjCObjectPointerType(T);
Chris Lattnera36ec422010-04-11 08:28:14 +00001653
1654 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001655 /*BaseExpr*/0,
1656 SourceLocation()/*OpLoc*/,
1657 &propertyName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001658 propertyNameLoc,
1659 receiverNameLoc, T, true);
Chris Lattnera36ec422010-04-11 08:28:14 +00001660 }
Mike Stump11289f42009-09-09 15:08:12 +00001661
Chris Lattnera36ec422010-04-11 08:28:14 +00001662 // Otherwise, if this is a class method, try dispatching to our
1663 // superclass.
1664 IFace = CurMethod->getClassInterface()->getSuperClass();
1665 }
John McCall5f2d5562011-02-03 09:00:02 +00001666 }
Chris Lattnera36ec422010-04-11 08:28:14 +00001667
1668 if (IFace == 0) {
1669 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1670 return ExprError();
1671 }
1672 }
1673
1674 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001675 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001676 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001677
1678 // If this reference is in an @implementation, check for 'private' methods.
1679 if (!Getter)
1680 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1681 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001682 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001683 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001684
1685 if (Getter) {
1686 // FIXME: refactor/share with ActOnMemberReference().
1687 // Check if we can reference this property.
1688 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1689 return ExprError();
1690 }
Mike Stump11289f42009-09-09 15:08:12 +00001691
Steve Naroff9527bbf2009-03-09 21:12:44 +00001692 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001693 Selector SetterSel =
1694 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Naroffc7597f82009-03-10 17:24:38 +00001695 PP.getSelectorTable(), &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001696
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001697 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001698 if (!Setter) {
1699 // If this reference is in an @implementation, also check for 'private'
1700 // methods.
1701 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1702 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001703 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001704 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001705 }
1706 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001707 if (!Setter)
1708 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001709
1710 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1711 return ExprError();
1712
1713 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001714 if (IsSuper)
1715 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001716 Context.PseudoObjectTy,
1717 VK_LValue, OK_ObjCProperty,
Douglas Gregor33823722011-06-11 01:09:30 +00001718 propertyNameLoc,
1719 receiverNameLoc,
1720 Context.getObjCInterfaceType(IFace)));
1721
John McCallb7bd14f2010-12-02 01:19:52 +00001722 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001723 Context.PseudoObjectTy,
1724 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001725 propertyNameLoc,
1726 receiverNameLoc, IFace));
Steve Naroff9527bbf2009-03-09 21:12:44 +00001727 }
1728 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1729 << &propertyName << Context.getObjCInterfaceType(IFace));
1730}
1731
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001732namespace {
1733
1734class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1735 public:
1736 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1737 // Determine whether "super" is acceptable in the current context.
1738 if (Method && Method->getClassInterface())
1739 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1740 }
1741
1742 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1743 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1744 candidate.isKeyword("super");
1745 }
1746};
1747
1748}
1749
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001750Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001751 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001752 SourceLocation NameLoc,
1753 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001754 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001755 ParsedType &ReceiverType) {
1756 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001757
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001758 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001759 // messaging super. If the identifier is "super" and there is a
1760 // trailing dot, it's an instance message.
1761 if (IsSuper && S->isInObjcMethodScope())
1762 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001763
1764 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1765 LookupName(Result, S);
1766
1767 switch (Result.getResultKind()) {
1768 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001769 // Normal name lookup didn't find anything. If we're in an
1770 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001771 // FIXME: This is a hack. Ivar lookup should be part of normal
1772 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001773 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001774 if (!Method->getClassInterface()) {
1775 // Fall back: let the parser try to parse it as an instance message.
1776 return ObjCInstanceMessage;
1777 }
1778
Douglas Gregorca7136b2010-04-19 20:09:36 +00001779 ObjCInterfaceDecl *ClassDeclared;
1780 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1781 ClassDeclared))
1782 return ObjCInstanceMessage;
1783 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001784
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001785 // Break out; we'll perform typo correction below.
1786 break;
1787
1788 case LookupResult::NotFoundInCurrentInstantiation:
1789 case LookupResult::FoundOverloaded:
1790 case LookupResult::FoundUnresolvedValue:
1791 case LookupResult::Ambiguous:
1792 Result.suppressDiagnostics();
1793 return ObjCInstanceMessage;
1794
1795 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001796 // If the identifier is a class or not, and there is a trailing dot,
1797 // it's an instance message.
1798 if (HasTrailingDot)
1799 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001800 // We found something. If it's a type, then we have a class
1801 // message. Otherwise, it's an instance message.
1802 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001803 QualType T;
1804 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1805 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001806 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001807 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001808 DiagnoseUseOfDecl(Type, NameLoc);
1809 }
1810 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001811 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001812
Douglas Gregore5798dc2010-04-21 20:38:13 +00001813 // We have a class message, and T is the type we're
1814 // messaging. Build source-location information for it.
1815 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001816 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001817 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001818 }
1819 }
1820
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001821 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001822 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1823 Result.getLookupKind(), S, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001824 Validator)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001825 if (Corrected.isKeyword()) {
1826 // If we've found the keyword "super" (the only keyword that would be
1827 // returned by CorrectTypo), this is a send to super.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001828 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001829 << Name << Corrected.getCorrection()
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001830 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001831 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001832 } else if (ObjCInterfaceDecl *Class =
1833 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1834 // If we found a declaration, correct when it refers to an Objective-C
1835 // class.
1836 Diag(NameLoc, diag::err_unknown_receiver_suggest)
1837 << Name << Corrected.getCorrection()
1838 << FixItHint::CreateReplacement(SourceRange(NameLoc),
1839 Class->getNameAsString());
1840 Diag(Class->getLocation(), diag::note_previous_decl)
1841 << Corrected.getCorrection();
1842
1843 QualType T = Context.getObjCInterfaceType(Class);
1844 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1845 ReceiverType = CreateParsedType(T, TSInfo);
1846 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001847 }
1848 }
1849
1850 // Fall back: let the parser try to parse it as an instance message.
1851 return ObjCInstanceMessage;
1852}
Steve Naroff9527bbf2009-03-09 21:12:44 +00001853
John McCalldadc5752010-08-24 06:29:42 +00001854ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001855 SourceLocation SuperLoc,
1856 Selector Sel,
1857 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00001858 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001859 SourceLocation RBracLoc,
1860 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001861 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00001862 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00001863 if (!Method) {
1864 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1865 return ExprError();
1866 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001867
Douglas Gregor4fdba132010-04-21 20:01:04 +00001868 ObjCInterfaceDecl *Class = Method->getClassInterface();
1869 if (!Class) {
1870 Diag(SuperLoc, diag::error_no_super_class_message)
1871 << Method->getDeclName();
1872 return ExprError();
1873 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001874
Douglas Gregor4fdba132010-04-21 20:01:04 +00001875 ObjCInterfaceDecl *Super = Class->getSuperClass();
1876 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001877 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00001878 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1879 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001880 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00001881 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001882
Douglas Gregor4fdba132010-04-21 20:01:04 +00001883 // We are in a method whose class has a superclass, so 'super'
1884 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00001885 if (Method->getSelector() == Sel)
1886 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00001887
Jordan Rose2afd6612012-10-19 16:05:26 +00001888 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00001889 // Since we are in an instance method, this is an instance
1890 // message to the superclass instance.
1891 QualType SuperTy = Context.getObjCInterfaceType(Super);
1892 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCallb268a282010-08-23 23:25:46 +00001893 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001894 Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001895 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001896 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00001897
1898 // Since we are in a class method, this is a class message to
1899 // the superclass.
1900 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1901 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001902 SuperLoc, Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001903 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001904}
1905
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001906
1907ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1908 bool isSuperReceiver,
1909 SourceLocation Loc,
1910 Selector Sel,
1911 ObjCMethodDecl *Method,
1912 MultiExprArg Args) {
1913 TypeSourceInfo *receiverTypeInfo = 0;
1914 if (!ReceiverType.isNull())
1915 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1916
1917 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1918 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1919 Sel, Method, Loc, Loc, Loc, Args,
1920 /*isImplicit=*/true);
1921
1922}
1923
Ted Kremeneke65b0862012-03-06 20:05:56 +00001924static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1925 unsigned DiagID,
1926 bool (*refactor)(const ObjCMessageExpr *,
1927 const NSAPI &, edit::Commit &)) {
1928 SourceLocation MsgLoc = Msg->getExprLoc();
1929 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
1930 return;
1931
1932 SourceManager &SM = S.SourceMgr;
1933 edit::Commit ECommit(SM, S.LangOpts);
1934 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1935 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1936 << Msg->getSelector() << Msg->getSourceRange();
1937 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1938 if (!ECommit.isCommitable())
1939 return;
1940 for (edit::Commit::edit_iterator
1941 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1942 const edit::Commit::Edit &Edit = *I;
1943 switch (Edit.Kind) {
1944 case edit::Commit::Act_Insert:
1945 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1946 Edit.Text,
1947 Edit.BeforePrev));
1948 break;
1949 case edit::Commit::Act_InsertFromRange:
1950 Builder.AddFixItHint(
1951 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1952 Edit.getInsertFromRange(SM),
1953 Edit.BeforePrev));
1954 break;
1955 case edit::Commit::Act_Remove:
1956 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1957 break;
1958 }
1959 }
1960 }
1961}
1962
1963static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1964 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1965 edit::rewriteObjCRedundantCallWithLiteral);
1966}
1967
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001968/// \brief Build an Objective-C class message expression.
1969///
1970/// This routine takes care of both normal class messages and
1971/// class messages to the superclass.
1972///
1973/// \param ReceiverTypeInfo Type source information that describes the
1974/// receiver of this message. This may be NULL, in which case we are
1975/// sending to the superclass and \p SuperLoc must be a valid source
1976/// location.
1977
1978/// \param ReceiverType The type of the object receiving the
1979/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1980/// type as that refers to. For a superclass send, this is the type of
1981/// the superclass.
1982///
1983/// \param SuperLoc The location of the "super" keyword in a
1984/// superclass message.
1985///
1986/// \param Sel The selector to which the message is being sent.
1987///
Douglas Gregorb5186b12010-04-22 17:01:48 +00001988/// \param Method The method that this class message is invoking, if
1989/// already known.
1990///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001991/// \param LBracLoc The location of the opening square bracket ']'.
1992///
James Dennettffad8b72012-06-22 08:10:18 +00001993/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001994///
James Dennettffad8b72012-06-22 08:10:18 +00001995/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00001996ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001997 QualType ReceiverType,
1998 SourceLocation SuperLoc,
1999 Selector Sel,
2000 ObjCMethodDecl *Method,
2001 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002002 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002003 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002004 MultiExprArg ArgsIn,
2005 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002006 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002007 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002008 if (LBracLoc.isInvalid()) {
2009 Diag(Loc, diag::err_missing_open_square_message_send)
2010 << FixItHint::CreateInsertion(Loc, "[");
2011 LBracLoc = Loc;
2012 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002013 SourceLocation SelLoc;
2014 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2015 SelLoc = SelectorLocs.front();
2016 else
2017 SelLoc = Loc;
2018
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002019 if (ReceiverType->isDependentType()) {
2020 // If the receiver type is dependent, we can't type-check anything
2021 // at this point. Build a dependent expression.
2022 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002023 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002024 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCall7decc9e2010-11-18 06:31:45 +00002025 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
2026 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002027 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002028 makeArrayRef(Args, NumArgs),RBracLoc,
2029 isImplicit));
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002030 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002031
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002032 // Find the class to which we are sending this message.
2033 ObjCInterfaceDecl *Class = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002034 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2035 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002036 Diag(Loc, diag::err_invalid_receiver_class_message)
2037 << ReceiverType;
2038 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002039 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002040 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002041 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002042 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002043 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002044 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002045 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002046 SourceRange TypeRange
2047 = SuperLoc.isValid()? SourceRange(SuperLoc)
2048 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002049 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002050 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002051 ? diag::err_arc_receiver_forward_class
2052 : diag::warn_receiver_forward_class),
2053 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002054 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002055 Method = LookupFactoryMethodInGlobalPool(Sel,
2056 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002057 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002058 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2059 << Method->getDeclName();
2060 }
2061 if (!Method)
2062 Method = Class->lookupClassMethod(Sel);
2063
2064 // If we have an implementation in scope, check "private" methods.
2065 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002066 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002067
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002068 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002069 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002070 }
Mike Stump11289f42009-09-09 15:08:12 +00002071
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002072 // Check the argument types and determine the result type.
2073 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002074 ExprValueKind VK = VK_RValue;
2075
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002076 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002077 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002078 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2079 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002080 Method, true,
Douglas Gregor33823722011-06-11 01:09:30 +00002081 SuperLoc.isValid(), LBracLoc, RBracLoc,
2082 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002083 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002084
Douglas Gregoraec93c62011-01-11 03:23:19 +00002085 if (Method && !Method->getResultType()->isVoidType() &&
2086 RequireCompleteType(LBracLoc, Method->getResultType(),
2087 diag::err_illegal_message_expr_incomplete_type))
2088 return ExprError();
2089
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002090 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002091 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002092 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002093 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002094 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002095 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002096 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002097 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002098 else {
John McCall7decc9e2010-11-18 06:31:45 +00002099 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002100 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002101 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002102 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002103 if (!isImplicit)
2104 checkCocoaAPI(*this, Result);
2105 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002106 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002107}
2108
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002109// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002110// ArgExprs is optional - if it is present, the number of expressions
2111// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002112ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002113 ParsedType Receiver,
2114 Selector Sel,
2115 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002116 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002117 SourceLocation RBracLoc,
2118 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002119 TypeSourceInfo *ReceiverTypeInfo;
2120 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2121 if (ReceiverType.isNull())
2122 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002123
Mike Stump11289f42009-09-09 15:08:12 +00002124
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002125 if (!ReceiverTypeInfo)
2126 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2127
2128 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorb5186b12010-04-22 17:01:48 +00002129 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002130 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002131}
2132
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002133ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2134 QualType ReceiverType,
2135 SourceLocation Loc,
2136 Selector Sel,
2137 ObjCMethodDecl *Method,
2138 MultiExprArg Args) {
2139 return BuildInstanceMessage(Receiver, ReceiverType,
2140 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2141 Sel, Method, Loc, Loc, Loc, Args,
2142 /*isImplicit=*/true);
2143}
2144
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002145/// \brief Build an Objective-C instance message expression.
2146///
2147/// This routine takes care of both normal instance messages and
2148/// instance messages to the superclass instance.
2149///
2150/// \param Receiver The expression that computes the object that will
2151/// receive this message. This may be empty, in which case we are
2152/// sending to the superclass instance and \p SuperLoc must be a valid
2153/// source location.
2154///
2155/// \param ReceiverType The (static) type of the object receiving the
2156/// message. When a \p Receiver expression is provided, this is the
2157/// same type as that expression. For a superclass instance send, this
2158/// is a pointer to the type of the superclass.
2159///
2160/// \param SuperLoc The location of the "super" keyword in a
2161/// superclass instance message.
2162///
2163/// \param Sel The selector to which the message is being sent.
2164///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002165/// \param Method The method that this instance message is invoking, if
2166/// already known.
2167///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002168/// \param LBracLoc The location of the opening square bracket ']'.
2169///
James Dennettffad8b72012-06-22 08:10:18 +00002170/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002171///
James Dennettffad8b72012-06-22 08:10:18 +00002172/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002173ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002174 QualType ReceiverType,
2175 SourceLocation SuperLoc,
2176 Selector Sel,
2177 ObjCMethodDecl *Method,
2178 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002179 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002180 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002181 MultiExprArg ArgsIn,
2182 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002183 // The location of the receiver.
2184 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002185 SourceRange RecRange =
2186 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2187 SourceLocation SelLoc;
2188 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2189 SelLoc = SelectorLocs.front();
2190 else
2191 SelLoc = Loc;
2192
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002193 if (LBracLoc.isInvalid()) {
2194 Diag(Loc, diag::err_missing_open_square_message_send)
2195 << FixItHint::CreateInsertion(Loc, "[");
2196 LBracLoc = Loc;
2197 }
2198
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002199 // If we have a receiver expression, perform appropriate promotions
2200 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002201 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002202 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002203 ExprResult Result;
2204 if (Receiver->getType() == Context.UnknownAnyTy)
2205 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2206 else
2207 Result = CheckPlaceholderExpr(Receiver);
2208 if (Result.isInvalid()) return ExprError();
2209 Receiver = Result.take();
John McCall4124c492011-10-17 18:40:02 +00002210 }
2211
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002212 if (Receiver->isTypeDependent()) {
2213 // If the receiver is type-dependent, we can't type-check anything
2214 // at this point. Build a dependent expression.
2215 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002216 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002217 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2218 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00002219 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002220 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002221 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002222 RBracLoc, isImplicit));
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002223 }
2224
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002225 // If necessary, apply function/array conversion to the receiver.
2226 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002227 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2228 if (Result.isInvalid())
2229 return ExprError();
2230 Receiver = Result.take();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002231 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002232
2233 // If the receiver is an ObjC pointer, a block pointer, or an
2234 // __attribute__((NSObject)) pointer, we don't need to do any
2235 // special conversion in order to look up a receiver.
2236 if (ReceiverType->isObjCRetainableType()) {
2237 // do nothing
2238 } else if (!getLangOpts().ObjCAutoRefCount &&
2239 !Context.getObjCIdType().isNull() &&
2240 (ReceiverType->isPointerType() ||
2241 ReceiverType->isIntegerType())) {
2242 // Implicitly convert integers and pointers to 'id' but emit a warning.
2243 // But not in ARC.
2244 Diag(Loc, diag::warn_bad_receiver_type)
2245 << ReceiverType
2246 << Receiver->getSourceRange();
2247 if (ReceiverType->isPointerType()) {
2248 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2249 CK_CPointerToObjCPointerCast).take();
2250 } else {
2251 // TODO: specialized warning on null receivers?
2252 bool IsNull = Receiver->isNullPointerConstant(Context,
2253 Expr::NPC_ValueDependentIsNull);
2254 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2255 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2256 Kind).take();
2257 }
2258 ReceiverType = Receiver->getType();
2259 } else if (getLangOpts().CPlusPlus) {
2260 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2261 if (result.isUsable()) {
2262 Receiver = result.take();
2263 ReceiverType = Receiver->getType();
2264 }
2265 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002266 }
2267
John McCall80c93a02013-03-01 09:20:14 +00002268 // There's a somewhat weird interaction here where we assume that we
2269 // won't actually have a method unless we also don't need to do some
2270 // of the more detailed type-checking on the receiver.
2271
Douglas Gregorb5186b12010-04-22 17:01:48 +00002272 if (!Method) {
2273 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002274 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002275 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002276 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2277 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002278 SourceRange(LBracLoc, RBracLoc),
2279 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002280 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002281 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002282 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002283 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002284 } else if (ReceiverType->isObjCClassType() ||
2285 ReceiverType->isObjCQualifiedClassType()) {
2286 // Handle messages to Class.
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002287 // We allow sending a message to a qualified Class ("Class<foo>"), which
2288 // is ok as long as one of the protocols implements the selector (if not, warn).
2289 if (const ObjCObjectPointerType *QClassTy
2290 = ReceiverType->getAsObjCQualifiedClassType()) {
2291 // Search protocols for class methods.
2292 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2293 if (!Method) {
2294 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2295 // warn if instance method found for a Class message.
2296 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002297 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002298 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002299 Diag(Method->getLocation(), diag::note_method_declared_at)
2300 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002301 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002302 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002303 } else {
2304 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2305 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2306 // First check the public methods in the class interface.
2307 Method = ClassDecl->lookupClassMethod(Sel);
2308
2309 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002310 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002311 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002312 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002313 return ExprError();
2314 }
2315 if (!Method) {
2316 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002317 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002318 Method = LookupFactoryMethodInGlobalPool(Sel,
2319 SourceRange(LBracLoc, RBracLoc),
2320 true);
2321 if (!Method) {
2322 // If no class (factory) method was found, check if an _instance_
2323 // method of the same name exists in the root class only.
2324 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002325 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002326 true);
2327 if (Method)
2328 if (const ObjCInterfaceDecl *ID =
2329 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2330 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002331 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002332 << Sel << SourceRange(LBracLoc, RBracLoc);
2333 }
2334 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002335 }
2336 }
2337 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002338 } else {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002339 ObjCInterfaceDecl* ClassDecl = 0;
2340
2341 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2342 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002343 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002344 if (const ObjCObjectPointerType *QIdTy
2345 = ReceiverType->getAsObjCQualifiedIdType()) {
2346 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002347 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2348 if (!Method)
2349 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002350 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002351 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002352 } else if (const ObjCObjectPointerType *OCIType
2353 = ReceiverType->getAsObjCInterfacePointerType()) {
2354 // We allow sending a message to a pointer to an interface (an object).
2355 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002356
Douglas Gregor4123a862011-11-14 22:10:01 +00002357 // Try to complete the type. Under ARC, this is a hard error from which
2358 // we don't try to recover.
2359 const ObjCInterfaceDecl *forwardClass = 0;
2360 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002361 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002362 ? diag::err_arc_receiver_forward_instance
2363 : diag::warn_receiver_forward_instance,
2364 Receiver? Receiver->getSourceRange()
2365 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002366 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002367 return ExprError();
2368
2369 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002370 Diag(Receiver ? Receiver->getLocStart()
2371 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002372 Method = 0;
2373 } else {
2374 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002375 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002376
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002377 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002378 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002379 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2380
Douglas Gregorb5186b12010-04-22 17:01:48 +00002381 if (!Method) {
2382 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002383 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002384
David Blaikiebbafb8a2012-03-11 07:00:24 +00002385 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002386 Diag(SelLoc, diag::err_arc_may_not_respond)
2387 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002388 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002389 return ExprError();
2390 }
2391
Douglas Gregor486b74e2011-09-27 16:10:05 +00002392 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002393 // If we still haven't found a method, look in the global pool. This
2394 // behavior isn't very desirable, however we need it for GCC
2395 // compatibility. FIXME: should we deviate??
2396 if (OCIType->qual_empty()) {
2397 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002398 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002399 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002400 Diag(SelLoc, diag::warn_maynot_respond)
2401 << OCIType->getInterfaceDecl()->getIdentifier()
2402 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002403 }
2404 }
2405 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002406 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002407 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002408 } else {
John McCall80c93a02013-03-01 09:20:14 +00002409 // Reject other random receiver types (e.g. structs).
2410 Diag(Loc, diag::err_bad_receiver_type)
2411 << ReceiverType << Receiver->getSourceRange();
2412 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002413 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002414 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002415 }
Mike Stump11289f42009-09-09 15:08:12 +00002416
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002417 // Check the message arguments.
2418 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002419 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002420 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002421 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002422 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2423 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002424 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2425 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002426 ClassMessage, SuperLoc.isValid(),
John McCall7decc9e2010-11-18 06:31:45 +00002427 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002428 return ExprError();
Fariborz Jahanian18e02752010-06-16 19:56:08 +00002429
Douglas Gregoraec93c62011-01-11 03:23:19 +00002430 if (Method && !Method->getResultType()->isVoidType() &&
2431 RequireCompleteType(LBracLoc, Method->getResultType(),
2432 diag::err_illegal_message_expr_incomplete_type))
2433 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002434
John McCall31168b02011-06-15 23:02:42 +00002435 // In ARC, forbid the user from sending messages to
2436 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002437 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002438 ObjCMethodFamily family =
2439 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2440 switch (family) {
2441 case OMF_init:
2442 if (Method)
2443 checkInitMethod(Method, ReceiverType);
2444
2445 case OMF_None:
2446 case OMF_alloc:
2447 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002448 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002449 case OMF_mutableCopy:
2450 case OMF_new:
2451 case OMF_self:
2452 break;
2453
2454 case OMF_dealloc:
2455 case OMF_retain:
2456 case OMF_release:
2457 case OMF_autorelease:
2458 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002459 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2460 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002461 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002462
2463 case OMF_performSelector:
2464 if (Method && NumArgs >= 1) {
2465 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2466 Selector ArgSel = SelExp->getSelector();
2467 ObjCMethodDecl *SelMethod =
2468 LookupInstanceMethodInGlobalPool(ArgSel,
2469 SelExp->getSourceRange());
2470 if (!SelMethod)
2471 SelMethod =
2472 LookupFactoryMethodInGlobalPool(ArgSel,
2473 SelExp->getSourceRange());
2474 if (SelMethod) {
2475 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2476 switch (SelFamily) {
2477 case OMF_alloc:
2478 case OMF_copy:
2479 case OMF_mutableCopy:
2480 case OMF_new:
2481 case OMF_self:
2482 case OMF_init:
2483 // Issue error, unless ns_returns_not_retained.
2484 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2485 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002486 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002487 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002488 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2489 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002490 }
2491 break;
2492 default:
2493 // +0 call. OK. unless ns_returns_retained.
2494 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2495 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002496 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002497 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002498 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2499 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002500 }
2501 break;
2502 }
2503 }
2504 } else {
2505 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002506 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002507 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2508 }
2509 }
2510 break;
John McCall31168b02011-06-15 23:02:42 +00002511 }
2512 }
2513
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002514 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002515 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002516 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002517 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002518 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002519 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002520 makeArrayRef(Args, NumArgs), RBracLoc,
2521 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002522 else {
John McCall7decc9e2010-11-18 06:31:45 +00002523 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002524 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002525 makeArrayRef(Args, NumArgs), RBracLoc,
2526 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002527 if (!isImplicit)
2528 checkCocoaAPI(*this, Result);
2529 }
John McCall31168b02011-06-15 23:02:42 +00002530
David Blaikiebbafb8a2012-03-11 07:00:24 +00002531 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahaniand155c782012-04-19 23:49:39 +00002532 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian6bd22262012-04-04 20:05:25 +00002533
John McCall31168b02011-06-15 23:02:42 +00002534 // In ARC, annotate delegate init calls.
2535 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002536 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002537 // Only consider init calls *directly* in init implementations,
2538 // not within blocks.
2539 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2540 if (method && method->getMethodFamily() == OMF_init) {
2541 // The implicit assignment to self means we also don't want to
2542 // consume the result.
2543 Result->setDelegateInitCall(true);
2544 return Owned(Result);
2545 }
2546 }
2547
2548 // In ARC, check for message sends which are likely to introduce
2549 // retain cycles.
2550 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002551
2552 if (!isImplicit && Method) {
2553 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2554 bool IsWeak =
2555 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2556 if (!IsWeak && Sel.isUnarySelector())
2557 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
2558
2559 if (IsWeak) {
2560 DiagnosticsEngine::Level Level =
2561 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
2562 LBracLoc);
2563 if (Level != DiagnosticsEngine::Ignored)
2564 getCurFunction()->recordUseOfWeak(Result, Prop);
2565
2566 }
2567 }
2568 }
John McCall31168b02011-06-15 23:02:42 +00002569 }
2570
Douglas Gregoraae38d62010-05-22 05:17:18 +00002571 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002572}
2573
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002574static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2575 if (ObjCSelectorExpr *OSE =
2576 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2577 Selector Sel = OSE->getSelector();
2578 SourceLocation Loc = OSE->getAtLoc();
2579 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2580 = S.ReferencedSelectors.find(Sel);
2581 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2582 S.ReferencedSelectors.erase(Pos);
2583 }
2584}
2585
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002586// ActOnInstanceMessage - used for both unary and keyword messages.
2587// ArgExprs is optional - if it is present, the number of expressions
2588// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002589ExprResult Sema::ActOnInstanceMessage(Scope *S,
2590 Expr *Receiver,
2591 Selector Sel,
2592 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002593 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002594 SourceLocation RBracLoc,
2595 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002596 if (!Receiver)
2597 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002598
2599 // A ParenListExpr can show up while doing error recovery with invalid code.
2600 if (isa<ParenListExpr>(Receiver)) {
2601 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2602 if (Result.isInvalid()) return ExprError();
2603 Receiver = Result.take();
2604 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002605
2606 if (RespondsToSelectorSel.isNull()) {
2607 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2608 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2609 }
2610 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002611 RemoveSelectorFromWarningCache(*this, Args[0]);
2612
John McCallb268a282010-08-23 23:25:46 +00002613 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorb5186b12010-04-22 17:01:48 +00002614 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002615 LBracLoc, SelectorLocs, RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002616}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002617
John McCall31168b02011-06-15 23:02:42 +00002618enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002619 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002620 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002621
2622 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002623 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002624
2625 /// id*, id***, void (^*)(),
2626 ACTC_indirectRetainable,
2627
2628 /// void* might be a normal C type, or it might a CF type.
2629 ACTC_voidPtr,
2630
2631 /// struct A*
2632 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002633};
John McCalle4fe2452011-10-01 01:01:08 +00002634static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2635 return (ACTC == ACTC_retainable ||
2636 ACTC == ACTC_coreFoundation ||
2637 ACTC == ACTC_voidPtr);
2638}
2639static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2640 return ACTC == ACTC_none ||
2641 ACTC == ACTC_voidPtr ||
2642 ACTC == ACTC_coreFoundation;
2643}
2644
John McCall31168b02011-06-15 23:02:42 +00002645static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002646 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002647
2648 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002649 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002650 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002651 isIndirect = true;
2652 }
John McCall31168b02011-06-15 23:02:42 +00002653
2654 // Drill through pointers and arrays recursively.
2655 while (true) {
2656 if (const PointerType *ptr = type->getAs<PointerType>()) {
2657 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002658
2659 // The first level of pointer may be the innermost pointer on a CF type.
2660 if (!isIndirect) {
2661 if (type->isVoidType()) return ACTC_voidPtr;
2662 if (type->isRecordType()) return ACTC_coreFoundation;
2663 }
John McCall31168b02011-06-15 23:02:42 +00002664 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2665 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2666 } else {
2667 break;
2668 }
John McCalle4fe2452011-10-01 01:01:08 +00002669 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002670 }
2671
John McCalle4fe2452011-10-01 01:01:08 +00002672 if (isIndirect) {
2673 if (type->isObjCARCBridgableType())
2674 return ACTC_indirectRetainable;
2675 return ACTC_none;
2676 }
2677
2678 if (type->isObjCARCBridgableType())
2679 return ACTC_retainable;
2680
2681 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002682}
2683
2684namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002685 /// A result from the cast checker.
2686 enum ACCResult {
2687 /// Cannot be casted.
2688 ACC_invalid,
2689
2690 /// Can be safely retained or not retained.
2691 ACC_bottom,
2692
2693 /// Can be casted at +0.
2694 ACC_plusZero,
2695
2696 /// Can be casted at +1.
2697 ACC_plusOne
2698 };
2699 ACCResult merge(ACCResult left, ACCResult right) {
2700 if (left == right) return left;
2701 if (left == ACC_bottom) return right;
2702 if (right == ACC_bottom) return left;
2703 return ACC_invalid;
2704 }
2705
2706 /// A checker which white-lists certain expressions whose conversion
2707 /// to or from retainable type would otherwise be forbidden in ARC.
2708 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2709 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2710
John McCall31168b02011-06-15 23:02:42 +00002711 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002712 ARCConversionTypeClass SourceClass;
2713 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002714 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002715
2716 static bool isCFType(QualType type) {
2717 // Someday this can use ns_bridged. For now, it has to do this.
2718 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002719 }
John McCalle4fe2452011-10-01 01:01:08 +00002720
2721 public:
2722 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002723 ARCConversionTypeClass target, bool diagnose)
2724 : Context(Context), SourceClass(source), TargetClass(target),
2725 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00002726
2727 using super::Visit;
2728 ACCResult Visit(Expr *e) {
2729 return super::Visit(e->IgnoreParens());
2730 }
2731
2732 ACCResult VisitStmt(Stmt *s) {
2733 return ACC_invalid;
2734 }
2735
2736 /// Null pointer constants can be casted however you please.
2737 ACCResult VisitExpr(Expr *e) {
2738 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2739 return ACC_bottom;
2740 return ACC_invalid;
2741 }
2742
2743 /// Objective-C string literals can be safely casted.
2744 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2745 // If we're casting to any retainable type, go ahead. Global
2746 // strings are immune to retains, so this is bottom.
2747 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2748
2749 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002750 }
2751
John McCalle4fe2452011-10-01 01:01:08 +00002752 /// Look through certain implicit and explicit casts.
2753 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002754 switch (e->getCastKind()) {
2755 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00002756 return ACC_bottom;
2757
John McCall31168b02011-06-15 23:02:42 +00002758 case CK_NoOp:
2759 case CK_LValueToRValue:
2760 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002761 case CK_CPointerToObjCPointerCast:
2762 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002763 case CK_AnyPointerToBlockPointerCast:
2764 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00002765
John McCall31168b02011-06-15 23:02:42 +00002766 default:
John McCalle4fe2452011-10-01 01:01:08 +00002767 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002768 }
2769 }
John McCalle4fe2452011-10-01 01:01:08 +00002770
2771 /// Look through unary extension.
2772 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002773 return Visit(e->getSubExpr());
2774 }
John McCalle4fe2452011-10-01 01:01:08 +00002775
2776 /// Ignore the LHS of a comma operator.
2777 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002778 return Visit(e->getRHS());
2779 }
John McCalle4fe2452011-10-01 01:01:08 +00002780
2781 /// Conditional operators are okay if both sides are okay.
2782 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2783 ACCResult left = Visit(e->getTrueExpr());
2784 if (left == ACC_invalid) return ACC_invalid;
2785 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00002786 }
John McCalle4fe2452011-10-01 01:01:08 +00002787
John McCallfe96e0b2011-11-06 09:01:30 +00002788 /// Look through pseudo-objects.
2789 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2790 // If we're getting here, we should always have a result.
2791 return Visit(e->getResultExpr());
2792 }
2793
John McCalle4fe2452011-10-01 01:01:08 +00002794 /// Statement expressions are okay if their result expression is okay.
2795 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002796 return Visit(e->getSubStmt()->body_back());
2797 }
John McCall31168b02011-06-15 23:02:42 +00002798
John McCalle4fe2452011-10-01 01:01:08 +00002799 /// Some declaration references are okay.
2800 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2801 // References to global constants from system headers are okay.
2802 // These are things like 'kCFStringTransformToLatin'. They are
2803 // can also be assumed to be immune to retains.
2804 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2805 if (isAnyRetainable(TargetClass) &&
2806 isAnyRetainable(SourceClass) &&
2807 var &&
2808 var->getStorageClass() == SC_Extern &&
2809 var->getType().isConstQualified() &&
2810 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2811 return ACC_bottom;
2812 }
2813
2814 // Nothing else.
2815 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00002816 }
John McCalle4fe2452011-10-01 01:01:08 +00002817
2818 /// Some calls are okay.
2819 ACCResult VisitCallExpr(CallExpr *e) {
2820 if (FunctionDecl *fn = e->getDirectCallee())
2821 if (ACCResult result = checkCallToFunction(fn))
2822 return result;
2823
2824 return super::VisitCallExpr(e);
2825 }
2826
2827 ACCResult checkCallToFunction(FunctionDecl *fn) {
2828 // Require a CF*Ref return type.
2829 if (!isCFType(fn->getResultType()))
2830 return ACC_invalid;
2831
2832 if (!isAnyRetainable(TargetClass))
2833 return ACC_invalid;
2834
2835 // Honor an explicit 'not retained' attribute.
2836 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2837 return ACC_plusZero;
2838
2839 // Honor an explicit 'retained' attribute, except that for
2840 // now we're not going to permit implicit handling of +1 results,
2841 // because it's a bit frightening.
2842 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00002843 return Diagnose ? ACC_plusOne
2844 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00002845
2846 // Recognize this specific builtin function, which is used by CFSTR.
2847 unsigned builtinID = fn->getBuiltinID();
2848 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2849 return ACC_bottom;
2850
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00002851 // Otherwise, don't do anything implicit with an unaudited function.
2852 if (!fn->hasAttr<CFAuditedTransferAttr>())
2853 return ACC_invalid;
2854
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002855 // Otherwise, it's +0 unless it follows the create convention.
2856 if (ento::coreFoundation::followsCreateRule(fn))
2857 return Diagnose ? ACC_plusOne
2858 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00002859
John McCalle4fe2452011-10-01 01:01:08 +00002860 return ACC_plusZero;
2861 }
2862
2863 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2864 return checkCallToMethod(e->getMethodDecl());
2865 }
2866
2867 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2868 ObjCMethodDecl *method;
2869 if (e->isExplicitProperty())
2870 method = e->getExplicitProperty()->getGetterMethodDecl();
2871 else
2872 method = e->getImplicitPropertyGetter();
2873 return checkCallToMethod(method);
2874 }
2875
2876 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2877 if (!method) return ACC_invalid;
2878
2879 // Check for message sends to functions returning CF types. We
2880 // just obey the Cocoa conventions with these, even though the
2881 // return type is CF.
2882 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2883 return ACC_invalid;
2884
2885 // If the method is explicitly marked not-retained, it's +0.
2886 if (method->hasAttr<CFReturnsNotRetainedAttr>())
2887 return ACC_plusZero;
2888
2889 // If the method is explicitly marked as returning retained, or its
2890 // selector follows a +1 Cocoa convention, treat it as +1.
2891 if (method->hasAttr<CFReturnsRetainedAttr>())
2892 return ACC_plusOne;
2893
2894 switch (method->getSelector().getMethodFamily()) {
2895 case OMF_alloc:
2896 case OMF_copy:
2897 case OMF_mutableCopy:
2898 case OMF_new:
2899 return ACC_plusOne;
2900
2901 default:
2902 // Otherwise, treat it as +0.
2903 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00002904 }
2905 }
John McCalle4fe2452011-10-01 01:01:08 +00002906 };
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00002907}
2908
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00002909bool Sema::isKnownName(StringRef name) {
2910 if (name.empty())
2911 return false;
2912 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00002913 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00002914 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00002915}
2916
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002917static void addFixitForObjCARCConversion(Sema &S,
2918 DiagnosticBuilder &DiagB,
2919 Sema::CheckedConversionKind CCK,
2920 SourceLocation afterLParen,
2921 QualType castType,
2922 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00002923 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002924 const char *bridgeKeyword,
2925 const char *CFBridgeName) {
2926 // We handle C-style and implicit casts here.
2927 switch (CCK) {
2928 case Sema::CCK_ImplicitConversion:
2929 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00002930 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002931 break;
2932 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002933 return;
2934 }
2935
2936 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00002937 if (CCK == Sema::CCK_OtherCast) {
2938 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
2939 SourceRange range(NCE->getOperatorLoc(),
2940 NCE->getAngleBrackets().getEnd());
2941 SmallString<32> BridgeCall;
2942
2943 SourceManager &SM = S.getSourceManager();
2944 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
2945 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
2946 BridgeCall += ' ';
2947
2948 BridgeCall += CFBridgeName;
2949 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
2950 }
2951 return;
2952 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002953 Expr *castedE = castExpr;
2954 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2955 castedE = CCE->getSubExpr();
2956 castedE = castedE->IgnoreImpCasts();
2957 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00002958
2959 SmallString<32> BridgeCall;
2960
2961 SourceManager &SM = S.getSourceManager();
2962 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
2963 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
2964 BridgeCall += ' ';
2965
2966 BridgeCall += CFBridgeName;
2967
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002968 if (isa<ParenExpr>(castedE)) {
2969 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00002970 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002971 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00002972 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002973 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00002974 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002975 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2976 S.PP.getLocForEndOfToken(range.getEnd()),
2977 ")"));
2978 }
2979 return;
2980 }
2981
2982 if (CCK == Sema::CCK_CStyleCast) {
2983 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00002984 } else if (CCK == Sema::CCK_OtherCast) {
2985 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
2986 std::string castCode = "(";
2987 castCode += bridgeKeyword;
2988 castCode += castType.getAsString();
2989 castCode += ")";
2990 SourceRange Range(NCE->getOperatorLoc(),
2991 NCE->getAngleBrackets().getEnd());
2992 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
2993 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002994 } else {
2995 std::string castCode = "(";
2996 castCode += bridgeKeyword;
2997 castCode += castType.getAsString();
2998 castCode += ")";
2999 Expr *castedE = castExpr->IgnoreImpCasts();
3000 SourceRange range = castedE->getSourceRange();
3001 if (isa<ParenExpr>(castedE)) {
3002 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3003 castCode));
3004 } else {
3005 castCode += "(";
3006 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3007 castCode));
3008 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3009 S.PP.getLocForEndOfToken(range.getEnd()),
3010 ")"));
3011 }
3012 }
3013}
3014
John McCall4124c492011-10-17 18:40:02 +00003015static void
3016diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3017 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003018 Expr *castExpr, Expr *realCast,
3019 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003020 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003021 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003022 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003023
John McCall4124c492011-10-17 18:40:02 +00003024 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003025 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003026 return;
John McCall4124c492011-10-17 18:40:02 +00003027
3028 QualType castExprType = castExpr->getType();
John McCall31168b02011-06-15 23:02:42 +00003029
John McCall640767f2011-06-17 06:50:50 +00003030 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003031 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003032 case ACTC_none:
3033 case ACTC_coreFoundation:
3034 case ACTC_voidPtr:
3035 srcKind = (castExprType->isPointerType() ? 1 : 0);
3036 break;
3037 case ACTC_retainable:
3038 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3039 break;
3040 case ACTC_indirectRetainable:
3041 srcKind = 4;
3042 break;
John McCall31168b02011-06-15 23:02:42 +00003043 }
3044
John McCall4124c492011-10-17 18:40:02 +00003045 // Check whether this could be fixed with a bridge cast.
3046 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3047 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003048
John McCall4124c492011-10-17 18:40:02 +00003049 // Bridge from an ARC type to a CF type.
3050 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003051
John McCall4124c492011-10-17 18:40:02 +00003052 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3053 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3054 << 2 // of C pointer type
3055 << castExprType
3056 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3057 << castType
3058 << castRange
3059 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003060 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003061 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003062 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003063 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003064 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003065 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003066 DiagnosticBuilder DiagB =
3067 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3068 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3069
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003070 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003071 castType, castExpr, realCast, "__bridge ", 0);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003072 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003073 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003074 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003075 DiagnosticBuilder DiagB =
3076 (CCK == Sema::CCK_OtherCast && !br) ?
3077 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3078 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3079 diag::note_arc_bridge_transfer)
3080 << castExprType << br;
3081
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003082 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003083 castType, castExpr, realCast, "__bridge_transfer ",
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003084 br ? "CFBridgingRelease" : 0);
3085 }
John McCall4124c492011-10-17 18:40:02 +00003086
3087 return;
3088 }
3089
3090 // Bridge from a CF type to an ARC type.
3091 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003092 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003093 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3094 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3095 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3096 << castExprType
3097 << 2 // to C pointer type
3098 << castType
3099 << castRange
3100 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003101 ACCResult CreateRule =
3102 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003103 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003104 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003105 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003106 DiagnosticBuilder DiagB =
3107 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3108 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003109 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003110 castType, castExpr, realCast, "__bridge ", 0);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003111 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003112 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003113 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003114 DiagnosticBuilder DiagB =
3115 (CCK == Sema::CCK_OtherCast && !br) ?
3116 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3117 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3118 diag::note_arc_bridge_retained)
3119 << castType << br;
3120
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003121 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003122 castType, castExpr, realCast, "__bridge_retained ",
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003123 br ? "CFBridgingRetain" : 0);
3124 }
John McCall4124c492011-10-17 18:40:02 +00003125
3126 return;
John McCall31168b02011-06-15 23:02:42 +00003127 }
3128
John McCall4124c492011-10-17 18:40:02 +00003129 S.Diag(loc, diag::err_arc_mismatched_cast)
3130 << (CCK != Sema::CCK_ImplicitConversion)
3131 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003132 << castRange << castExpr->getSourceRange();
3133}
3134
John McCall4124c492011-10-17 18:40:02 +00003135Sema::ARCConversionResult
3136Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
3137 Expr *&castExpr, CheckedConversionKind CCK) {
3138 QualType castExprType = castExpr->getType();
3139
3140 // For the purposes of the classification, we assume reference types
3141 // will bind to temporaries.
3142 QualType effCastType = castType;
3143 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3144 effCastType = ref->getPointeeType();
3145
3146 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3147 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003148 if (exprACTC == castACTC) {
3149 // check for viablity and report error if casting an rvalue to a
3150 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003151 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003152 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003153 (castType != castExprType)) {
3154 const Type *DT = castType.getTypePtr();
3155 QualType QDT = castType;
3156 // We desugar some types but not others. We ignore those
3157 // that cannot happen in a cast; i.e. auto, and those which
3158 // should not be de-sugared; i.e typedef.
3159 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3160 QDT = PT->desugar();
3161 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3162 QDT = TP->desugar();
3163 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3164 QDT = AT->desugar();
3165 if (QDT != castType &&
3166 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3167 SourceLocation loc =
3168 (castRange.isValid() ? castRange.getBegin()
3169 : castExpr->getExprLoc());
3170 Diag(loc, diag::err_arc_nolifetime_behavior);
3171 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003172 }
3173 return ACR_okay;
3174 }
3175
John McCall4124c492011-10-17 18:40:02 +00003176 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3177
3178 // Allow all of these types to be cast to integer types (but not
3179 // vice-versa).
3180 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3181 return ACR_okay;
3182
3183 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3184 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3185 // must be explicit.
3186 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3187 return ACR_okay;
3188 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3189 CCK != CCK_ImplicitConversion)
3190 return ACR_okay;
3191
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003192 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003193 // For invalid casts, fall through.
3194 case ACC_invalid:
3195 break;
3196
3197 // Do nothing for both bottom and +0.
3198 case ACC_bottom:
3199 case ACC_plusZero:
3200 return ACR_okay;
3201
3202 // If the result is +1, consume it here.
3203 case ACC_plusOne:
3204 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3205 CK_ARCConsumeObject, castExpr,
3206 0, VK_RValue);
3207 ExprNeedsCleanups = true;
3208 return ACR_okay;
3209 }
3210
3211 // If this is a non-implicit cast from id or block type to a
3212 // CoreFoundation type, delay complaining in case the cast is used
3213 // in an acceptable context.
3214 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3215 CCK != CCK_ImplicitConversion)
3216 return ACR_unbridged;
3217
3218 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003219 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003220 return ACR_okay;
3221}
3222
3223/// Given that we saw an expression with the ARCUnbridgedCastTy
3224/// placeholder type, complain bitterly.
3225void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3226 // We expect the spurious ImplicitCastExpr to already have been stripped.
3227 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3228 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3229
3230 SourceRange castRange;
3231 QualType castType;
3232 CheckedConversionKind CCK;
3233
3234 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3235 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3236 castType = cast->getTypeAsWritten();
3237 CCK = CCK_CStyleCast;
3238 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3239 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3240 castType = cast->getTypeAsWritten();
3241 CCK = CCK_OtherCast;
3242 } else {
3243 castType = cast->getType();
3244 CCK = CCK_ImplicitConversion;
3245 }
3246
3247 ARCConversionTypeClass castACTC =
3248 classifyTypeForARCConversion(castType.getNonReferenceType());
3249
3250 Expr *castExpr = realCast->getSubExpr();
3251 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3252
3253 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003254 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003255}
3256
3257/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3258/// type, remove the placeholder cast.
3259Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3260 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3261
3262 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3263 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3264 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3265 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3266 assert(uo->getOpcode() == UO_Extension);
3267 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3268 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3269 sub->getValueKind(), sub->getObjectKind(),
3270 uo->getOperatorLoc());
3271 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3272 assert(!gse->isResultDependent());
3273
3274 unsigned n = gse->getNumAssocs();
3275 SmallVector<Expr*, 4> subExprs(n);
3276 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3277 for (unsigned i = 0; i != n; ++i) {
3278 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3279 Expr *sub = gse->getAssocExpr(i);
3280 if (i == gse->getResultIndex())
3281 sub = stripARCUnbridgedCast(sub);
3282 subExprs[i] = sub;
3283 }
3284
3285 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3286 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003287 subTypes, subExprs,
3288 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003289 gse->getRParenLoc(),
3290 gse->containsUnexpandedParameterPack(),
3291 gse->getResultIndex());
3292 } else {
3293 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3294 return cast<ImplicitCastExpr>(e)->getSubExpr();
3295 }
3296}
3297
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003298bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3299 QualType exprType) {
3300 QualType canCastType =
3301 Context.getCanonicalType(castType).getUnqualifiedType();
3302 QualType canExprType =
3303 Context.getCanonicalType(exprType).getUnqualifiedType();
3304 if (isa<ObjCObjectPointerType>(canCastType) &&
3305 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3306 canExprType->isObjCObjectPointerType()) {
3307 if (const ObjCObjectPointerType *ObjT =
3308 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00003309 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3310 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003311 }
3312 return true;
3313}
3314
John McCall4db5c3c2011-07-07 06:58:02 +00003315/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3316static Expr *maybeUndoReclaimObject(Expr *e) {
3317 // For now, we just undo operands that are *immediately* reclaim
3318 // expressions, which prevents the vast majority of potential
3319 // problems here. To catch them all, we'd need to rebuild arbitrary
3320 // value-propagating subexpressions --- we can't reliably rebuild
3321 // in-place because of expression sharing.
3322 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00003323 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00003324 return ice->getSubExpr();
3325
3326 return e;
3327}
3328
John McCall31168b02011-06-15 23:02:42 +00003329ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3330 ObjCBridgeCastKind Kind,
3331 SourceLocation BridgeKeywordLoc,
3332 TypeSourceInfo *TSInfo,
3333 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00003334 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3335 if (SubResult.isInvalid()) return ExprError();
3336 SubExpr = SubResult.take();
3337
John McCall31168b02011-06-15 23:02:42 +00003338 QualType T = TSInfo->getType();
3339 QualType FromType = SubExpr->getType();
3340
John McCall9320b872011-09-09 05:25:32 +00003341 CastKind CK;
3342
John McCall31168b02011-06-15 23:02:42 +00003343 bool MustConsume = false;
3344 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3345 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00003346 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00003347 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3348 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00003349 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3350 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00003351 switch (Kind) {
3352 case OBC_Bridge:
3353 break;
3354
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003355 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003356 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00003357 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3358 << 2
3359 << FromType
3360 << (T->isBlockPointerType()? 1 : 0)
3361 << T
3362 << SubExpr->getSourceRange()
3363 << Kind;
3364 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3365 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3366 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003367 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00003368 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003369 br ? "CFBridgingRelease "
3370 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00003371
3372 Kind = OBC_Bridge;
3373 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003374 }
John McCall31168b02011-06-15 23:02:42 +00003375
3376 case OBC_BridgeTransfer:
3377 // We must consume the Objective-C object produced by the cast.
3378 MustConsume = true;
3379 break;
3380 }
3381 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3382 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00003383 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00003384 switch (Kind) {
3385 case OBC_Bridge:
John McCall4db5c3c2011-07-07 06:58:02 +00003386 // Reclaiming a value that's going to be __bridge-casted to CF
3387 // is very dangerous, so we don't do it.
3388 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCall31168b02011-06-15 23:02:42 +00003389 break;
3390
3391 case OBC_BridgeRetained:
3392 // Produce the object before casting it.
3393 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00003394 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00003395 SubExpr, 0, VK_RValue);
3396 break;
3397
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003398 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003399 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00003400 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3401 << (FromType->isBlockPointerType()? 1 : 0)
3402 << FromType
3403 << 2
3404 << T
3405 << SubExpr->getSourceRange()
3406 << Kind;
3407
3408 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3409 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3410 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003411 << T << br
3412 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3413 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00003414
3415 Kind = OBC_Bridge;
3416 break;
3417 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003418 }
John McCall31168b02011-06-15 23:02:42 +00003419 } else {
3420 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3421 << FromType << T << Kind
3422 << SubExpr->getSourceRange()
3423 << TSInfo->getTypeLoc().getSourceRange();
3424 return ExprError();
3425 }
3426
John McCall9320b872011-09-09 05:25:32 +00003427 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00003428 BridgeKeywordLoc,
3429 TSInfo, SubExpr);
3430
3431 if (MustConsume) {
3432 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00003433 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCall31168b02011-06-15 23:02:42 +00003434 0, VK_RValue);
3435 }
3436
3437 return Result;
3438}
3439
3440ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3441 SourceLocation LParenLoc,
3442 ObjCBridgeCastKind Kind,
3443 SourceLocation BridgeKeywordLoc,
3444 ParsedType Type,
3445 SourceLocation RParenLoc,
3446 Expr *SubExpr) {
3447 TypeSourceInfo *TSInfo = 0;
3448 QualType T = GetTypeFromParser(Type, &TSInfo);
3449 if (!TSInfo)
3450 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3451 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3452 SubExpr);
3453}