blob: e3e91d140a066d918a2fc871a58c0d44ce97b4cc [file] [log] [blame]
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Chris Lattnera3fc41d2008-01-04 22:32:30 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
Steve Naroff021ca182008-05-29 21:12:08 +000017#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor0c78ad92010-04-21 19:57:20 +000019#include "clang/AST/TypeLoc.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
21#include "clang/Edit/Commit.h"
22#include "clang/Edit/Rewriters.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Scope.h"
27#include "clang/Sema/ScopeInfo.h"
28#include "llvm/ADT/SmallString.h"
Steve Naroff9527bbf2009-03-09 21:12:44 +000029
Chris Lattnera3fc41d2008-01-04 22:32:30 +000030using namespace clang;
John McCall5f2d5562011-02-03 09:00:02 +000031using namespace sema;
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +000032using llvm::makeArrayRef;
Chris Lattnera3fc41d2008-01-04 22:32:30 +000033
John McCallfaf5fb42010-08-26 23:41:50 +000034ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 Expr **strings,
36 unsigned NumStrings) {
Chris Lattner163ffd22009-02-18 06:48:40 +000037 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
Chris Lattnerd7670d92009-02-18 06:13:04 +000039 // Most ObjC strings are formed out of a single piece. However, we *can*
40 // have strings formed out of multiple @ strings with multiple pptokens in
41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
42 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner163ffd22009-02-18 06:48:40 +000043 StringLiteral *S = Strings[0];
Mike Stump11289f42009-09-09 15:08:12 +000044
Chris Lattnerd7670d92009-02-18 06:13:04 +000045 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
Chris Lattnera3fc41d2008-01-04 22:32:30 +000047 // Concatenate objc strings.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +000048 SmallString<128> StrBuf;
Chris Lattner0e62c1c2011-07-23 10:55:15 +000049 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump11289f42009-09-09 15:08:12 +000050
Chris Lattner630970d2009-02-18 05:49:11 +000051 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner163ffd22009-02-18 06:48:40 +000052 S = Strings[i];
Mike Stump11289f42009-09-09 15:08:12 +000053
Douglas Gregorfb65e592011-07-27 05:40:30 +000054 // ObjC strings can't be wide or UTF.
55 if (!S->isAscii()) {
Chris Lattnerd7670d92009-02-18 06:13:04 +000056 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
58 return true;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Benjamin Kramer35b077e2010-08-17 12:54:38 +000061 // Append the string.
62 StrBuf += S->getString();
Mike Stump11289f42009-09-09 15:08:12 +000063
Chris Lattner163ffd22009-02-18 06:48:40 +000064 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000066 }
Mike Stump11289f42009-09-09 15:08:12 +000067
Chris Lattner163ffd22009-02-18 06:48:40 +000068 // Create the aggregate string with the appropriate content and location
69 // information.
Jay Foad9a6b0982011-06-21 15:13:30 +000070 S = StringLiteral::Create(Context, StrBuf,
Douglas Gregorfb65e592011-07-27 05:40:30 +000071 StringLiteral::Ascii, /*Pascal=*/false,
Chris Lattnerf83b5af2009-02-18 06:40:38 +000072 Context.getPointerType(Context.CharTy),
Chris Lattner163ffd22009-02-18 06:48:40 +000073 &StrLocs[0], StrLocs.size());
Chris Lattnera3fc41d2008-01-04 22:32:30 +000074 }
Ted Kremeneke65b0862012-03-06 20:05:56 +000075
76 return BuildObjCStringLiteral(AtLocs[0], S);
77}
Mike Stump11289f42009-09-09 15:08:12 +000078
Ted Kremeneke65b0862012-03-06 20:05:56 +000079ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner6436fb62009-02-18 06:01:06 +000080 // Verify that this composite string is acceptable for ObjC strings.
81 if (CheckObjCString(S))
Chris Lattnera3fc41d2008-01-04 22:32:30 +000082 return true;
Chris Lattnerfffd6a72009-02-18 06:06:56 +000083
84 // Initialize the constant string interface lazily. This assumes
Steve Naroff54e59452009-04-07 14:18:33 +000085 // the NSString interface is seen in this translation unit. Note: We
86 // don't use NSConstantString, since the runtime team considers this
87 // interface private (even though it appears in the header files).
Chris Lattnerfffd6a72009-02-18 06:06:56 +000088 QualType Ty = Context.getObjCConstantStringInterface();
89 if (!Ty.isNull()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +000090 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikiebbafb8a2012-03-11 07:00:24 +000091 } else if (getLangOpts().NoConstantCFStrings) {
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000092 IdentifierInfo *NSIdent=0;
David Blaikiebbafb8a2012-03-11 07:00:24 +000093 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian50c925f2010-10-19 17:19:29 +000094
95 if (StringClass.empty())
96 NSIdent = &Context.Idents.get("NSConstantString");
97 else
98 NSIdent = &Context.Idents.get(StringClass);
99
Ted Kremeneke65b0862012-03-06 20:05:56 +0000100 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian07317632010-04-23 23:19:04 +0000101 LookupOrdinaryName);
102 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
103 Context.setObjCConstantStringInterface(StrIF);
104 Ty = Context.getObjCConstantStringInterface();
105 Ty = Context.getObjCObjectPointerType(Ty);
106 } else {
107 // If there is no NSConstantString interface defined then treat this
108 // as error and recover from it.
109 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
110 << S->getSourceRange();
111 Ty = Context.getObjCIdType();
112 }
Chris Lattner091f6982008-06-21 21:44:18 +0000113 } else {
Patrick Beard0caa3942012-04-19 00:25:12 +0000114 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000115 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000116 LookupOrdinaryName);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000117 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
118 Context.setObjCConstantStringInterface(StrIF);
119 Ty = Context.getObjCConstantStringInterface();
Steve Naroff7cae42b2009-07-10 23:34:53 +0000120 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000121 } else {
Fariborz Jahanian86f82662012-02-23 22:51:36 +0000122 // If there is no NSString interface defined, implicitly declare
123 // a @class NSString; and use that instead. This is to make sure
124 // type of an NSString literal is represented correctly, instead of
125 // being an 'id' type.
126 Ty = Context.getObjCNSStringType();
127 if (Ty.isNull()) {
128 ObjCInterfaceDecl *NSStringIDecl =
129 ObjCInterfaceDecl::Create (Context,
130 Context.getTranslationUnitDecl(),
131 SourceLocation(), NSIdent,
132 0, SourceLocation());
133 Ty = Context.getObjCInterfaceType(NSStringIDecl);
134 Context.setObjCNSStringType(Ty);
135 }
136 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnerfffd6a72009-02-18 06:06:56 +0000137 }
Chris Lattner091f6982008-06-21 21:44:18 +0000138 }
Mike Stump11289f42009-09-09 15:08:12 +0000139
Ted Kremeneke65b0862012-03-06 20:05:56 +0000140 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
141}
142
Jordy Rose08e500c2012-05-12 17:32:44 +0000143/// \brief Emits an error if the given method does not exist, or if the return
144/// type is not an Objective-C object.
145static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
146 const ObjCInterfaceDecl *Class,
147 Selector Sel, const ObjCMethodDecl *Method) {
148 if (!Method) {
149 // FIXME: Is there a better way to avoid quotes than using getName()?
150 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
151 return false;
152 }
153
154 // Make sure the return type is reasonable.
155 QualType ReturnType = Method->getResultType();
156 if (!ReturnType->isObjCObjectPointerType()) {
157 S.Diag(Loc, diag::err_objc_literal_method_sig)
158 << Sel;
159 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
160 << ReturnType;
161 return false;
162 }
163
164 return true;
165}
166
Ted Kremeneke65b0862012-03-06 20:05:56 +0000167/// \brief Retrieve the NSNumber factory method that should be used to create
168/// an Objective-C literal for the given type.
169static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beard0caa3942012-04-19 00:25:12 +0000170 QualType NumberType,
171 bool isLiteral = false,
172 SourceRange R = SourceRange()) {
David Blaikie05785d12013-02-20 22:23:23 +0000173 Optional<NSAPI::NSNumberLiteralMethodKind> Kind =
174 S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
175
Ted Kremeneke65b0862012-03-06 20:05:56 +0000176 if (!Kind) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000177 if (isLiteral) {
178 S.Diag(Loc, diag::err_invalid_nsnumber_type)
179 << NumberType << R;
180 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000181 return 0;
182 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000183
Ted Kremeneke65b0862012-03-06 20:05:56 +0000184 // If we already looked up this method, we're done.
185 if (S.NSNumberLiteralMethods[*Kind])
186 return S.NSNumberLiteralMethods[*Kind];
187
188 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
189 /*Instance=*/false);
190
Patrick Beard0caa3942012-04-19 00:25:12 +0000191 ASTContext &CX = S.Context;
192
193 // Look up the NSNumber class, if we haven't done so already. It's cached
194 // in the Sema instance.
195 if (!S.NSNumberDecl) {
Jordy Roseaca01f92012-05-12 17:32:52 +0000196 IdentifierInfo *NSNumberId =
197 S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
Patrick Beard0caa3942012-04-19 00:25:12 +0000198 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
199 Loc, Sema::LookupOrdinaryName);
200 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
201 if (!S.NSNumberDecl) {
202 if (S.getLangOpts().DebuggerObjCLiteral) {
203 // Create a stub definition of NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000204 S.NSNumberDecl = ObjCInterfaceDecl::Create(CX,
205 CX.getTranslationUnitDecl(),
206 SourceLocation(), NSNumberId,
207 0, SourceLocation());
Patrick Beard0caa3942012-04-19 00:25:12 +0000208 } else {
209 // Otherwise, require a declaration of NSNumber.
210 S.Diag(Loc, diag::err_undeclared_nsnumber);
211 return 0;
212 }
213 } else if (!S.NSNumberDecl->hasDefinition()) {
214 S.Diag(Loc, diag::err_undeclared_nsnumber);
215 return 0;
216 }
217
218 // generate the pointer to NSNumber type.
Jordy Roseaca01f92012-05-12 17:32:52 +0000219 QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl);
220 S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000221 }
222
Ted Kremeneke65b0862012-03-06 20:05:56 +0000223 // Look for the appropriate method within NSNumber.
Jordy Roseaca01f92012-05-12 17:32:52 +0000224 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000225 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000226 // create a stub definition this NSNumber factory method.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000227 TypeSourceInfo *ResultTInfo = 0;
Patrick Beard0caa3942012-04-19 00:25:12 +0000228 Method = ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +0000229 S.NSNumberPointer, ResultTInfo,
230 S.NSNumberDecl,
Patrick Beard0caa3942012-04-19 00:25:12 +0000231 /*isInstance=*/false, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000232 /*isPropertyAccessor=*/false,
Patrick Beard0caa3942012-04-19 00:25:12 +0000233 /*isImplicitlyDeclared=*/true,
Jordy Roseaca01f92012-05-12 17:32:52 +0000234 /*isDefined=*/false,
235 ObjCMethodDecl::Required,
Patrick Beard0caa3942012-04-19 00:25:12 +0000236 /*HasRelatedResultType=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000237 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
238 SourceLocation(), SourceLocation(),
Patrick Beard0caa3942012-04-19 00:25:12 +0000239 &CX.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000240 NumberType, /*TInfo=*/0, SC_None,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000241 0);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000242 Method->setMethodParams(S.Context, value, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000243 }
244
Jordy Rose08e500c2012-05-12 17:32:44 +0000245 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000246 return 0;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000247
248 // Note: if the parameter type is out-of-line, we'll catch it later in the
249 // implicit conversion.
250
251 S.NSNumberLiteralMethods[*Kind] = Method;
252 return Method;
253}
254
Patrick Beard0caa3942012-04-19 00:25:12 +0000255/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
256/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremeneke65b0862012-03-06 20:05:56 +0000257ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000258 // Determine the type of the literal.
259 QualType NumberType = Number->getType();
260 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
261 // In C, character literals have type 'int'. That's not the type we want
262 // to use to determine the Objective-c literal kind.
263 switch (Char->getKind()) {
264 case CharacterLiteral::Ascii:
265 NumberType = Context.CharTy;
266 break;
267
268 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000269 NumberType = Context.getWideCharType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000270 break;
271
272 case CharacterLiteral::UTF16:
273 NumberType = Context.Char16Ty;
274 break;
275
276 case CharacterLiteral::UTF32:
277 NumberType = Context.Char32Ty;
278 break;
279 }
280 }
281
Ted Kremeneke65b0862012-03-06 20:05:56 +0000282 // Look for the appropriate method within NSNumber.
283 // Construct the literal.
Patrick Beard2565c592012-05-01 21:47:19 +0000284 SourceRange NR(Number->getSourceRange());
Patrick Beard0caa3942012-04-19 00:25:12 +0000285 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Beard2565c592012-05-01 21:47:19 +0000286 true, NR);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000287 if (!Method)
288 return ExprError();
289
290 // Convert the number to the type that the parameter expects.
Patrick Beard2565c592012-05-01 21:47:19 +0000291 ParmVarDecl *ParamDecl = Method->param_begin()[0];
292 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
293 ParamDecl);
294 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
295 SourceLocation(),
296 Owned(Number));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000297 if (ConvertedNumber.isInvalid())
298 return ExprError();
299 Number = ConvertedNumber.get();
300
Patrick Beard2565c592012-05-01 21:47:19 +0000301 // Use the effective source range of the literal, including the leading '@'.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000302 return MaybeBindToTemporary(
Patrick Beard2565c592012-05-01 21:47:19 +0000303 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
304 SourceRange(AtLoc, NR.getEnd())));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000305}
306
307ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
308 SourceLocation ValueLoc,
309 bool Value) {
310 ExprResult Inner;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000311 if (getLangOpts().CPlusPlus) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000312 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
313 } else {
314 // C doesn't actually have a way to represent literal values of type
315 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
316 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
317 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
318 CK_IntegralToBoolean);
319 }
320
321 return BuildObjCNumericLiteral(AtLoc, Inner.get());
322}
323
324/// \brief Check that the given expression is a valid element of an Objective-C
325/// collection literal.
326static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000327 QualType T,
328 bool ArrayLiteral = false) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000329 // If the expression is type-dependent, there's nothing for us to do.
330 if (Element->isTypeDependent())
331 return Element;
332
333 ExprResult Result = S.CheckPlaceholderExpr(Element);
334 if (Result.isInvalid())
335 return ExprError();
336 Element = Result.get();
337
338 // In C++, check for an implicit conversion to an Objective-C object pointer
339 // type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000340 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000341 InitializedEntity Entity
Jordy Roseaca01f92012-05-12 17:32:52 +0000342 = InitializedEntity::InitializeParameter(S.Context, T,
343 /*Consumed=*/false);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000344 InitializationKind Kind
Jordy Roseaca01f92012-05-12 17:32:52 +0000345 = InitializationKind::CreateCopy(Element->getLocStart(),
346 SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +0000347 InitializationSequence Seq(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000348 if (!Seq.Failed())
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000349 return Seq.Perform(S, Entity, Kind, Element);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000350 }
351
352 Expr *OrigElement = Element;
353
354 // Perform lvalue-to-rvalue conversion.
355 Result = S.DefaultLvalueConversion(Element);
356 if (Result.isInvalid())
357 return ExprError();
358 Element = Result.get();
359
360 // Make sure that we have an Objective-C pointer type or block.
361 if (!Element->getType()->isObjCObjectPointerType() &&
362 !Element->getType()->isBlockPointerType()) {
363 bool Recovered = false;
364
365 // If this is potentially an Objective-C numeric literal, add the '@'.
366 if (isa<IntegerLiteral>(OrigElement) ||
367 isa<CharacterLiteral>(OrigElement) ||
368 isa<FloatingLiteral>(OrigElement) ||
369 isa<ObjCBoolLiteralExpr>(OrigElement) ||
370 isa<CXXBoolLiteralExpr>(OrigElement)) {
371 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
372 int Which = isa<CharacterLiteral>(OrigElement) ? 1
373 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
374 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
375 : 3;
376
377 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
378 << Which << OrigElement->getSourceRange()
379 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
380
381 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
382 OrigElement);
383 if (Result.isInvalid())
384 return ExprError();
385
386 Element = Result.get();
387 Recovered = true;
388 }
389 }
390 // If this is potentially an Objective-C string literal, add the '@'.
391 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
392 if (String->isAscii()) {
393 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
394 << 0 << OrigElement->getSourceRange()
395 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
396
397 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
398 if (Result.isInvalid())
399 return ExprError();
400
401 Element = Result.get();
402 Recovered = true;
403 }
404 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000405
Ted Kremeneke65b0862012-03-06 20:05:56 +0000406 if (!Recovered) {
407 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
408 << Element->getType();
409 return ExprError();
410 }
411 }
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000412 if (ArrayLiteral)
413 if (ObjCStringLiteral *getString = dyn_cast<ObjCStringLiteral>(OrigElement)) {
414 if (getString->getString() && getString->getString()->getNumConcatenated() > 1)
415 S.Diag(Element->getLocStart(), diag::warn_concatenated_nsarray_literal)
416 << Element->getType();
417 }
418
Ted Kremeneke65b0862012-03-06 20:05:56 +0000419 // Make sure that the element has the type that the container factory
420 // function expects.
421 return S.PerformCopyInitialization(
422 InitializedEntity::InitializeParameter(S.Context, T,
423 /*Consumed=*/false),
424 Element->getLocStart(), Element);
425}
426
Patrick Beard0caa3942012-04-19 00:25:12 +0000427ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
428 if (ValueExpr->isTypeDependent()) {
429 ObjCBoxedExpr *BoxedExpr =
430 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR);
431 return Owned(BoxedExpr);
432 }
433 ObjCMethodDecl *BoxingMethod = NULL;
434 QualType BoxedType;
435 // Convert the expression to an RValue, so we can check for pointer types...
436 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
437 if (RValue.isInvalid()) {
438 return ExprError();
439 }
440 ValueExpr = RValue.get();
Patrick Beard2565c592012-05-01 21:47:19 +0000441 QualType ValueType(ValueExpr->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +0000442 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
443 QualType PointeeType = PT->getPointeeType();
444 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
445
446 if (!NSStringDecl) {
447 IdentifierInfo *NSStringId =
448 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
449 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
450 SR.getBegin(), LookupOrdinaryName);
451 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
452 if (!NSStringDecl) {
453 if (getLangOpts().DebuggerObjCLiteral) {
454 // Support boxed expressions in the debugger w/o NSString declaration.
Jordy Roseaca01f92012-05-12 17:32:52 +0000455 DeclContext *TU = Context.getTranslationUnitDecl();
456 NSStringDecl = ObjCInterfaceDecl::Create(Context, TU,
457 SourceLocation(),
458 NSStringId,
Patrick Beard0caa3942012-04-19 00:25:12 +0000459 0, SourceLocation());
460 } else {
461 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
462 return ExprError();
463 }
464 } else if (!NSStringDecl->hasDefinition()) {
465 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
466 return ExprError();
467 }
468 assert(NSStringDecl && "NSStringDecl should not be NULL");
Jordy Roseaca01f92012-05-12 17:32:52 +0000469 QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl);
470 NSStringPointer = Context.getObjCObjectPointerType(NSStringObject);
Patrick Beard0caa3942012-04-19 00:25:12 +0000471 }
472
473 if (!StringWithUTF8StringMethod) {
474 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
475 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
476
477 // Look for the appropriate method within NSString.
Jordy Rose08e500c2012-05-12 17:32:44 +0000478 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
479 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000480 // Debugger needs to work even if NSString hasn't been defined.
481 TypeSourceInfo *ResultTInfo = 0;
482 ObjCMethodDecl *M =
483 ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(),
484 stringWithUTF8String, NSStringPointer,
485 ResultTInfo, NSStringDecl,
486 /*isInstance=*/false, /*isVariadic=*/false,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000487 /*isPropertyAccessor=*/false,
Patrick Beard0caa3942012-04-19 00:25:12 +0000488 /*isImplicitlyDeclared=*/true,
489 /*isDefined=*/false,
490 ObjCMethodDecl::Required,
491 /*HasRelatedResultType=*/false);
Jordy Roseaca01f92012-05-12 17:32:52 +0000492 QualType ConstCharType = Context.CharTy.withConst();
Patrick Beard0caa3942012-04-19 00:25:12 +0000493 ParmVarDecl *value =
494 ParmVarDecl::Create(Context, M,
495 SourceLocation(), SourceLocation(),
496 &Context.Idents.get("value"),
Jordy Roseaca01f92012-05-12 17:32:52 +0000497 Context.getPointerType(ConstCharType),
Patrick Beard0caa3942012-04-19 00:25:12 +0000498 /*TInfo=*/0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000499 SC_None, 0);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000500 M->setMethodParams(Context, value, None);
Jordy Rose08e500c2012-05-12 17:32:44 +0000501 BoxingMethod = M;
Patrick Beard0caa3942012-04-19 00:25:12 +0000502 }
Jordy Rose890f4572012-05-12 15:53:41 +0000503
Jordy Rose08e500c2012-05-12 17:32:44 +0000504 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
505 stringWithUTF8String, BoxingMethod))
506 return ExprError();
507
508 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beard0caa3942012-04-19 00:25:12 +0000509 }
510
511 BoxingMethod = StringWithUTF8StringMethod;
512 BoxedType = NSStringPointer;
513 }
Patrick Beard2565c592012-05-01 21:47:19 +0000514 } else if (ValueType->isBuiltinType()) {
Patrick Beard0caa3942012-04-19 00:25:12 +0000515 // The other types we support are numeric, char and BOOL/bool. We could also
516 // provide limited support for structure types, such as NSRange, NSRect, and
517 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
518 // for more details.
519
520 // Check for a top-level character literal.
521 if (const CharacterLiteral *Char =
522 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
523 // In C, character literals have type 'int'. That's not the type we want
524 // to use to determine the Objective-c literal kind.
525 switch (Char->getKind()) {
526 case CharacterLiteral::Ascii:
527 ValueType = Context.CharTy;
528 break;
529
530 case CharacterLiteral::Wide:
Hans Wennborg0d81e012013-05-10 10:08:40 +0000531 ValueType = Context.getWideCharType();
Patrick Beard0caa3942012-04-19 00:25:12 +0000532 break;
533
534 case CharacterLiteral::UTF16:
535 ValueType = Context.Char16Ty;
536 break;
537
538 case CharacterLiteral::UTF32:
539 ValueType = Context.Char32Ty;
540 break;
541 }
542 }
543
544 // FIXME: Do I need to do anything special with BoolTy expressions?
545
546 // Look for the appropriate method within NSNumber.
547 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
548 BoxedType = NSNumberPointer;
Argyrios Kyrtzidis8e6951d2012-05-15 19:17:44 +0000549
550 } else if (const EnumType *ET = ValueType->getAs<EnumType>()) {
551 if (!ET->getDecl()->isComplete()) {
552 Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type)
553 << ValueType << ValueExpr->getSourceRange();
554 return ExprError();
555 }
556
557 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(),
558 ET->getDecl()->getIntegerType());
559 BoxedType = NSNumberPointer;
Patrick Beard0caa3942012-04-19 00:25:12 +0000560 }
561
562 if (!BoxingMethod) {
563 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
564 << ValueType << ValueExpr->getSourceRange();
565 return ExprError();
566 }
567
568 // Convert the expression to the type that the parameter requires.
Patrick Beard2565c592012-05-01 21:47:19 +0000569 ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0];
570 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
571 ParamDecl);
572 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
573 SourceLocation(),
574 Owned(ValueExpr));
Patrick Beard0caa3942012-04-19 00:25:12 +0000575 if (ConvertedValueExpr.isInvalid())
576 return ExprError();
577 ValueExpr = ConvertedValueExpr.get();
578
579 ObjCBoxedExpr *BoxedExpr =
580 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
581 BoxingMethod, SR);
582 return MaybeBindToTemporary(BoxedExpr);
583}
584
John McCallf2538342012-07-31 05:14:30 +0000585/// Build an ObjC subscript pseudo-object expression, given that
586/// that's supported by the runtime.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000587ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
588 Expr *IndexExpr,
589 ObjCMethodDecl *getterMethod,
590 ObjCMethodDecl *setterMethod) {
John McCallf2538342012-07-31 05:14:30 +0000591 assert(!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic());
John McCall5fb5df92012-06-20 06:18:46 +0000592
John McCallf2538342012-07-31 05:14:30 +0000593 // We can't get dependent types here; our callers should have
594 // filtered them out.
595 assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
596 "base or index cannot have dependent type here");
597
598 // Filter out placeholders in the index. In theory, overloads could
599 // be preserved here, although that might not actually work correctly.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000600 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
601 if (Result.isInvalid())
602 return ExprError();
603 IndexExpr = Result.get();
604
John McCallf2538342012-07-31 05:14:30 +0000605 // Perform lvalue-to-rvalue conversion on the base.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000606 Result = DefaultLvalueConversion(BaseExpr);
607 if (Result.isInvalid())
608 return ExprError();
609 BaseExpr = Result.get();
John McCallf2538342012-07-31 05:14:30 +0000610
611 // Build the pseudo-object expression.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000612 return Owned(ObjCSubscriptRefExpr::Create(Context,
613 BaseExpr,
614 IndexExpr,
615 Context.PseudoObjectTy,
616 getterMethod,
617 setterMethod, RB));
618
619}
620
621ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
622 // Look up the NSArray class, if we haven't done so already.
623 if (!NSArrayDecl) {
624 NamedDecl *IF = LookupSingleName(TUScope,
625 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
626 SR.getBegin(),
627 LookupOrdinaryName);
628 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000629 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000630 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
631 Context.getTranslationUnitDecl(),
632 SourceLocation(),
633 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
634 0, SourceLocation());
635
636 if (!NSArrayDecl) {
637 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
638 return ExprError();
639 }
640 }
641
642 // Find the arrayWithObjects:count: method, if we haven't done so already.
643 QualType IdT = Context.getObjCIdType();
644 if (!ArrayWithObjectsMethod) {
645 Selector
646 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
Jordy Rose08e500c2012-05-12 17:32:44 +0000647 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
648 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000649 TypeSourceInfo *ResultTInfo = 0;
Jordy Rose08e500c2012-05-12 17:32:44 +0000650 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000651 SourceLocation(), SourceLocation(), Sel,
652 IdT,
653 ResultTInfo,
654 Context.getTranslationUnitDecl(),
655 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000656 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000657 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
658 ObjCMethodDecl::Required,
659 false);
660 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000661 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000662 SourceLocation(),
663 SourceLocation(),
664 &Context.Idents.get("objects"),
665 Context.getPointerType(IdT),
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000666 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000667 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000668 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000669 SourceLocation(),
670 SourceLocation(),
671 &Context.Idents.get("cnt"),
672 Context.UnsignedLongTy,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000673 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000674 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000675 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000676 }
677
Jordy Rose08e500c2012-05-12 17:32:44 +0000678 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremeneke65b0862012-03-06 20:05:56 +0000679 return ExprError();
Jordy Rose08e500c2012-05-12 17:32:44 +0000680
Jordy Rose4af44872012-05-12 17:32:56 +0000681 // Dig out the type that all elements should be converted to.
682 QualType T = Method->param_begin()[0]->getType();
683 const PointerType *PtrT = T->getAs<PointerType>();
684 if (!PtrT ||
685 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
686 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
687 << Sel;
688 Diag(Method->param_begin()[0]->getLocation(),
689 diag::note_objc_literal_method_param)
690 << 0 << T
691 << Context.getPointerType(IdT.withConst());
692 return ExprError();
693 }
694
695 // Check that the 'count' parameter is integral.
696 if (!Method->param_begin()[1]->getType()->isIntegerType()) {
697 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
698 << Sel;
699 Diag(Method->param_begin()[1]->getLocation(),
700 diag::note_objc_literal_method_param)
701 << 1
702 << Method->param_begin()[1]->getType()
703 << "integral";
704 return ExprError();
705 }
706
707 // We've found a good +arrayWithObjects:count: method. Save it!
Jordy Rose08e500c2012-05-12 17:32:44 +0000708 ArrayWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000709 }
710
Jordy Rose4af44872012-05-12 17:32:56 +0000711 QualType ObjectsType = ArrayWithObjectsMethod->param_begin()[0]->getType();
712 QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000713
714 // Check that each of the elements provided is valid in a collection literal,
715 // performing conversions as necessary.
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000716 Expr **ElementsBuffer = Elements.data();
Ted Kremeneke65b0862012-03-06 20:05:56 +0000717 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
718 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
719 ElementsBuffer[I],
Fariborz Jahaniana802c352013-08-13 23:44:55 +0000720 RequiredType, true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000721 if (Converted.isInvalid())
722 return ExprError();
723
724 ElementsBuffer[I] = Converted.get();
725 }
726
727 QualType Ty
728 = Context.getObjCObjectPointerType(
729 Context.getObjCInterfaceType(NSArrayDecl));
730
731 return MaybeBindToTemporary(
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000732 ObjCArrayLiteral::Create(Context, Elements, Ty,
733 ArrayWithObjectsMethod, SR));
Ted Kremeneke65b0862012-03-06 20:05:56 +0000734}
735
736ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
737 ObjCDictionaryElement *Elements,
738 unsigned NumElements) {
739 // Look up the NSDictionary class, if we haven't done so already.
740 if (!NSDictionaryDecl) {
741 NamedDecl *IF = LookupSingleName(TUScope,
742 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
743 SR.getBegin(), LookupOrdinaryName);
744 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikiebbafb8a2012-03-11 07:00:24 +0000745 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremeneke65b0862012-03-06 20:05:56 +0000746 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
747 Context.getTranslationUnitDecl(),
748 SourceLocation(),
749 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
750 0, SourceLocation());
751
752 if (!NSDictionaryDecl) {
753 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
754 return ExprError();
755 }
756 }
757
758 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
759 // so already.
760 QualType IdT = Context.getObjCIdType();
761 if (!DictionaryWithObjectsMethod) {
762 Selector Sel = NSAPIObj->getNSDictionarySelector(
Jordy Roseaca01f92012-05-12 17:32:52 +0000763 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
Jordy Rose08e500c2012-05-12 17:32:44 +0000764 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
765 if (!Method && getLangOpts().DebuggerObjCLiteral) {
766 Method = ObjCMethodDecl::Create(Context,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000767 SourceLocation(), SourceLocation(), Sel,
768 IdT,
769 0 /*TypeSourceInfo */,
770 Context.getTranslationUnitDecl(),
771 false /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +0000772 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +0000773 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
774 ObjCMethodDecl::Required,
775 false);
776 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rose08e500c2012-05-12 17:32:44 +0000777 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000778 SourceLocation(),
779 SourceLocation(),
780 &Context.Idents.get("objects"),
781 Context.getPointerType(IdT),
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000782 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000783 Params.push_back(objects);
Jordy Rose08e500c2012-05-12 17:32:44 +0000784 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000785 SourceLocation(),
786 SourceLocation(),
787 &Context.Idents.get("keys"),
788 Context.getPointerType(IdT),
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000789 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000790 Params.push_back(keys);
Jordy Rose08e500c2012-05-12 17:32:44 +0000791 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Jordy Roseaca01f92012-05-12 17:32:52 +0000792 SourceLocation(),
793 SourceLocation(),
794 &Context.Idents.get("cnt"),
795 Context.UnsignedLongTy,
Rafael Espindola6ae7e502013-04-03 19:27:57 +0000796 /*TInfo=*/0, SC_None, 0);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000797 Params.push_back(cnt);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000798 Method->setMethodParams(Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000799 }
800
Jordy Rose08e500c2012-05-12 17:32:44 +0000801 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
802 Method))
803 return ExprError();
804
Jordy Rose4af44872012-05-12 17:32:56 +0000805 // Dig out the type that all values should be converted to.
806 QualType ValueT = Method->param_begin()[0]->getType();
807 const PointerType *PtrValue = ValueT->getAs<PointerType>();
808 if (!PtrValue ||
809 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000810 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
Jordy Rose4af44872012-05-12 17:32:56 +0000811 << Sel;
812 Diag(Method->param_begin()[0]->getLocation(),
Ted Kremeneke65b0862012-03-06 20:05:56 +0000813 diag::note_objc_literal_method_param)
Jordy Rose4af44872012-05-12 17:32:56 +0000814 << 0 << ValueT
Ted Kremeneke65b0862012-03-06 20:05:56 +0000815 << Context.getPointerType(IdT.withConst());
816 return ExprError();
817 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000818
Jordy Rose4af44872012-05-12 17:32:56 +0000819 // Dig out the type that all keys should be converted to.
820 QualType KeyT = Method->param_begin()[1]->getType();
821 const PointerType *PtrKey = KeyT->getAs<PointerType>();
822 if (!PtrKey ||
823 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
824 IdT)) {
825 bool err = true;
826 if (PtrKey) {
827 if (QIDNSCopying.isNull()) {
828 // key argument of selector is id<NSCopying>?
829 if (ObjCProtocolDecl *NSCopyingPDecl =
830 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
831 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
832 QIDNSCopying =
833 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
834 (ObjCProtocolDecl**) PQ,1);
835 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
836 }
837 }
838 if (!QIDNSCopying.isNull())
839 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
840 QIDNSCopying);
841 }
842
843 if (err) {
844 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
845 << Sel;
846 Diag(Method->param_begin()[1]->getLocation(),
847 diag::note_objc_literal_method_param)
848 << 1 << KeyT
849 << Context.getPointerType(IdT.withConst());
850 return ExprError();
851 }
852 }
853
854 // Check that the 'count' parameter is integral.
855 QualType CountType = Method->param_begin()[2]->getType();
856 if (!CountType->isIntegerType()) {
857 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
858 << Sel;
859 Diag(Method->param_begin()[2]->getLocation(),
860 diag::note_objc_literal_method_param)
861 << 2 << CountType
862 << "integral";
863 return ExprError();
864 }
865
866 // We've found a good +dictionaryWithObjects:keys:count: method; save it!
867 DictionaryWithObjectsMethod = Method;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000868 }
869
Jordy Rose4af44872012-05-12 17:32:56 +0000870 QualType ValuesT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
871 QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType();
872 QualType KeysT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
873 QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType();
874
Ted Kremeneke65b0862012-03-06 20:05:56 +0000875 // Check that each of the keys and values provided is valid in a collection
876 // literal, performing conversions as necessary.
877 bool HasPackExpansions = false;
878 for (unsigned I = 0, N = NumElements; I != N; ++I) {
879 // Check the key.
880 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
881 KeyT);
882 if (Key.isInvalid())
883 return ExprError();
884
885 // Check the value.
886 ExprResult Value
887 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
888 if (Value.isInvalid())
889 return ExprError();
890
891 Elements[I].Key = Key.get();
892 Elements[I].Value = Value.get();
893
894 if (Elements[I].EllipsisLoc.isInvalid())
895 continue;
896
897 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
898 !Elements[I].Value->containsUnexpandedParameterPack()) {
899 Diag(Elements[I].EllipsisLoc,
900 diag::err_pack_expansion_without_parameter_packs)
901 << SourceRange(Elements[I].Key->getLocStart(),
902 Elements[I].Value->getLocEnd());
903 return ExprError();
904 }
905
906 HasPackExpansions = true;
907 }
908
909
910 QualType Ty
911 = Context.getObjCObjectPointerType(
912 Context.getObjCInterfaceType(NSDictionaryDecl));
913 return MaybeBindToTemporary(
914 ObjCDictionaryLiteral::Create(Context,
915 llvm::makeArrayRef(Elements,
916 NumElements),
917 HasPackExpansions,
918 Ty,
919 DictionaryWithObjectsMethod, SR));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000920}
921
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000922ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregorabd9e962010-04-20 15:39:42 +0000923 TypeSourceInfo *EncodedTypeInfo,
Anders Carlsson315d2292009-06-07 18:45:35 +0000924 SourceLocation RParenLoc) {
Douglas Gregorabd9e962010-04-20 15:39:42 +0000925 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlsson315d2292009-06-07 18:45:35 +0000926 QualType StrTy;
Mike Stump11289f42009-09-09 15:08:12 +0000927 if (EncodedType->isDependentType())
Anders Carlsson315d2292009-06-07 18:45:35 +0000928 StrTy = Context.DependentTy;
929 else {
Fariborz Jahaniand9bc6c32011-06-16 22:34:44 +0000930 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
931 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000932 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000933 diag::err_incomplete_type_objc_at_encode,
934 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis7da04c62011-05-14 20:32:39 +0000935 return ExprError();
936
Anders Carlsson315d2292009-06-07 18:45:35 +0000937 std::string Str;
938 Context.getObjCEncodingForType(EncodedType, Str);
939
940 // The type of @encode is the same as the type of the corresponding string,
941 // which is an array type.
942 StrTy = Context.CharTy;
943 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +0000944 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlsson315d2292009-06-07 18:45:35 +0000945 StrTy.addConst();
946 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
947 ArrayType::Normal, 0);
948 }
Mike Stump11289f42009-09-09 15:08:12 +0000949
Douglas Gregorabd9e962010-04-20 15:39:42 +0000950 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlsson315d2292009-06-07 18:45:35 +0000951}
952
John McCallfaf5fb42010-08-26 23:41:50 +0000953ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
954 SourceLocation EncodeLoc,
955 SourceLocation LParenLoc,
956 ParsedType ty,
957 SourceLocation RParenLoc) {
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000958 // FIXME: Preserve type source info ?
Douglas Gregorabd9e962010-04-20 15:39:42 +0000959 TypeSourceInfo *TInfo;
960 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
961 if (!TInfo)
962 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
963 PP.getLocForEndOfToken(LParenLoc));
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000964
Douglas Gregorabd9e962010-04-20 15:39:42 +0000965 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +0000966}
967
John McCallfaf5fb42010-08-26 23:41:50 +0000968ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
969 SourceLocation AtLoc,
970 SourceLocation SelLoc,
971 SourceLocation LParenLoc,
Fariborz Jahanian02447d82013-01-22 18:35:43 +0000972 SourceLocation RParenLoc) {
973 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
974 SourceRange(LParenLoc, RParenLoc), false, false);
975 if (!Method)
976 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian0571d9b2009-06-16 16:25:00 +0000977 SourceRange(LParenLoc, RParenLoc));
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +0000978 if (!Method) {
979 if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) {
980 Selector MatchedSel = OM->getSelector();
981 SourceRange SelectorRange(LParenLoc.getLocWithOffset(1),
982 RParenLoc.getLocWithOffset(-1));
983 Diag(SelLoc, diag::warn_undeclared_selector_with_typo)
984 << Sel << MatchedSel
985 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
986
987 } else
988 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
989 }
Fariborz Jahanian9a881012011-07-13 19:05:43 +0000990
Fariborz Jahanian02447d82013-01-22 18:35:43 +0000991 if (!Method ||
992 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
993 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
994 = ReferencedSelectors.find(Sel);
995 if (Pos == ReferencedSelectors.end())
996 ReferencedSelectors.insert(std::make_pair(Sel, AtLoc));
Fariborz Jahanian9a881012011-07-13 19:05:43 +0000997 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +0000998
Fariborz Jahanian02447d82013-01-22 18:35:43 +0000999 // In ARC, forbid the user from using @selector for
John McCall31168b02011-06-15 23:02:42 +00001000 // retain/release/autorelease/dealloc/retainCount.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001001 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001002 switch (Sel.getMethodFamily()) {
1003 case OMF_retain:
1004 case OMF_release:
1005 case OMF_autorelease:
1006 case OMF_retainCount:
1007 case OMF_dealloc:
1008 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1009 Sel << SourceRange(LParenLoc, RParenLoc);
1010 break;
1011
1012 case OMF_None:
1013 case OMF_alloc:
1014 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00001015 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001016 case OMF_init:
1017 case OMF_mutableCopy:
1018 case OMF_new:
1019 case OMF_self:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001020 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001021 break;
1022 }
1023 }
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001024 QualType Ty = Context.getObjCSelType();
Daniel Dunbar45858d22010-02-03 20:11:42 +00001025 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001026}
1027
John McCallfaf5fb42010-08-26 23:41:50 +00001028ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1029 SourceLocation AtLoc,
1030 SourceLocation ProtoLoc,
1031 SourceLocation LParenLoc,
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001032 SourceLocation ProtoIdLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00001033 SourceLocation RParenLoc) {
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001034 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001035 if (!PDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001036 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001037 return true;
1038 }
Mike Stump11289f42009-09-09 15:08:12 +00001039
Chris Lattnerfffd6a72009-02-18 06:06:56 +00001040 QualType Ty = Context.getObjCProtoType();
1041 if (Ty.isNull())
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001042 return true;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001043 Ty = Context.getObjCObjectPointerType(Ty);
Argyrios Kyrtzidisb7e43672012-05-16 00:50:02 +00001044 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001045}
1046
John McCall5f2d5562011-02-03 09:00:02 +00001047/// Try to capture an implicit reference to 'self'.
Eli Friedman24af8502012-02-03 22:47:37 +00001048ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1049 DeclContext *DC = getFunctionLevelDeclContext();
John McCall5f2d5562011-02-03 09:00:02 +00001050
1051 // If we're not in an ObjC method, error out. Note that, unlike the
1052 // C++ case, we don't require an instance method --- class methods
1053 // still have a 'self', and we really do still need to capture it!
1054 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1055 if (!method)
1056 return 0;
1057
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001058 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall5f2d5562011-02-03 09:00:02 +00001059
1060 return method;
1061}
1062
Douglas Gregor64910ca2011-09-09 20:05:21 +00001063static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1064 if (T == Context.getObjCInstanceType())
1065 return Context.getObjCIdType();
1066
1067 return T;
1068}
1069
Douglas Gregor33823722011-06-11 01:09:30 +00001070QualType Sema::getMessageSendResultType(QualType ReceiverType,
1071 ObjCMethodDecl *Method,
1072 bool isClassMessage, bool isSuperMessage) {
1073 assert(Method && "Must have a method");
1074 if (!Method->hasRelatedResultType())
1075 return Method->getSendResultType();
1076
1077 // If a method has a related return type:
1078 // - if the method found is an instance method, but the message send
1079 // was a class message send, T is the declared return type of the method
1080 // found
1081 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor64910ca2011-09-09 20:05:21 +00001082 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001083
1084 // - if the receiver is super, T is a pointer to the class of the
1085 // enclosing method definition
1086 if (isSuperMessage) {
1087 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1088 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1089 return Context.getObjCObjectPointerType(
1090 Context.getObjCInterfaceType(Class));
1091 }
1092
1093 // - if the receiver is the name of a class U, T is a pointer to U
1094 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1095 ReceiverType->isObjCQualifiedInterfaceType())
1096 return Context.getObjCObjectPointerType(ReceiverType);
1097 // - if the receiver is of type Class or qualified Class type,
1098 // T is the declared return type of the method.
1099 if (ReceiverType->isObjCClassType() ||
1100 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor64910ca2011-09-09 20:05:21 +00001101 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor33823722011-06-11 01:09:30 +00001102
1103 // - if the receiver is id, qualified id, Class, or qualified Class, T
1104 // is the receiver type, otherwise
1105 // - T is the type of the receiver expression.
1106 return ReceiverType;
1107}
John McCall5f2d5562011-02-03 09:00:02 +00001108
John McCall5ec7e7d2013-03-19 07:04:25 +00001109/// Look for an ObjC method whose result type exactly matches the given type.
1110static const ObjCMethodDecl *
1111findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD,
1112 QualType instancetype) {
1113 if (MD->getResultType() == instancetype) return MD;
1114
1115 // For these purposes, a method in an @implementation overrides a
1116 // declaration in the @interface.
1117 if (const ObjCImplDecl *impl =
1118 dyn_cast<ObjCImplDecl>(MD->getDeclContext())) {
1119 const ObjCContainerDecl *iface;
1120 if (const ObjCCategoryImplDecl *catImpl =
1121 dyn_cast<ObjCCategoryImplDecl>(impl)) {
1122 iface = catImpl->getCategoryDecl();
1123 } else {
1124 iface = impl->getClassInterface();
1125 }
1126
1127 const ObjCMethodDecl *ifaceMD =
1128 iface->getMethod(MD->getSelector(), MD->isInstanceMethod());
1129 if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype);
1130 }
1131
1132 SmallVector<const ObjCMethodDecl *, 4> overrides;
1133 MD->getOverriddenMethods(overrides);
1134 for (unsigned i = 0, e = overrides.size(); i != e; ++i) {
1135 if (const ObjCMethodDecl *result =
1136 findExplicitInstancetypeDeclarer(overrides[i], instancetype))
1137 return result;
1138 }
1139
1140 return 0;
1141}
1142
1143void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) {
1144 // Only complain if we're in an ObjC method and the required return
1145 // type doesn't match the method's declared return type.
1146 ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext);
1147 if (!MD || !MD->hasRelatedResultType() ||
1148 Context.hasSameUnqualifiedType(destType, MD->getResultType()))
1149 return;
1150
1151 // Look for a method overridden by this method which explicitly uses
1152 // 'instancetype'.
1153 if (const ObjCMethodDecl *overridden =
1154 findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) {
1155 SourceLocation loc;
1156 SourceRange range;
1157 if (TypeSourceInfo *TSI = overridden->getResultTypeSourceInfo()) {
1158 range = TSI->getTypeLoc().getSourceRange();
1159 loc = range.getBegin();
1160 }
1161 if (loc.isInvalid())
1162 loc = overridden->getLocation();
1163 Diag(loc, diag::note_related_result_type_explicit)
1164 << /*current method*/ 1 << range;
1165 return;
1166 }
1167
1168 // Otherwise, if we have an interesting method family, note that.
1169 // This should always trigger if the above didn't.
1170 if (ObjCMethodFamily family = MD->getMethodFamily())
1171 Diag(MD->getLocation(), diag::note_related_result_type_family)
1172 << /*current method*/ 1
1173 << family;
1174}
1175
Douglas Gregor33823722011-06-11 01:09:30 +00001176void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1177 E = E->IgnoreParenImpCasts();
1178 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1179 if (!MsgSend)
1180 return;
1181
1182 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1183 if (!Method)
1184 return;
1185
1186 if (!Method->hasRelatedResultType())
1187 return;
1188
1189 if (Context.hasSameUnqualifiedType(Method->getResultType()
1190 .getNonReferenceType(),
1191 MsgSend->getType()))
1192 return;
1193
Douglas Gregorbab8a962011-09-08 01:46:34 +00001194 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
1195 Context.getObjCInstanceType()))
1196 return;
1197
Douglas Gregor33823722011-06-11 01:09:30 +00001198 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1199 << Method->isInstanceMethod() << Method->getSelector()
1200 << MsgSend->getType();
1201}
1202
1203bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001204 MultiExprArg Args,
1205 Selector Sel,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001206 ArrayRef<SourceLocation> SelectorLocs,
1207 ObjCMethodDecl *Method,
Douglas Gregor33823722011-06-11 01:09:30 +00001208 bool isClassMessage, bool isSuperMessage,
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001209 SourceLocation lbrac, SourceLocation rbrac,
John McCall7decc9e2010-11-18 06:31:45 +00001210 QualType &ReturnType, ExprValueKind &VK) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001211 SourceLocation SelLoc;
1212 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
1213 SelLoc = SelectorLocs.front();
1214 else
1215 SelLoc = lbrac;
1216
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001217 if (!Method) {
Daniel Dunbar83876b42008-09-11 00:04:36 +00001218 // Apply default argument promotion as for (C99 6.5.2.2p6).
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001219 for (unsigned i = 0, e = Args.size(); i != e; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001220 if (Args[i]->isTypeDependent())
1221 continue;
1222
John McCallcc5788c2013-03-04 07:34:02 +00001223 ExprResult result;
1224 if (getLangOpts().DebuggerSupport) {
1225 QualType paramTy; // ignored
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001226 result = checkUnknownAnyArg(SelLoc, Args[i], paramTy);
John McCallcc5788c2013-03-04 07:34:02 +00001227 } else {
1228 result = DefaultArgumentPromotion(Args[i]);
1229 }
1230 if (result.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00001231 return true;
John McCallcc5788c2013-03-04 07:34:02 +00001232 Args[i] = result.take();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001233 }
Daniel Dunbar83876b42008-09-11 00:04:36 +00001234
John McCall31168b02011-06-15 23:02:42 +00001235 unsigned DiagID;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001236 if (getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00001237 DiagID = diag::err_arc_method_not_found;
1238 else
1239 DiagID = isClassMessage ? diag::warn_class_method_not_found
1240 : diag::warn_inst_method_not_found;
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001241 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001242 const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType);
Fariborz Jahanian06499232013-06-18 17:10:58 +00001243 if (OMD && !OMD->isInvalidDecl()) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001244 if (getLangOpts().ObjCAutoRefCount)
1245 DiagID = diag::error_method_not_found_with_typo;
1246 else
1247 DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo
1248 : diag::warn_instance_method_not_found_with_typo;
Fariborz Jahanian75481672013-06-17 17:10:54 +00001249 Selector MatchedSel = OMD->getSelector();
1250 SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00001251 Diag(SelLoc, DiagID)
1252 << Sel<< isClassMessage << MatchedSel
Fariborz Jahanian75481672013-06-17 17:10:54 +00001253 << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString());
1254 }
1255 else
1256 Diag(SelLoc, DiagID)
1257 << Sel << isClassMessage << SourceRange(SelectorLocs.front(),
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00001258 SelectorLocs.back());
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001259 // Find the class to which we are sending this message.
1260 if (ReceiverType->isObjCObjectPointerType()) {
Fariborz Jahanian478536b2013-05-15 15:27:35 +00001261 if (ObjCInterfaceDecl *Class =
1262 ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl())
1263 Diag(Class->getLocation(), diag::note_receiver_class_declared);
Fariborz Jahanian773df4a2013-05-14 23:24:17 +00001264 }
1265 }
John McCall3f4138c2011-07-13 17:56:40 +00001266
1267 // In debuggers, we want to use __unknown_anytype for these
1268 // results so that clients can cast them.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001269 if (getLangOpts().DebuggerSupport) {
John McCall3f4138c2011-07-13 17:56:40 +00001270 ReturnType = Context.UnknownAnyTy;
1271 } else {
1272 ReturnType = Context.getObjCIdType();
1273 }
John McCall7decc9e2010-11-18 06:31:45 +00001274 VK = VK_RValue;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001275 return false;
Daniel Dunbaraa9326c2008-09-11 00:01:56 +00001276 }
Mike Stump11289f42009-09-09 15:08:12 +00001277
Douglas Gregor33823722011-06-11 01:09:30 +00001278 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1279 isSuperMessage);
John McCall7decc9e2010-11-18 06:31:45 +00001280 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump11289f42009-09-09 15:08:12 +00001281
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001282 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian60462092010-04-08 00:30:06 +00001283 // Method might have more arguments than selector indicates. This is due
1284 // to addition of c-style arguments in method.
1285 if (Method->param_size() > Sel.getNumArgs())
1286 NumNamedArgs = Method->param_size();
1287 // FIXME. This need be cleaned up.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001288 if (Args.size() < NumNamedArgs) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001289 Diag(SelLoc, diag::err_typecheck_call_too_few_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001290 << 2 << NumNamedArgs << static_cast<unsigned>(Args.size());
Fariborz Jahanian60462092010-04-08 00:30:06 +00001291 return false;
1292 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001293
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001294 bool IsError = false;
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001295 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001296 // We can't do any type-checking on a type-dependent argument.
1297 if (Args[i]->isTypeDependent())
1298 continue;
1299
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001300 Expr *argExpr = Args[i];
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001301
John McCall4124c492011-10-17 18:40:02 +00001302 ParmVarDecl *param = Method->param_begin()[i];
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001303 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump11289f42009-09-09 15:08:12 +00001304
John McCall4124c492011-10-17 18:40:02 +00001305 // Strip the unbridged-cast placeholder expression off unless it's
1306 // a consumed argument.
1307 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1308 !param->hasAttr<CFConsumedAttr>())
1309 argExpr = stripARCUnbridgedCast(argExpr);
1310
John McCallea0a39e2012-11-14 00:49:39 +00001311 // If the parameter is __unknown_anytype, infer its type
1312 // from the argument.
1313 if (param->getType() == Context.UnknownAnyTy) {
John McCallcc5788c2013-03-04 07:34:02 +00001314 QualType paramType;
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001315 ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType);
John McCallcc5788c2013-03-04 07:34:02 +00001316 if (argE.isInvalid()) {
John McCallea0a39e2012-11-14 00:49:39 +00001317 IsError = true;
John McCallcc5788c2013-03-04 07:34:02 +00001318 } else {
1319 Args[i] = argE.take();
John McCallea0a39e2012-11-14 00:49:39 +00001320
John McCallcc5788c2013-03-04 07:34:02 +00001321 // Update the parameter type in-place.
1322 param->setType(paramType);
1323 }
1324 continue;
John McCallea0a39e2012-11-14 00:49:39 +00001325 }
1326
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001327 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall4124c492011-10-17 18:40:02 +00001328 param->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001329 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001330 return true;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001331
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00001332 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall4124c492011-10-17 18:40:02 +00001333 param);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00001334 ExprResult ArgE = PerformCopyInitialization(Entity, SelLoc, Owned(argExpr));
Douglas Gregor6b7f12c2010-04-21 23:24:10 +00001335 if (ArgE.isInvalid())
1336 IsError = true;
1337 else
1338 Args[i] = ArgE.takeAs<Expr>();
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001339 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001340
1341 // Promote additional arguments to variadic methods.
1342 if (Method->isVariadic()) {
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001343 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001344 if (Args[i]->isTypeDependent())
1345 continue;
1346
Jordy Roseaca01f92012-05-12 17:32:52 +00001347 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
1348 0);
John Wiegley01296292011-04-08 18:41:53 +00001349 IsError |= Arg.isInvalid();
1350 Args[i] = Arg.take();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00001351 }
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001352 } else {
1353 // Check for extra arguments to non-variadic methods.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001354 if (Args.size() != NumNamedArgs) {
Mike Stump11289f42009-09-09 15:08:12 +00001355 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00001356 diag::err_typecheck_call_too_many_args)
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001357 << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size())
Eric Christopher2a5aaff2010-04-16 04:56:46 +00001358 << Method->getSourceRange()
Chris Lattner3b054132008-11-19 05:08:23 +00001359 << SourceRange(Args[NumNamedArgs]->getLocStart(),
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001360 Args.back()->getLocEnd());
Daniel Dunbarce05c8e2008-09-11 00:50:25 +00001361 }
1362 }
1363
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001364 DiagnoseSentinelCalls(Method, SelLoc, Args);
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001365
1366 // Do additional checkings on method.
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00001367 IsError |= CheckObjCMethodCall(
1368 Method, SelLoc,
1369 llvm::makeArrayRef<const Expr *>(Args.data(), Args.size()));
Jean-Daniel Dupas0ae6e672012-01-17 20:03:31 +00001370
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00001371 return IsError;
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001372}
1373
Douglas Gregor486b74e2011-09-27 16:10:05 +00001374bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianb3b1e172011-03-27 19:53:47 +00001375 // 'self' is objc 'self' in an objc method only.
John McCallfe96e0b2011-11-06 09:01:30 +00001376 ObjCMethodDecl *method =
John McCalldec348f72013-05-03 07:33:41 +00001377 dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
John McCallfe96e0b2011-11-06 09:01:30 +00001378 if (!method) return false;
1379
John McCall31168b02011-06-15 23:02:42 +00001380 receiver = receiver->IgnoreParenLValueCasts();
1381 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCallfe96e0b2011-11-06 09:01:30 +00001382 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregor486b74e2011-09-27 16:10:05 +00001383 return true;
1384 return false;
Steve Naroff3f49fee2009-03-04 15:11:40 +00001385}
1386
John McCall526ab472011-10-25 17:37:35 +00001387/// LookupMethodInType - Look up a method in an ObjCObjectType.
1388ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1389 bool isInstance) {
1390 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1391 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1392 // Look it up in the main interface (and categories, etc.)
1393 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1394 return method;
1395
1396 // Okay, look for "private" methods declared in any
1397 // @implementations we've seen.
Anna Zaksc77a3b12012-07-27 19:07:44 +00001398 if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance))
1399 return method;
John McCall526ab472011-10-25 17:37:35 +00001400 }
1401
1402 // Check qualifiers.
1403 for (ObjCObjectType::qual_iterator
1404 i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
1405 if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
1406 return method;
1407
1408 return 0;
1409}
1410
Fariborz Jahanian3dc11ad2011-03-09 20:18:06 +00001411/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1412/// list of a qualified objective pointer type.
1413ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1414 const ObjCObjectPointerType *OPT,
1415 bool Instance)
1416{
1417 ObjCMethodDecl *MD = 0;
1418 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1419 E = OPT->qual_end(); I != E; ++I) {
1420 ObjCProtocolDecl *PROTO = (*I);
1421 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1422 return MD;
1423 }
1424 }
1425 return 0;
1426}
1427
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001428static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1429 if (!Receiver)
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001430 return;
1431
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001432 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver))
1433 Receiver = OVE->getSourceExpr();
1434
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001435 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1436 SourceLocation Loc = RExpr->getLocStart();
1437 QualType T = RExpr->getType();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001438 const ObjCPropertyDecl *PDecl = 0;
1439 const ObjCMethodDecl *GDecl = 0;
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001440 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1441 RExpr = POE->getSyntacticForm();
1442 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1443 if (PRE->isImplicitProperty()) {
1444 GDecl = PRE->getImplicitPropertyGetter();
1445 if (GDecl) {
1446 T = GDecl->getResultType();
1447 }
1448 }
1449 else {
1450 PDecl = PRE->getExplicitProperty();
1451 if (PDecl) {
1452 T = PDecl->getType();
1453 }
1454 }
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001455 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001456 }
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001457 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) {
1458 // See if receiver is a method which envokes a synthesized getter
1459 // backing a 'weak' property.
1460 ObjCMethodDecl *Method = ME->getMethodDecl();
Jordan Rose2bd991a2012-10-10 16:42:54 +00001461 if (Method && Method->getSelector().getNumArgs() == 0) {
1462 PDecl = Method->findPropertyDecl();
Fariborz Jahanian22535de2012-06-04 19:16:34 +00001463 if (PDecl)
1464 T = PDecl->getType();
1465 }
1466 }
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001467
Jordan Rose13d6b712012-09-28 22:21:42 +00001468 if (T.getObjCLifetime() != Qualifiers::OCL_Weak) {
1469 if (!PDecl)
1470 return;
1471 if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak))
1472 return;
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001473 }
Jordan Rose13d6b712012-09-28 22:21:42 +00001474
1475 S.Diag(Loc, diag::warn_receiver_is_weak)
1476 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1477
1478 if (PDecl)
Fariborz Jahaniand155c782012-04-19 23:49:39 +00001479 S.Diag(PDecl->getLocation(), diag::note_property_declare);
Jordan Rose13d6b712012-09-28 22:21:42 +00001480 else if (GDecl)
1481 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
1482
1483 S.Diag(Loc, diag::note_arc_assign_to_strong);
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001484}
1485
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001486/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1487/// objective C interface. This is a property reference expression.
John McCalldadc5752010-08-24 06:29:42 +00001488ExprResult Sema::
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001489HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001490 Expr *BaseExpr, SourceLocation OpLoc,
1491 DeclarationName MemberName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001492 SourceLocation MemberLoc,
1493 SourceLocation SuperLoc, QualType SuperType,
1494 bool Super) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001495 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1496 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Benjamin Kramer1458c1c2012-05-19 16:03:58 +00001497
Benjamin Kramer365082d2012-05-19 16:34:46 +00001498 if (!MemberName.isIdentifier()) {
Douglas Gregord6459312011-04-20 18:19:55 +00001499 Diag(MemberLoc, diag::err_invalid_property_name)
1500 << MemberName << QualType(OPT, 0);
1501 return ExprError();
1502 }
Benjamin Kramer365082d2012-05-19 16:34:46 +00001503
1504 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregord6459312011-04-20 18:19:55 +00001505
Douglas Gregor4123a862011-11-14 22:10:01 +00001506 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1507 : BaseExpr->getSourceRange();
1508 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001509 diag::err_property_not_found_forward_class,
1510 MemberName, BaseRange))
Fariborz Jahanian7cabbe02010-12-16 00:56:28 +00001511 return ExprError();
Douglas Gregor4123a862011-11-14 22:10:01 +00001512
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001513 // Search for a declared property first.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001514 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001515 // Check whether we can reference this property.
1516 if (DiagnoseUseOfDecl(PD, MemberLoc))
1517 return ExprError();
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001518 if (Super)
John McCall526ab472011-10-25 17:37:35 +00001519 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001520 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001521 MemberLoc,
1522 SuperLoc, SuperType));
1523 else
John McCall526ab472011-10-25 17:37:35 +00001524 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001525 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001526 MemberLoc, BaseExpr));
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001527 }
1528 // Check protocols on qualified interfaces.
1529 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1530 E = OPT->qual_end(); I != E; ++I)
1531 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1532 // Check whether we can reference this property.
1533 if (DiagnoseUseOfDecl(PD, MemberLoc))
1534 return ExprError();
Fariborz Jahanianfce89c62012-04-19 21:44:57 +00001535
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001536 if (Super)
John McCall526ab472011-10-25 17:37:35 +00001537 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1538 Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001539 VK_LValue,
1540 OK_ObjCProperty,
1541 MemberLoc,
1542 SuperLoc, SuperType));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001543 else
John McCall526ab472011-10-25 17:37:35 +00001544 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1545 Context.PseudoObjectTy,
John McCall7decc9e2010-11-18 06:31:45 +00001546 VK_LValue,
1547 OK_ObjCProperty,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001548 MemberLoc,
1549 BaseExpr));
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001550 }
1551 // If that failed, look for an "implicit" property by seeing if the nullary
1552 // selector is implemented.
1553
1554 // FIXME: The logic for looking up nullary and unary selectors should be
1555 // shared with the code in ActOnInstanceMessage.
1556
1557 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1558 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001559
1560 // May be founf in property's qualified list.
1561 if (!Getter)
1562 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001563
1564 // If this reference is in an @implementation, check for 'private' methods.
1565 if (!Getter)
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001566 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001567
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001568 if (Getter) {
1569 // Check if we can reference this property.
1570 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1571 return ExprError();
1572 }
1573 // If we found a getter then this may be a valid dot-reference, we
1574 // will look for the matching setter, in case it is needed.
1575 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001576 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1577 PP.getSelectorTable(), Member);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001578 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +00001579
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001580 // May be founf in property's qualified list.
1581 if (!Setter)
1582 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1583
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001584 if (!Setter) {
1585 // If this reference is in an @implementation, also check for 'private'
1586 // methods.
Fariborz Jahanianecbbb6e2010-12-03 23:37:08 +00001587 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001588 }
Fariborz Jahanianb296e332011-03-09 22:17:12 +00001589
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001590 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1591 return ExprError();
1592
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001593 if (Getter || Setter) {
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001594 if (Super)
John McCallb7bd14f2010-12-02 01:19:52 +00001595 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001596 Context.PseudoObjectTy,
1597 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001598 MemberLoc,
1599 SuperLoc, SuperType));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001600 else
John McCallb7bd14f2010-12-02 01:19:52 +00001601 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001602 Context.PseudoObjectTy,
1603 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001604 MemberLoc, BaseExpr));
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001605
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001606 }
1607
1608 // Attempt to correct for typos in property names.
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001609 DeclFilterCCC<ObjCPropertyDecl> Validator;
1610 if (TypoCorrection Corrected = CorrectTypo(
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001611 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001612 NULL, Validator, IFace, false, OPT)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001613 ObjCPropertyDecl *Property =
1614 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001615 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001616 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattner90c58fa2010-04-11 07:51:10 +00001617 << MemberName << QualType(OPT, 0) << TypoResult
1618 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001619 Diag(Property->getLocation(), diag::note_previous_decl)
1620 << Property->getDeclName();
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001621 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1622 TypoResult, MemberLoc,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001623 SuperLoc, SuperType, Super);
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001624 }
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001625 ObjCInterfaceDecl *ClassDeclared;
1626 if (ObjCIvarDecl *Ivar =
1627 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1628 QualType T = Ivar->getType();
1629 if (const ObjCObjectPointerType * OBJPT =
1630 T->getAsObjCInterfacePointerType()) {
Douglas Gregor4123a862011-11-14 22:10:01 +00001631 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001632 diag::err_property_not_as_forward_class,
1633 MemberName, BaseExpr))
Douglas Gregor4123a862011-11-14 22:10:01 +00001634 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001635 }
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001636 Diag(MemberLoc,
1637 diag::err_ivar_access_using_property_syntax_suggest)
1638 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1639 << FixItHint::CreateReplacement(OpLoc, "->");
1640 return ExprError();
Fariborz Jahanian05d389f2011-02-17 01:26:14 +00001641 }
Chris Lattner90c58fa2010-04-11 07:51:10 +00001642
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001643 Diag(MemberLoc, diag::err_property_not_found)
1644 << MemberName << QualType(OPT, 0);
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001645 if (Setter)
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001646 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian0f0b3022010-12-22 19:46:35 +00001647 << MemberName << BaseExpr->getSourceRange();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001648 return ExprError();
Chris Lattner2b1ca5f2010-04-11 07:45:24 +00001649}
1650
1651
1652
John McCalldadc5752010-08-24 06:29:42 +00001653ExprResult Sema::
Chris Lattnera36ec422010-04-11 08:28:14 +00001654ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1655 IdentifierInfo &propertyName,
1656 SourceLocation receiverNameLoc,
1657 SourceLocation propertyNameLoc) {
Mike Stump11289f42009-09-09 15:08:12 +00001658
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001659 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001660 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1661 receiverNameLoc);
Douglas Gregor33823722011-06-11 01:09:30 +00001662
1663 bool IsSuper = false;
Chris Lattnera36ec422010-04-11 08:28:14 +00001664 if (IFace == 0) {
1665 // If the "receiver" is 'super' in a method, handle it as an expression-like
1666 // property reference.
John McCall5f2d5562011-02-03 09:00:02 +00001667 if (receiverNamePtr->isStr("super")) {
Douglas Gregor33823722011-06-11 01:09:30 +00001668 IsSuper = true;
1669
Eli Friedman24af8502012-02-03 22:47:37 +00001670 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnera36ec422010-04-11 08:28:14 +00001671 if (CurMethod->isInstanceMethod()) {
Fariborz Jahanian05e2aaa2013-03-11 22:26:33 +00001672 ObjCInterfaceDecl *Super =
1673 CurMethod->getClassInterface()->getSuperClass();
1674 if (!Super) {
1675 // The current class does not have a superclass.
1676 Diag(receiverNameLoc, diag::error_root_class_cannot_use_super)
1677 << CurMethod->getClassInterface()->getIdentifier();
1678 return ExprError();
1679 }
1680 QualType T = Context.getObjCInterfaceType(Super);
Chris Lattnera36ec422010-04-11 08:28:14 +00001681 T = Context.getObjCObjectPointerType(T);
Chris Lattnera36ec422010-04-11 08:28:14 +00001682
1683 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001684 /*BaseExpr*/0,
1685 SourceLocation()/*OpLoc*/,
1686 &propertyName,
Fariborz Jahanian681c0752010-10-14 16:04:05 +00001687 propertyNameLoc,
1688 receiverNameLoc, T, true);
Chris Lattnera36ec422010-04-11 08:28:14 +00001689 }
Mike Stump11289f42009-09-09 15:08:12 +00001690
Chris Lattnera36ec422010-04-11 08:28:14 +00001691 // Otherwise, if this is a class method, try dispatching to our
1692 // superclass.
1693 IFace = CurMethod->getClassInterface()->getSuperClass();
1694 }
John McCall5f2d5562011-02-03 09:00:02 +00001695 }
Chris Lattnera36ec422010-04-11 08:28:14 +00001696
1697 if (IFace == 0) {
1698 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1699 return ExprError();
1700 }
1701 }
1702
1703 // Search for a declared property first.
Steve Naroff9527bbf2009-03-09 21:12:44 +00001704 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001705 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001706
1707 // If this reference is in an @implementation, check for 'private' methods.
1708 if (!Getter)
1709 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1710 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001711 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001712 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001713
1714 if (Getter) {
1715 // FIXME: refactor/share with ActOnMemberReference().
1716 // Check if we can reference this property.
1717 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1718 return ExprError();
1719 }
Mike Stump11289f42009-09-09 15:08:12 +00001720
Steve Naroff9527bbf2009-03-09 21:12:44 +00001721 // Look for the matching setter, in case it is needed.
Mike Stump11289f42009-09-09 15:08:12 +00001722 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001723 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1724 PP.getSelectorTable(),
1725 &propertyName);
Mike Stump11289f42009-09-09 15:08:12 +00001726
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001727 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001728 if (!Setter) {
1729 // If this reference is in an @implementation, also check for 'private'
1730 // methods.
1731 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1732 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001733 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001734 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001735 }
1736 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1559d67b2009-07-21 00:06:20 +00001737 if (!Setter)
1738 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff9527bbf2009-03-09 21:12:44 +00001739
1740 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1741 return ExprError();
1742
1743 if (Getter || Setter) {
Douglas Gregor33823722011-06-11 01:09:30 +00001744 if (IsSuper)
1745 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001746 Context.PseudoObjectTy,
1747 VK_LValue, OK_ObjCProperty,
Douglas Gregor33823722011-06-11 01:09:30 +00001748 propertyNameLoc,
1749 receiverNameLoc,
1750 Context.getObjCInterfaceType(IFace)));
1751
John McCallb7bd14f2010-12-02 01:19:52 +00001752 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001753 Context.PseudoObjectTy,
1754 VK_LValue, OK_ObjCProperty,
John McCallb7bd14f2010-12-02 01:19:52 +00001755 propertyNameLoc,
1756 receiverNameLoc, IFace));
Steve Naroff9527bbf2009-03-09 21:12:44 +00001757 }
1758 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1759 << &propertyName << Context.getObjCInterfaceType(IFace));
1760}
1761
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001762namespace {
1763
1764class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1765 public:
1766 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1767 // Determine whether "super" is acceptable in the current context.
1768 if (Method && Method->getClassInterface())
1769 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1770 }
1771
1772 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1773 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1774 candidate.isKeyword("super");
1775 }
1776};
1777
1778}
1779
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001780Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001781 IdentifierInfo *Name,
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001782 SourceLocation NameLoc,
1783 bool IsSuper,
Douglas Gregore5798dc2010-04-21 20:38:13 +00001784 bool HasTrailingDot,
John McCallba7bf592010-08-24 05:47:05 +00001785 ParsedType &ReceiverType) {
1786 ReceiverType = ParsedType();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001787
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001788 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor57756ea2010-10-14 22:11:03 +00001789 // messaging super. If the identifier is "super" and there is a
1790 // trailing dot, it's an instance message.
1791 if (IsSuper && S->isInObjcMethodScope())
1792 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001793
1794 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1795 LookupName(Result, S);
1796
1797 switch (Result.getResultKind()) {
1798 case LookupResult::NotFound:
Douglas Gregorca7136b2010-04-19 20:09:36 +00001799 // Normal name lookup didn't find anything. If we're in an
1800 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor57756ea2010-10-14 22:11:03 +00001801 // FIXME: This is a hack. Ivar lookup should be part of normal
1802 // lookup.
Douglas Gregorca7136b2010-04-19 20:09:36 +00001803 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidis3a8de5b2011-11-09 00:22:48 +00001804 if (!Method->getClassInterface()) {
1805 // Fall back: let the parser try to parse it as an instance message.
1806 return ObjCInstanceMessage;
1807 }
1808
Douglas Gregorca7136b2010-04-19 20:09:36 +00001809 ObjCInterfaceDecl *ClassDeclared;
1810 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1811 ClassDeclared))
1812 return ObjCInstanceMessage;
1813 }
Douglas Gregor57756ea2010-10-14 22:11:03 +00001814
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001815 // Break out; we'll perform typo correction below.
1816 break;
1817
1818 case LookupResult::NotFoundInCurrentInstantiation:
1819 case LookupResult::FoundOverloaded:
1820 case LookupResult::FoundUnresolvedValue:
1821 case LookupResult::Ambiguous:
1822 Result.suppressDiagnostics();
1823 return ObjCInstanceMessage;
1824
1825 case LookupResult::Found: {
Fariborz Jahanian14889fc2011-02-08 00:23:07 +00001826 // If the identifier is a class or not, and there is a trailing dot,
1827 // it's an instance message.
1828 if (HasTrailingDot)
1829 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001830 // We found something. If it's a type, then we have a class
1831 // message. Otherwise, it's an instance message.
1832 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregore5798dc2010-04-21 20:38:13 +00001833 QualType T;
1834 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1835 T = Context.getObjCInterfaceType(Class);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001836 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) {
Douglas Gregore5798dc2010-04-21 20:38:13 +00001837 T = Context.getTypeDeclType(Type);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +00001838 DiagnoseUseOfDecl(Type, NameLoc);
1839 }
1840 else
Douglas Gregore5798dc2010-04-21 20:38:13 +00001841 return ObjCInstanceMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001842
Douglas Gregore5798dc2010-04-21 20:38:13 +00001843 // We have a class message, and T is the type we're
1844 // messaging. Build source-location information for it.
1845 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +00001846 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregore5798dc2010-04-21 20:38:13 +00001847 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001848 }
1849 }
1850
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001851 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001852 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1853 Result.getLookupKind(), S, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001854 Validator)) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001855 if (Corrected.isKeyword()) {
1856 // If we've found the keyword "super" (the only keyword that would be
1857 // returned by CorrectTypo), this is a send to super.
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001858 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001859 << Name << Corrected.getCorrection()
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001860 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001861 return ObjCSuperMessage;
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001862 } else if (ObjCInterfaceDecl *Class =
1863 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1864 // If we found a declaration, correct when it refers to an Objective-C
1865 // class.
1866 Diag(NameLoc, diag::err_unknown_receiver_suggest)
1867 << Name << Corrected.getCorrection()
1868 << FixItHint::CreateReplacement(SourceRange(NameLoc),
1869 Class->getNameAsString());
1870 Diag(Class->getLocation(), diag::note_previous_decl)
1871 << Corrected.getCorrection();
1872
1873 QualType T = Context.getObjCInterfaceType(Class);
1874 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1875 ReceiverType = CreateParsedType(T, TSInfo);
1876 return ObjCClassMessage;
Douglas Gregor8aa4ebf2010-04-14 02:46:37 +00001877 }
1878 }
1879
1880 // Fall back: let the parser try to parse it as an instance message.
1881 return ObjCInstanceMessage;
1882}
Steve Naroff9527bbf2009-03-09 21:12:44 +00001883
John McCalldadc5752010-08-24 06:29:42 +00001884ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001885 SourceLocation SuperLoc,
1886 Selector Sel,
1887 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00001888 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00001889 SourceLocation RBracLoc,
1890 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001891 // Determine whether we are inside a method or not.
Eli Friedman24af8502012-02-03 22:47:37 +00001892 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregor4fdba132010-04-21 20:01:04 +00001893 if (!Method) {
1894 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1895 return ExprError();
1896 }
Chris Lattnera3fc41d2008-01-04 22:32:30 +00001897
Douglas Gregor4fdba132010-04-21 20:01:04 +00001898 ObjCInterfaceDecl *Class = Method->getClassInterface();
1899 if (!Class) {
1900 Diag(SuperLoc, diag::error_no_super_class_message)
1901 << Method->getDeclName();
1902 return ExprError();
1903 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001904
Douglas Gregor4fdba132010-04-21 20:01:04 +00001905 ObjCInterfaceDecl *Super = Class->getSuperClass();
1906 if (!Super) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001907 // The current class does not have a superclass.
Ted Kremenek499897b2011-01-23 17:21:34 +00001908 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1909 << Class->getIdentifier();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001910 return ExprError();
Chris Lattnerc2ebb032010-04-12 05:38:43 +00001911 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001912
Douglas Gregor4fdba132010-04-21 20:01:04 +00001913 // We are in a method whose class has a superclass, so 'super'
1914 // is acting as a keyword.
Jordan Rose2afd6612012-10-19 16:05:26 +00001915 if (Method->getSelector() == Sel)
1916 getCurFunction()->ObjCShouldCallSuper = false;
Nico Weber715abaf2011-08-22 17:25:57 +00001917
Jordan Rose2afd6612012-10-19 16:05:26 +00001918 if (Method->isInstanceMethod()) {
Douglas Gregor4fdba132010-04-21 20:01:04 +00001919 // Since we are in an instance method, this is an instance
1920 // message to the superclass instance.
1921 QualType SuperTy = Context.getObjCInterfaceType(Super);
1922 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCallb268a282010-08-23 23:25:46 +00001923 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001924 Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001925 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001926 }
Douglas Gregor4fdba132010-04-21 20:01:04 +00001927
1928 // Since we are in a class method, this is a class message to
1929 // the superclass.
1930 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1931 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00001932 SuperLoc, Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001933 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001934}
1935
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00001936
1937ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1938 bool isSuperReceiver,
1939 SourceLocation Loc,
1940 Selector Sel,
1941 ObjCMethodDecl *Method,
1942 MultiExprArg Args) {
1943 TypeSourceInfo *receiverTypeInfo = 0;
1944 if (!ReceiverType.isNull())
1945 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1946
1947 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1948 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1949 Sel, Method, Loc, Loc, Loc, Args,
1950 /*isImplicit=*/true);
1951
1952}
1953
Ted Kremeneke65b0862012-03-06 20:05:56 +00001954static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1955 unsigned DiagID,
1956 bool (*refactor)(const ObjCMessageExpr *,
1957 const NSAPI &, edit::Commit &)) {
1958 SourceLocation MsgLoc = Msg->getExprLoc();
1959 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
1960 return;
1961
1962 SourceManager &SM = S.SourceMgr;
1963 edit::Commit ECommit(SM, S.LangOpts);
1964 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1965 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1966 << Msg->getSelector() << Msg->getSourceRange();
1967 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1968 if (!ECommit.isCommitable())
1969 return;
1970 for (edit::Commit::edit_iterator
1971 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1972 const edit::Commit::Edit &Edit = *I;
1973 switch (Edit.Kind) {
1974 case edit::Commit::Act_Insert:
1975 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1976 Edit.Text,
1977 Edit.BeforePrev));
1978 break;
1979 case edit::Commit::Act_InsertFromRange:
1980 Builder.AddFixItHint(
1981 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1982 Edit.getInsertFromRange(SM),
1983 Edit.BeforePrev));
1984 break;
1985 case edit::Commit::Act_Remove:
1986 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1987 break;
1988 }
1989 }
1990 }
1991}
1992
1993static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1994 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1995 edit::rewriteObjCRedundantCallWithLiteral);
1996}
1997
Douglas Gregor0c78ad92010-04-21 19:57:20 +00001998/// \brief Build an Objective-C class message expression.
1999///
2000/// This routine takes care of both normal class messages and
2001/// class messages to the superclass.
2002///
2003/// \param ReceiverTypeInfo Type source information that describes the
2004/// receiver of this message. This may be NULL, in which case we are
2005/// sending to the superclass and \p SuperLoc must be a valid source
2006/// location.
2007
2008/// \param ReceiverType The type of the object receiving the
2009/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
2010/// type as that refers to. For a superclass send, this is the type of
2011/// the superclass.
2012///
2013/// \param SuperLoc The location of the "super" keyword in a
2014/// superclass message.
2015///
2016/// \param Sel The selector to which the message is being sent.
2017///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002018/// \param Method The method that this class message is invoking, if
2019/// already known.
2020///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002021/// \param LBracLoc The location of the opening square bracket ']'.
2022///
James Dennettffad8b72012-06-22 08:10:18 +00002023/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002024///
James Dennettffad8b72012-06-22 08:10:18 +00002025/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002026ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002027 QualType ReceiverType,
2028 SourceLocation SuperLoc,
2029 Selector Sel,
2030 ObjCMethodDecl *Method,
2031 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002032 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002033 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002034 MultiExprArg ArgsIn,
2035 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002036 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregorabf4a3e2010-09-16 01:51:54 +00002037 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002038 if (LBracLoc.isInvalid()) {
2039 Diag(Loc, diag::err_missing_open_square_message_send)
2040 << FixItHint::CreateInsertion(Loc, "[");
2041 LBracLoc = Loc;
2042 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002043 SourceLocation SelLoc;
2044 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2045 SelLoc = SelectorLocs.front();
2046 else
2047 SelLoc = Loc;
2048
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002049 if (ReceiverType->isDependentType()) {
2050 // If the receiver type is dependent, we can't type-check anything
2051 // at this point. Build a dependent expression.
2052 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002053 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002054 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCall7decc9e2010-11-18 06:31:45 +00002055 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
2056 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002057 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002058 makeArrayRef(Args, NumArgs),RBracLoc,
2059 isImplicit));
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002060 }
Chris Lattnerc2ebb032010-04-12 05:38:43 +00002061
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002062 // Find the class to which we are sending this message.
2063 ObjCInterfaceDecl *Class = 0;
John McCall8b07ec22010-05-15 11:32:37 +00002064 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
2065 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002066 Diag(Loc, diag::err_invalid_receiver_class_message)
2067 << ReceiverType;
2068 return ExprError();
Steve Naroffe2177fb2008-07-25 19:39:00 +00002069 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002070 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanianc27cd1b2011-10-15 19:18:36 +00002071 // objc++ diagnoses during typename annotation.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002072 if (!getLangOpts().CPlusPlus)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002073 (void)DiagnoseUseOfDecl(Class, SelLoc);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002074 // Find the method we are messaging.
Douglas Gregorb5186b12010-04-22 17:01:48 +00002075 if (!Method) {
Douglas Gregor4123a862011-11-14 22:10:01 +00002076 SourceRange TypeRange
2077 = SuperLoc.isValid()? SourceRange(SuperLoc)
2078 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002079 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002080 (getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002081 ? diag::err_arc_receiver_forward_class
2082 : diag::warn_receiver_forward_class),
2083 TypeRange)) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002084 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorb5186b12010-04-22 17:01:48 +00002085 Method = LookupFactoryMethodInGlobalPool(Sel,
2086 SourceRange(LBracLoc, RBracLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00002087 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002088 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
2089 << Method->getDeclName();
2090 }
2091 if (!Method)
2092 Method = Class->lookupClassMethod(Sel);
2093
2094 // If we have an implementation in scope, check "private" methods.
2095 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002096 Method = Class->lookupPrivateClassMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002097
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002098 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002099 return ExprError();
Fariborz Jahanian1bd844d2009-05-08 23:02:36 +00002100 }
Mike Stump11289f42009-09-09 15:08:12 +00002101
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002102 // Check the argument types and determine the result type.
2103 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002104 ExprValueKind VK = VK_RValue;
2105
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002106 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002107 Expr **Args = ArgsIn.data();
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002108 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2109 Sel, SelectorLocs,
Fariborz Jahanian6ce25c02012-08-31 17:03:18 +00002110 Method, true,
Douglas Gregor33823722011-06-11 01:09:30 +00002111 SuperLoc.isValid(), LBracLoc, RBracLoc,
2112 ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002113 return ExprError();
Ted Kremeneka3a37ae2008-06-24 15:50:53 +00002114
Douglas Gregoraec93c62011-01-11 03:23:19 +00002115 if (Method && !Method->getResultType()->isVoidType() &&
2116 RequireCompleteType(LBracLoc, Method->getResultType(),
2117 diag::err_illegal_message_expr_incomplete_type))
2118 return ExprError();
2119
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002120 // Construct the appropriate ObjCMessageExpr.
Ted Kremeneke65b0862012-03-06 20:05:56 +00002121 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002122 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002123 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002124 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002125 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002126 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002127 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002128 else {
John McCall7decc9e2010-11-18 06:31:45 +00002129 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002130 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002131 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002132 RBracLoc, isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002133 if (!isImplicit)
2134 checkCocoaAPI(*this, Result);
2135 }
Douglas Gregoraae38d62010-05-22 05:17:18 +00002136 return MaybeBindToTemporary(Result);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002137}
2138
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002139// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002140// ArgExprs is optional - if it is present, the number of expressions
2141// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002142ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor3e972002010-09-15 23:19:31 +00002143 ParsedType Receiver,
2144 Selector Sel,
2145 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002146 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor3e972002010-09-15 23:19:31 +00002147 SourceLocation RBracLoc,
2148 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002149 TypeSourceInfo *ReceiverTypeInfo;
2150 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2151 if (ReceiverType.isNull())
2152 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00002153
Mike Stump11289f42009-09-09 15:08:12 +00002154
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002155 if (!ReceiverTypeInfo)
2156 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2157
2158 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorb5186b12010-04-22 17:01:48 +00002159 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002160 LBracLoc, SelectorLocs, RBracLoc, Args);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002161}
2162
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002163ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2164 QualType ReceiverType,
2165 SourceLocation Loc,
2166 Selector Sel,
2167 ObjCMethodDecl *Method,
2168 MultiExprArg Args) {
2169 return BuildInstanceMessage(Receiver, ReceiverType,
2170 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2171 Sel, Method, Loc, Loc, Loc, Args,
2172 /*isImplicit=*/true);
2173}
2174
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002175/// \brief Build an Objective-C instance message expression.
2176///
2177/// This routine takes care of both normal instance messages and
2178/// instance messages to the superclass instance.
2179///
2180/// \param Receiver The expression that computes the object that will
2181/// receive this message. This may be empty, in which case we are
2182/// sending to the superclass instance and \p SuperLoc must be a valid
2183/// source location.
2184///
2185/// \param ReceiverType The (static) type of the object receiving the
2186/// message. When a \p Receiver expression is provided, this is the
2187/// same type as that expression. For a superclass instance send, this
2188/// is a pointer to the type of the superclass.
2189///
2190/// \param SuperLoc The location of the "super" keyword in a
2191/// superclass instance message.
2192///
2193/// \param Sel The selector to which the message is being sent.
2194///
Douglas Gregorb5186b12010-04-22 17:01:48 +00002195/// \param Method The method that this instance message is invoking, if
2196/// already known.
2197///
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002198/// \param LBracLoc The location of the opening square bracket ']'.
2199///
James Dennettffad8b72012-06-22 08:10:18 +00002200/// \param RBracLoc The location of the closing square bracket ']'.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002201///
James Dennettffad8b72012-06-22 08:10:18 +00002202/// \param ArgsIn The message arguments.
John McCalldadc5752010-08-24 06:29:42 +00002203ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002204 QualType ReceiverType,
2205 SourceLocation SuperLoc,
2206 Selector Sel,
2207 ObjCMethodDecl *Method,
2208 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002209 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisd0039e52010-12-10 20:08:27 +00002210 SourceLocation RBracLoc,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002211 MultiExprArg ArgsIn,
2212 bool isImplicit) {
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002213 // The location of the receiver.
2214 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002215 SourceRange RecRange =
2216 SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange();
2217 SourceLocation SelLoc;
2218 if (!SelectorLocs.empty() && SelectorLocs.front().isValid())
2219 SelLoc = SelectorLocs.front();
2220 else
2221 SelLoc = Loc;
2222
Douglas Gregore9bba4f2010-09-15 14:51:05 +00002223 if (LBracLoc.isInvalid()) {
2224 Diag(Loc, diag::err_missing_open_square_message_send)
2225 << FixItHint::CreateInsertion(Loc, "[");
2226 LBracLoc = Loc;
2227 }
2228
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002229 // If we have a receiver expression, perform appropriate promotions
2230 // and determine receiver type.
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002231 if (Receiver) {
John McCall4124c492011-10-17 18:40:02 +00002232 if (Receiver->hasPlaceholderType()) {
Douglas Gregord8fb1e32011-12-01 01:37:36 +00002233 ExprResult Result;
2234 if (Receiver->getType() == Context.UnknownAnyTy)
2235 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2236 else
2237 Result = CheckPlaceholderExpr(Receiver);
2238 if (Result.isInvalid()) return ExprError();
2239 Receiver = Result.take();
John McCall4124c492011-10-17 18:40:02 +00002240 }
2241
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002242 if (Receiver->isTypeDependent()) {
2243 // If the receiver is type-dependent, we can't type-check anything
2244 // at this point. Build a dependent expression.
2245 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002246 Expr **Args = ArgsIn.data();
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002247 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2248 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00002249 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002250 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis59ad1e32011-10-03 06:36:45 +00002251 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002252 RBracLoc, isImplicit));
Douglas Gregorc298ffc2010-04-22 16:44:27 +00002253 }
2254
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002255 // If necessary, apply function/array conversion to the receiver.
2256 // C99 6.7.5.3p[7,8].
John Wiegley01296292011-04-08 18:41:53 +00002257 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2258 if (Result.isInvalid())
2259 return ExprError();
2260 Receiver = Result.take();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002261 ReceiverType = Receiver->getType();
John McCall80c93a02013-03-01 09:20:14 +00002262
2263 // If the receiver is an ObjC pointer, a block pointer, or an
2264 // __attribute__((NSObject)) pointer, we don't need to do any
2265 // special conversion in order to look up a receiver.
2266 if (ReceiverType->isObjCRetainableType()) {
2267 // do nothing
2268 } else if (!getLangOpts().ObjCAutoRefCount &&
2269 !Context.getObjCIdType().isNull() &&
2270 (ReceiverType->isPointerType() ||
2271 ReceiverType->isIntegerType())) {
2272 // Implicitly convert integers and pointers to 'id' but emit a warning.
2273 // But not in ARC.
2274 Diag(Loc, diag::warn_bad_receiver_type)
2275 << ReceiverType
2276 << Receiver->getSourceRange();
2277 if (ReceiverType->isPointerType()) {
2278 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2279 CK_CPointerToObjCPointerCast).take();
2280 } else {
2281 // TODO: specialized warning on null receivers?
2282 bool IsNull = Receiver->isNullPointerConstant(Context,
2283 Expr::NPC_ValueDependentIsNull);
2284 CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer;
2285 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2286 Kind).take();
2287 }
2288 ReceiverType = Receiver->getType();
2289 } else if (getLangOpts().CPlusPlus) {
2290 ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver);
2291 if (result.isUsable()) {
2292 Receiver = result.take();
2293 ReceiverType = Receiver->getType();
2294 }
2295 }
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002296 }
2297
John McCall80c93a02013-03-01 09:20:14 +00002298 // There's a somewhat weird interaction here where we assume that we
2299 // won't actually have a method unless we also don't need to do some
2300 // of the more detailed type-checking on the receiver.
2301
Douglas Gregorb5186b12010-04-22 17:01:48 +00002302 if (!Method) {
2303 // Handle messages to id.
Fariborz Jahanian32e59ba2010-08-10 18:10:50 +00002304 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002305 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorb5186b12010-04-22 17:01:48 +00002306 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2307 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002308 SourceRange(LBracLoc, RBracLoc),
2309 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002310 if (!Method)
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002311 Method = LookupFactoryMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002312 SourceRange(LBracLoc,RBracLoc),
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002313 receiverIsId);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002314 } else if (ReceiverType->isObjCClassType() ||
2315 ReceiverType->isObjCQualifiedClassType()) {
2316 // Handle messages to Class.
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002317 // We allow sending a message to a qualified Class ("Class<foo>"), which
2318 // is ok as long as one of the protocols implements the selector (if not, warn).
2319 if (const ObjCObjectPointerType *QClassTy
2320 = ReceiverType->getAsObjCQualifiedClassType()) {
2321 // Search protocols for class methods.
2322 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2323 if (!Method) {
2324 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2325 // warn if instance method found for a Class message.
2326 if (Method) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002327 Diag(SelLoc, diag::warn_instance_method_on_class_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002328 << Method->getSelector() << Sel;
Ted Kremenek59b10db2012-02-27 22:55:11 +00002329 Diag(Method->getLocation(), diag::note_method_declared_at)
2330 << Method->getDeclName();
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002331 }
Steve Naroff3f49fee2009-03-04 15:11:40 +00002332 }
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002333 } else {
2334 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2335 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2336 // First check the public methods in the class interface.
2337 Method = ClassDecl->lookupClassMethod(Sel);
2338
2339 if (!Method)
Anna Zaksc77a3b12012-07-27 19:07:44 +00002340 Method = ClassDecl->lookupPrivateClassMethod(Sel);
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002341 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002342 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002343 return ExprError();
2344 }
2345 if (!Method) {
2346 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor486b74e2011-09-27 16:10:05 +00002347 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002348 Method = LookupFactoryMethodInGlobalPool(Sel,
2349 SourceRange(LBracLoc, RBracLoc),
2350 true);
2351 if (!Method) {
2352 // If no class (factory) method was found, check if an _instance_
2353 // method of the same name exists in the root class only.
2354 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002355 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002356 true);
2357 if (Method)
2358 if (const ObjCInterfaceDecl *ID =
2359 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2360 if (ID->getSuperClass())
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002361 Diag(SelLoc, diag::warn_root_inst_method_not_found)
Fariborz Jahanian3b9819b2011-04-06 18:40:08 +00002362 << Sel << SourceRange(LBracLoc, RBracLoc);
2363 }
2364 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002365 }
2366 }
2367 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002368 } else {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002369 ObjCInterfaceDecl* ClassDecl = 0;
2370
2371 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2372 // long as one of the protocols implements the selector (if not, warn).
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002373 // And as long as message is not deprecated/unavailable (warn if it is).
Douglas Gregorb5186b12010-04-22 17:01:48 +00002374 if (const ObjCObjectPointerType *QIdTy
2375 = ReceiverType->getAsObjCQualifiedIdType()) {
2376 // Search protocols for instance methods.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002377 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2378 if (!Method)
2379 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002380 if (Method && DiagnoseUseOfDecl(Method, SelLoc))
Fariborz Jahaniana245f192012-06-23 18:39:57 +00002381 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002382 } else if (const ObjCObjectPointerType *OCIType
2383 = ReceiverType->getAsObjCInterfacePointerType()) {
2384 // We allow sending a message to a pointer to an interface (an object).
2385 ClassDecl = OCIType->getInterfaceDecl();
John McCall31168b02011-06-15 23:02:42 +00002386
Douglas Gregor4123a862011-11-14 22:10:01 +00002387 // Try to complete the type. Under ARC, this is a hard error from which
2388 // we don't try to recover.
2389 const ObjCInterfaceDecl *forwardClass = 0;
2390 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002391 getLangOpts().ObjCAutoRefCount
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002392 ? diag::err_arc_receiver_forward_instance
2393 : diag::warn_receiver_forward_instance,
2394 Receiver? Receiver->getSourceRange()
2395 : SourceRange(SuperLoc))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002396 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregor4123a862011-11-14 22:10:01 +00002397 return ExprError();
2398
2399 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanianc934de62012-02-03 01:02:44 +00002400 Diag(Receiver ? Receiver->getLocStart()
2401 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002402 Method = 0;
2403 } else {
2404 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCall31168b02011-06-15 23:02:42 +00002405 }
Douglas Gregorb5186b12010-04-22 17:01:48 +00002406
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002407 if (!Method)
Douglas Gregorb5186b12010-04-22 17:01:48 +00002408 // Search protocol qualifiers.
Fariborz Jahanianb296e332011-03-09 22:17:12 +00002409 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2410
Douglas Gregorb5186b12010-04-22 17:01:48 +00002411 if (!Method) {
2412 // If we have implementations in scope, check "private" methods.
Anna Zaksc77a3b12012-07-27 19:07:44 +00002413 Method = ClassDecl->lookupPrivateMethod(Sel);
Douglas Gregorb5186b12010-04-22 17:01:48 +00002414
David Blaikiebbafb8a2012-03-11 07:00:24 +00002415 if (!Method && getLangOpts().ObjCAutoRefCount) {
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002416 Diag(SelLoc, diag::err_arc_may_not_respond)
2417 << OCIType->getPointeeType() << Sel << RecRange
Fariborz Jahanian32c13502012-11-28 01:27:44 +00002418 << SourceRange(SelectorLocs.front(), SelectorLocs.back());
John McCall31168b02011-06-15 23:02:42 +00002419 return ExprError();
2420 }
2421
Douglas Gregor486b74e2011-09-27 16:10:05 +00002422 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorb5186b12010-04-22 17:01:48 +00002423 // If we still haven't found a method, look in the global pool. This
2424 // behavior isn't very desirable, however we need it for GCC
2425 // compatibility. FIXME: should we deviate??
2426 if (OCIType->qual_empty()) {
2427 Method = LookupInstanceMethodInGlobalPool(Sel,
Jordy Roseaca01f92012-05-12 17:32:52 +00002428 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +00002429 if (Method && !forwardClass)
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002430 Diag(SelLoc, diag::warn_maynot_respond)
2431 << OCIType->getInterfaceDecl()->getIdentifier()
2432 << Sel << RecRange;
Douglas Gregorb5186b12010-04-22 17:01:48 +00002433 }
2434 }
2435 }
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002436 if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass))
Douglas Gregorb5186b12010-04-22 17:01:48 +00002437 return ExprError();
John McCallfec112d2011-09-09 06:11:02 +00002438 } else {
John McCall80c93a02013-03-01 09:20:14 +00002439 // Reject other random receiver types (e.g. structs).
2440 Diag(Loc, diag::err_bad_receiver_type)
2441 << ReceiverType << Receiver->getSourceRange();
2442 return ExprError();
Douglas Gregorb5186b12010-04-22 17:01:48 +00002443 }
Douglas Gregor9a129192010-04-21 00:45:42 +00002444 }
Chris Lattner6b946cc2008-07-21 05:57:44 +00002445 }
Mike Stump11289f42009-09-09 15:08:12 +00002446
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002447 // Check the message arguments.
2448 unsigned NumArgs = ArgsIn.size();
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00002449 Expr **Args = ArgsIn.data();
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002450 QualType ReturnType;
John McCall7decc9e2010-11-18 06:31:45 +00002451 ExprValueKind VK = VK_RValue;
Fariborz Jahanian68500912010-12-01 01:07:24 +00002452 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2453 ReceiverType->isObjCQualifiedClassType());
Dmitri Gribenko2a40f082013-05-10 00:27:15 +00002454 if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs),
2455 Sel, SelectorLocs, Method,
Douglas Gregor33823722011-06-11 01:09:30 +00002456 ClassMessage, SuperLoc.isValid(),
John McCall7decc9e2010-11-18 06:31:45 +00002457 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002458 return ExprError();
Fariborz Jahanian18e02752010-06-16 19:56:08 +00002459
Douglas Gregoraec93c62011-01-11 03:23:19 +00002460 if (Method && !Method->getResultType()->isVoidType() &&
2461 RequireCompleteType(LBracLoc, Method->getResultType(),
2462 diag::err_illegal_message_expr_incomplete_type))
2463 return ExprError();
Douglas Gregor9a129192010-04-21 00:45:42 +00002464
John McCall31168b02011-06-15 23:02:42 +00002465 // In ARC, forbid the user from sending messages to
2466 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002467 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00002468 ObjCMethodFamily family =
2469 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2470 switch (family) {
2471 case OMF_init:
2472 if (Method)
2473 checkInitMethod(Method, ReceiverType);
2474
2475 case OMF_None:
2476 case OMF_alloc:
2477 case OMF_copy:
Nico Weber1fb82662011-08-28 22:35:17 +00002478 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002479 case OMF_mutableCopy:
2480 case OMF_new:
2481 case OMF_self:
2482 break;
2483
2484 case OMF_dealloc:
2485 case OMF_retain:
2486 case OMF_release:
2487 case OMF_autorelease:
2488 case OMF_retainCount:
Argyrios Kyrtzidisbcf2bdc2013-05-01 00:24:09 +00002489 Diag(SelLoc, diag::err_arc_illegal_explicit_message)
2490 << Sel << RecRange;
John McCall31168b02011-06-15 23:02:42 +00002491 break;
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002492
2493 case OMF_performSelector:
2494 if (Method && NumArgs >= 1) {
2495 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2496 Selector ArgSel = SelExp->getSelector();
2497 ObjCMethodDecl *SelMethod =
2498 LookupInstanceMethodInGlobalPool(ArgSel,
2499 SelExp->getSourceRange());
2500 if (!SelMethod)
2501 SelMethod =
2502 LookupFactoryMethodInGlobalPool(ArgSel,
2503 SelExp->getSourceRange());
2504 if (SelMethod) {
2505 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2506 switch (SelFamily) {
2507 case OMF_alloc:
2508 case OMF_copy:
2509 case OMF_mutableCopy:
2510 case OMF_new:
2511 case OMF_self:
2512 case OMF_init:
2513 // Issue error, unless ns_returns_not_retained.
2514 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2515 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002516 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002517 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002518 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2519 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002520 }
2521 break;
2522 default:
2523 // +0 call. OK. unless ns_returns_retained.
2524 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2525 // selector names a +1 method
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002526 Diag(SelLoc,
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002527 diag::err_arc_perform_selector_retains);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002528 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2529 << SelMethod->getDeclName();
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002530 }
2531 break;
2532 }
2533 }
2534 } else {
2535 // error (may leak).
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002536 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002537 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2538 }
2539 }
2540 break;
John McCall31168b02011-06-15 23:02:42 +00002541 }
2542 }
2543
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002544 // Construct the appropriate ObjCMessageExpr instance.
John McCall31168b02011-06-15 23:02:42 +00002545 ObjCMessageExpr *Result;
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002546 if (SuperLoc.isValid())
John McCall7decc9e2010-11-18 06:31:45 +00002547 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregoraae38d62010-05-22 05:17:18 +00002548 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002549 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002550 makeArrayRef(Args, NumArgs), RBracLoc,
2551 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002552 else {
John McCall7decc9e2010-11-18 06:31:45 +00002553 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002554 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +00002555 makeArrayRef(Args, NumArgs), RBracLoc,
2556 isImplicit);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002557 if (!isImplicit)
2558 checkCocoaAPI(*this, Result);
2559 }
John McCall31168b02011-06-15 23:02:42 +00002560
David Blaikiebbafb8a2012-03-11 07:00:24 +00002561 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahaniand155c782012-04-19 23:49:39 +00002562 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian6bd22262012-04-04 20:05:25 +00002563
John McCall31168b02011-06-15 23:02:42 +00002564 // In ARC, annotate delegate init calls.
2565 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregor486b74e2011-09-27 16:10:05 +00002566 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCall31168b02011-06-15 23:02:42 +00002567 // Only consider init calls *directly* in init implementations,
2568 // not within blocks.
2569 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2570 if (method && method->getMethodFamily() == OMF_init) {
2571 // The implicit assignment to self means we also don't want to
2572 // consume the result.
2573 Result->setDelegateInitCall(true);
2574 return Owned(Result);
2575 }
2576 }
2577
2578 // In ARC, check for message sends which are likely to introduce
2579 // retain cycles.
2580 checkRetainCycles(Result);
Jordan Rose22487652012-10-11 16:06:21 +00002581
2582 if (!isImplicit && Method) {
2583 if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) {
2584 bool IsWeak =
2585 Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak;
2586 if (!IsWeak && Sel.isUnarySelector())
2587 IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak;
2588
2589 if (IsWeak) {
2590 DiagnosticsEngine::Level Level =
2591 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
2592 LBracLoc);
2593 if (Level != DiagnosticsEngine::Ignored)
2594 getCurFunction()->recordUseOfWeak(Result, Prop);
2595
2596 }
2597 }
2598 }
John McCall31168b02011-06-15 23:02:42 +00002599 }
2600
Douglas Gregoraae38d62010-05-22 05:17:18 +00002601 return MaybeBindToTemporary(Result);
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002602}
2603
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002604static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) {
2605 if (ObjCSelectorExpr *OSE =
2606 dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) {
2607 Selector Sel = OSE->getSelector();
2608 SourceLocation Loc = OSE->getAtLoc();
2609 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
2610 = S.ReferencedSelectors.find(Sel);
2611 if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc)
2612 S.ReferencedSelectors.erase(Pos);
2613 }
2614}
2615
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002616// ActOnInstanceMessage - used for both unary and keyword messages.
2617// ArgExprs is optional - if it is present, the number of expressions
2618// is obtained from Sel.getNumArgs().
John McCalldadc5752010-08-24 06:29:42 +00002619ExprResult Sema::ActOnInstanceMessage(Scope *S,
2620 Expr *Receiver,
2621 Selector Sel,
2622 SourceLocation LBracLoc,
Argyrios Kyrtzidisf934ec82011-10-03 06:36:17 +00002623 ArrayRef<SourceLocation> SelectorLocs,
John McCalldadc5752010-08-24 06:29:42 +00002624 SourceLocation RBracLoc,
2625 MultiExprArg Args) {
Douglas Gregor0c78ad92010-04-21 19:57:20 +00002626 if (!Receiver)
2627 return ExprError();
Argyrios Kyrtzidis336cc8b2013-02-15 18:34:15 +00002628
2629 // A ParenListExpr can show up while doing error recovery with invalid code.
2630 if (isa<ParenListExpr>(Receiver)) {
2631 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver);
2632 if (Result.isInvalid()) return ExprError();
2633 Receiver = Result.take();
2634 }
Fariborz Jahanian17748062013-01-22 19:05:17 +00002635
2636 if (RespondsToSelectorSel.isNull()) {
2637 IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector");
2638 RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId);
2639 }
2640 if (Sel == RespondsToSelectorSel)
Fariborz Jahanian02447d82013-01-22 18:35:43 +00002641 RemoveSelectorFromWarningCache(*this, Args[0]);
2642
John McCallb268a282010-08-23 23:25:46 +00002643 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorb5186b12010-04-22 17:01:48 +00002644 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002645 LBracLoc, SelectorLocs, RBracLoc, Args);
Chris Lattnera3fc41d2008-01-04 22:32:30 +00002646}
Chris Lattner2a3569b2008-04-07 05:30:13 +00002647
John McCall31168b02011-06-15 23:02:42 +00002648enum ARCConversionTypeClass {
John McCalle4fe2452011-10-01 01:01:08 +00002649 /// int, void, struct A
John McCall31168b02011-06-15 23:02:42 +00002650 ACTC_none,
John McCalle4fe2452011-10-01 01:01:08 +00002651
2652 /// id, void (^)()
John McCall31168b02011-06-15 23:02:42 +00002653 ACTC_retainable,
John McCalle4fe2452011-10-01 01:01:08 +00002654
2655 /// id*, id***, void (^*)(),
2656 ACTC_indirectRetainable,
2657
2658 /// void* might be a normal C type, or it might a CF type.
2659 ACTC_voidPtr,
2660
2661 /// struct A*
2662 ACTC_coreFoundation
John McCall31168b02011-06-15 23:02:42 +00002663};
John McCalle4fe2452011-10-01 01:01:08 +00002664static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2665 return (ACTC == ACTC_retainable ||
2666 ACTC == ACTC_coreFoundation ||
2667 ACTC == ACTC_voidPtr);
2668}
2669static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2670 return ACTC == ACTC_none ||
2671 ACTC == ACTC_voidPtr ||
2672 ACTC == ACTC_coreFoundation;
2673}
2674
John McCall31168b02011-06-15 23:02:42 +00002675static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCalle4fe2452011-10-01 01:01:08 +00002676 bool isIndirect = false;
John McCall31168b02011-06-15 23:02:42 +00002677
2678 // Ignore an outermost reference type.
John McCalle4fe2452011-10-01 01:01:08 +00002679 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCall31168b02011-06-15 23:02:42 +00002680 type = ref->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002681 isIndirect = true;
2682 }
John McCall31168b02011-06-15 23:02:42 +00002683
2684 // Drill through pointers and arrays recursively.
2685 while (true) {
2686 if (const PointerType *ptr = type->getAs<PointerType>()) {
2687 type = ptr->getPointeeType();
John McCalle4fe2452011-10-01 01:01:08 +00002688
2689 // The first level of pointer may be the innermost pointer on a CF type.
2690 if (!isIndirect) {
2691 if (type->isVoidType()) return ACTC_voidPtr;
2692 if (type->isRecordType()) return ACTC_coreFoundation;
2693 }
John McCall31168b02011-06-15 23:02:42 +00002694 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2695 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2696 } else {
2697 break;
2698 }
John McCalle4fe2452011-10-01 01:01:08 +00002699 isIndirect = true;
John McCall31168b02011-06-15 23:02:42 +00002700 }
2701
John McCalle4fe2452011-10-01 01:01:08 +00002702 if (isIndirect) {
2703 if (type->isObjCARCBridgableType())
2704 return ACTC_indirectRetainable;
2705 return ACTC_none;
2706 }
2707
2708 if (type->isObjCARCBridgableType())
2709 return ACTC_retainable;
2710
2711 return ACTC_none;
John McCall31168b02011-06-15 23:02:42 +00002712}
2713
2714namespace {
John McCalle4fe2452011-10-01 01:01:08 +00002715 /// A result from the cast checker.
2716 enum ACCResult {
2717 /// Cannot be casted.
2718 ACC_invalid,
2719
2720 /// Can be safely retained or not retained.
2721 ACC_bottom,
2722
2723 /// Can be casted at +0.
2724 ACC_plusZero,
2725
2726 /// Can be casted at +1.
2727 ACC_plusOne
2728 };
2729 ACCResult merge(ACCResult left, ACCResult right) {
2730 if (left == right) return left;
2731 if (left == ACC_bottom) return right;
2732 if (right == ACC_bottom) return left;
2733 return ACC_invalid;
2734 }
2735
2736 /// A checker which white-lists certain expressions whose conversion
2737 /// to or from retainable type would otherwise be forbidden in ARC.
2738 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2739 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2740
John McCall31168b02011-06-15 23:02:42 +00002741 ASTContext &Context;
John McCalle4fe2452011-10-01 01:01:08 +00002742 ARCConversionTypeClass SourceClass;
2743 ARCConversionTypeClass TargetClass;
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002744 bool Diagnose;
John McCalle4fe2452011-10-01 01:01:08 +00002745
2746 static bool isCFType(QualType type) {
2747 // Someday this can use ns_bridged. For now, it has to do this.
2748 return type->isCARCBridgableType();
John McCall31168b02011-06-15 23:02:42 +00002749 }
John McCalle4fe2452011-10-01 01:01:08 +00002750
2751 public:
2752 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002753 ARCConversionTypeClass target, bool diagnose)
2754 : Context(Context), SourceClass(source), TargetClass(target),
2755 Diagnose(diagnose) {}
John McCalle4fe2452011-10-01 01:01:08 +00002756
2757 using super::Visit;
2758 ACCResult Visit(Expr *e) {
2759 return super::Visit(e->IgnoreParens());
2760 }
2761
2762 ACCResult VisitStmt(Stmt *s) {
2763 return ACC_invalid;
2764 }
2765
2766 /// Null pointer constants can be casted however you please.
2767 ACCResult VisitExpr(Expr *e) {
2768 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2769 return ACC_bottom;
2770 return ACC_invalid;
2771 }
2772
2773 /// Objective-C string literals can be safely casted.
2774 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2775 // If we're casting to any retainable type, go ahead. Global
2776 // strings are immune to retains, so this is bottom.
2777 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2778
2779 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002780 }
2781
John McCalle4fe2452011-10-01 01:01:08 +00002782 /// Look through certain implicit and explicit casts.
2783 ACCResult VisitCastExpr(CastExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002784 switch (e->getCastKind()) {
2785 case CK_NullToPointer:
John McCalle4fe2452011-10-01 01:01:08 +00002786 return ACC_bottom;
2787
John McCall31168b02011-06-15 23:02:42 +00002788 case CK_NoOp:
2789 case CK_LValueToRValue:
2790 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00002791 case CK_CPointerToObjCPointerCast:
2792 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002793 case CK_AnyPointerToBlockPointerCast:
2794 return Visit(e->getSubExpr());
John McCalle4fe2452011-10-01 01:01:08 +00002795
John McCall31168b02011-06-15 23:02:42 +00002796 default:
John McCalle4fe2452011-10-01 01:01:08 +00002797 return ACC_invalid;
John McCall31168b02011-06-15 23:02:42 +00002798 }
2799 }
John McCalle4fe2452011-10-01 01:01:08 +00002800
2801 /// Look through unary extension.
2802 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002803 return Visit(e->getSubExpr());
2804 }
John McCalle4fe2452011-10-01 01:01:08 +00002805
2806 /// Ignore the LHS of a comma operator.
2807 ACCResult VisitBinComma(BinaryOperator *e) {
John McCall31168b02011-06-15 23:02:42 +00002808 return Visit(e->getRHS());
2809 }
John McCalle4fe2452011-10-01 01:01:08 +00002810
2811 /// Conditional operators are okay if both sides are okay.
2812 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2813 ACCResult left = Visit(e->getTrueExpr());
2814 if (left == ACC_invalid) return ACC_invalid;
2815 return merge(left, Visit(e->getFalseExpr()));
John McCall31168b02011-06-15 23:02:42 +00002816 }
John McCalle4fe2452011-10-01 01:01:08 +00002817
John McCallfe96e0b2011-11-06 09:01:30 +00002818 /// Look through pseudo-objects.
2819 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2820 // If we're getting here, we should always have a result.
2821 return Visit(e->getResultExpr());
2822 }
2823
John McCalle4fe2452011-10-01 01:01:08 +00002824 /// Statement expressions are okay if their result expression is okay.
2825 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCall31168b02011-06-15 23:02:42 +00002826 return Visit(e->getSubStmt()->body_back());
2827 }
John McCall31168b02011-06-15 23:02:42 +00002828
John McCalle4fe2452011-10-01 01:01:08 +00002829 /// Some declaration references are okay.
2830 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2831 // References to global constants from system headers are okay.
2832 // These are things like 'kCFStringTransformToLatin'. They are
2833 // can also be assumed to be immune to retains.
2834 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2835 if (isAnyRetainable(TargetClass) &&
2836 isAnyRetainable(SourceClass) &&
2837 var &&
2838 var->getStorageClass() == SC_Extern &&
2839 var->getType().isConstQualified() &&
2840 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2841 return ACC_bottom;
2842 }
2843
2844 // Nothing else.
2845 return ACC_invalid;
Fariborz Jahanian78876372011-06-21 17:38:29 +00002846 }
John McCalle4fe2452011-10-01 01:01:08 +00002847
2848 /// Some calls are okay.
2849 ACCResult VisitCallExpr(CallExpr *e) {
2850 if (FunctionDecl *fn = e->getDirectCallee())
2851 if (ACCResult result = checkCallToFunction(fn))
2852 return result;
2853
2854 return super::VisitCallExpr(e);
2855 }
2856
2857 ACCResult checkCallToFunction(FunctionDecl *fn) {
2858 // Require a CF*Ref return type.
2859 if (!isCFType(fn->getResultType()))
2860 return ACC_invalid;
2861
2862 if (!isAnyRetainable(TargetClass))
2863 return ACC_invalid;
2864
2865 // Honor an explicit 'not retained' attribute.
2866 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2867 return ACC_plusZero;
2868
2869 // Honor an explicit 'retained' attribute, except that for
2870 // now we're not going to permit implicit handling of +1 results,
2871 // because it's a bit frightening.
2872 if (fn->hasAttr<CFReturnsRetainedAttr>())
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00002873 return Diagnose ? ACC_plusOne
2874 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00002875
2876 // Recognize this specific builtin function, which is used by CFSTR.
2877 unsigned builtinID = fn->getBuiltinID();
2878 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2879 return ACC_bottom;
2880
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00002881 // Otherwise, don't do anything implicit with an unaudited function.
2882 if (!fn->hasAttr<CFAuditedTransferAttr>())
2883 return ACC_invalid;
2884
Fariborz Jahanian36986c62012-07-27 22:37:07 +00002885 // Otherwise, it's +0 unless it follows the create convention.
2886 if (ento::coreFoundation::followsCreateRule(fn))
2887 return Diagnose ? ACC_plusOne
2888 : ACC_invalid; // ACC_plusOne if we start accepting this
John McCalle4fe2452011-10-01 01:01:08 +00002889
John McCalle4fe2452011-10-01 01:01:08 +00002890 return ACC_plusZero;
2891 }
2892
2893 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2894 return checkCallToMethod(e->getMethodDecl());
2895 }
2896
2897 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2898 ObjCMethodDecl *method;
2899 if (e->isExplicitProperty())
2900 method = e->getExplicitProperty()->getGetterMethodDecl();
2901 else
2902 method = e->getImplicitPropertyGetter();
2903 return checkCallToMethod(method);
2904 }
2905
2906 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2907 if (!method) return ACC_invalid;
2908
2909 // Check for message sends to functions returning CF types. We
2910 // just obey the Cocoa conventions with these, even though the
2911 // return type is CF.
2912 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2913 return ACC_invalid;
2914
2915 // If the method is explicitly marked not-retained, it's +0.
2916 if (method->hasAttr<CFReturnsNotRetainedAttr>())
2917 return ACC_plusZero;
2918
2919 // If the method is explicitly marked as returning retained, or its
2920 // selector follows a +1 Cocoa convention, treat it as +1.
2921 if (method->hasAttr<CFReturnsRetainedAttr>())
2922 return ACC_plusOne;
2923
2924 switch (method->getSelector().getMethodFamily()) {
2925 case OMF_alloc:
2926 case OMF_copy:
2927 case OMF_mutableCopy:
2928 case OMF_new:
2929 return ACC_plusOne;
2930
2931 default:
2932 // Otherwise, treat it as +0.
2933 return ACC_plusZero;
Fariborz Jahanian9b83be82011-06-21 19:42:38 +00002934 }
2935 }
John McCalle4fe2452011-10-01 01:01:08 +00002936 };
Fariborz Jahanian4ad56862011-06-20 20:54:42 +00002937}
2938
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00002939bool Sema::isKnownName(StringRef name) {
2940 if (name.empty())
2941 return false;
2942 LookupResult R(*this, &Context.Idents.get(name), SourceLocation(),
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00002943 Sema::LookupOrdinaryName);
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00002944 return LookupName(R, TUScope, false);
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00002945}
2946
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002947static void addFixitForObjCARCConversion(Sema &S,
2948 DiagnosticBuilder &DiagB,
2949 Sema::CheckedConversionKind CCK,
2950 SourceLocation afterLParen,
2951 QualType castType,
2952 Expr *castExpr,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00002953 Expr *realCast,
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002954 const char *bridgeKeyword,
2955 const char *CFBridgeName) {
2956 // We handle C-style and implicit casts here.
2957 switch (CCK) {
2958 case Sema::CCK_ImplicitConversion:
2959 case Sema::CCK_CStyleCast:
Fariborz Jahanianf0738712013-02-22 22:02:53 +00002960 case Sema::CCK_OtherCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002961 break;
2962 case Sema::CCK_FunctionalCast:
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002963 return;
2964 }
2965
2966 if (CFBridgeName) {
Fariborz Jahanianf0738712013-02-22 22:02:53 +00002967 if (CCK == Sema::CCK_OtherCast) {
2968 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
2969 SourceRange range(NCE->getOperatorLoc(),
2970 NCE->getAngleBrackets().getEnd());
2971 SmallString<32> BridgeCall;
2972
2973 SourceManager &SM = S.getSourceManager();
2974 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
2975 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
2976 BridgeCall += ' ';
2977
2978 BridgeCall += CFBridgeName;
2979 DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall));
2980 }
2981 return;
2982 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002983 Expr *castedE = castExpr;
2984 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2985 castedE = CCE->getSubExpr();
2986 castedE = castedE->IgnoreImpCasts();
2987 SourceRange range = castedE->getSourceRange();
Jordan Rose288c4212012-06-07 01:10:31 +00002988
2989 SmallString<32> BridgeCall;
2990
2991 SourceManager &SM = S.getSourceManager();
2992 char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1));
2993 if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts()))
2994 BridgeCall += ' ';
2995
2996 BridgeCall += CFBridgeName;
2997
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00002998 if (isa<ParenExpr>(castedE)) {
2999 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003000 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003001 } else {
Jordan Rose288c4212012-06-07 01:10:31 +00003002 BridgeCall += '(';
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003003 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
Jordan Rose288c4212012-06-07 01:10:31 +00003004 BridgeCall));
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003005 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3006 S.PP.getLocForEndOfToken(range.getEnd()),
3007 ")"));
3008 }
3009 return;
3010 }
3011
3012 if (CCK == Sema::CCK_CStyleCast) {
3013 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003014 } else if (CCK == Sema::CCK_OtherCast) {
3015 if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) {
3016 std::string castCode = "(";
3017 castCode += bridgeKeyword;
3018 castCode += castType.getAsString();
3019 castCode += ")";
3020 SourceRange Range(NCE->getOperatorLoc(),
3021 NCE->getAngleBrackets().getEnd());
3022 DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode));
3023 }
Argyrios Kyrtzidis6aa70e22012-02-16 17:31:07 +00003024 } else {
3025 std::string castCode = "(";
3026 castCode += bridgeKeyword;
3027 castCode += castType.getAsString();
3028 castCode += ")";
3029 Expr *castedE = castExpr->IgnoreImpCasts();
3030 SourceRange range = castedE->getSourceRange();
3031 if (isa<ParenExpr>(castedE)) {
3032 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3033 castCode));
3034 } else {
3035 castCode += "(";
3036 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
3037 castCode));
3038 DiagB.AddFixItHint(FixItHint::CreateInsertion(
3039 S.PP.getLocForEndOfToken(range.getEnd()),
3040 ")"));
3041 }
3042 }
3043}
3044
John McCall4124c492011-10-17 18:40:02 +00003045static void
3046diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
3047 QualType castType, ARCConversionTypeClass castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003048 Expr *castExpr, Expr *realCast,
3049 ARCConversionTypeClass exprACTC,
John McCall4124c492011-10-17 18:40:02 +00003050 Sema::CheckedConversionKind CCK) {
John McCall31168b02011-06-15 23:02:42 +00003051 SourceLocation loc =
John McCalle4fe2452011-10-01 01:01:08 +00003052 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00003053
John McCall4124c492011-10-17 18:40:02 +00003054 if (S.makeUnavailableInSystemHeader(loc,
John McCalle4fe2452011-10-01 01:01:08 +00003055 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCall31168b02011-06-15 23:02:42 +00003056 return;
John McCall4124c492011-10-17 18:40:02 +00003057
3058 QualType castExprType = castExpr->getType();
John McCall31168b02011-06-15 23:02:42 +00003059
John McCall640767f2011-06-17 06:50:50 +00003060 unsigned srcKind = 0;
John McCall31168b02011-06-15 23:02:42 +00003061 switch (exprACTC) {
John McCalle4fe2452011-10-01 01:01:08 +00003062 case ACTC_none:
3063 case ACTC_coreFoundation:
3064 case ACTC_voidPtr:
3065 srcKind = (castExprType->isPointerType() ? 1 : 0);
3066 break;
3067 case ACTC_retainable:
3068 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
3069 break;
3070 case ACTC_indirectRetainable:
3071 srcKind = 4;
3072 break;
John McCall31168b02011-06-15 23:02:42 +00003073 }
3074
John McCall4124c492011-10-17 18:40:02 +00003075 // Check whether this could be fixed with a bridge cast.
3076 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
3077 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCall31168b02011-06-15 23:02:42 +00003078
John McCall4124c492011-10-17 18:40:02 +00003079 // Bridge from an ARC type to a CF type.
3080 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003081
John McCall4124c492011-10-17 18:40:02 +00003082 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3083 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3084 << 2 // of C pointer type
3085 << castExprType
3086 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
3087 << castType
3088 << castRange
3089 << castExpr->getSourceRange();
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003090 bool br = S.isKnownName("CFBridgingRelease");
Jordan Rose4502b532012-07-31 01:07:43 +00003091 ACCResult CreateRule =
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003092 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003093 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003094 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003095 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003096 DiagnosticBuilder DiagB =
3097 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3098 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
3099
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003100 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003101 castType, castExpr, realCast, "__bridge ", 0);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003102 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003103 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003104 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003105 DiagnosticBuilder DiagB =
3106 (CCK == Sema::CCK_OtherCast && !br) ?
3107 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType :
3108 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3109 diag::note_arc_bridge_transfer)
3110 << castExprType << br;
3111
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003112 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003113 castType, castExpr, realCast, "__bridge_transfer ",
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003114 br ? "CFBridgingRelease" : 0);
3115 }
John McCall4124c492011-10-17 18:40:02 +00003116
3117 return;
3118 }
3119
3120 // Bridge from a CF type to an ARC type.
3121 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003122 bool br = S.isKnownName("CFBridgingRetain");
John McCall4124c492011-10-17 18:40:02 +00003123 S.Diag(loc, diag::err_arc_cast_requires_bridge)
3124 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
3125 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
3126 << castExprType
3127 << 2 // to C pointer type
3128 << castType
3129 << castRange
3130 << castExpr->getSourceRange();
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003131 ACCResult CreateRule =
3132 ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr);
Jordan Rose4502b532012-07-31 01:07:43 +00003133 assert(CreateRule != ACC_bottom && "This cast should already be accepted.");
Fariborz Jahanianae5bbfc2012-07-27 23:55:46 +00003134 if (CreateRule != ACC_plusOne)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003135 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003136 DiagnosticBuilder DiagB =
3137 (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge)
3138 : S.Diag(noteLoc, diag::note_arc_cstyle_bridge);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003139 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003140 castType, castExpr, realCast, "__bridge ", 0);
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003141 }
Fariborz Jahanianf7759e82012-07-28 18:59:49 +00003142 if (CreateRule != ACC_plusZero)
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003143 {
Fariborz Jahanianac2d0822013-02-22 01:22:48 +00003144 DiagnosticBuilder DiagB =
3145 (CCK == Sema::CCK_OtherCast && !br) ?
3146 S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType :
3147 S.Diag(br ? castExpr->getExprLoc() : noteLoc,
3148 diag::note_arc_bridge_retained)
3149 << castType << br;
3150
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003151 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003152 castType, castExpr, realCast, "__bridge_retained ",
Fariborz Jahanian84c97ca2012-07-27 21:34:23 +00003153 br ? "CFBridgingRetain" : 0);
3154 }
John McCall4124c492011-10-17 18:40:02 +00003155
3156 return;
John McCall31168b02011-06-15 23:02:42 +00003157 }
3158
John McCall4124c492011-10-17 18:40:02 +00003159 S.Diag(loc, diag::err_arc_mismatched_cast)
3160 << (CCK != Sema::CCK_ImplicitConversion)
3161 << srcKind << castExprType << castType
John McCall31168b02011-06-15 23:02:42 +00003162 << castRange << castExpr->getSourceRange();
3163}
3164
John McCall4124c492011-10-17 18:40:02 +00003165Sema::ARCConversionResult
3166Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003167 Expr *&castExpr, CheckedConversionKind CCK,
3168 bool DiagnoseCFAudited) {
John McCall4124c492011-10-17 18:40:02 +00003169 QualType castExprType = castExpr->getType();
3170
3171 // For the purposes of the classification, we assume reference types
3172 // will bind to temporaries.
3173 QualType effCastType = castType;
3174 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
3175 effCastType = ref->getPointeeType();
3176
3177 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
3178 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003179 if (exprACTC == castACTC) {
3180 // check for viablity and report error if casting an rvalue to a
3181 // life-time qualifier.
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003182 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003183 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanian244b1872011-10-29 00:06:10 +00003184 (castType != castExprType)) {
3185 const Type *DT = castType.getTypePtr();
3186 QualType QDT = castType;
3187 // We desugar some types but not others. We ignore those
3188 // that cannot happen in a cast; i.e. auto, and those which
3189 // should not be de-sugared; i.e typedef.
3190 if (const ParenType *PT = dyn_cast<ParenType>(DT))
3191 QDT = PT->desugar();
3192 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
3193 QDT = TP->desugar();
3194 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
3195 QDT = AT->desugar();
3196 if (QDT != castType &&
3197 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
3198 SourceLocation loc =
3199 (castRange.isValid() ? castRange.getBegin()
3200 : castExpr->getExprLoc());
3201 Diag(loc, diag::err_arc_nolifetime_behavior);
3202 }
Fariborz Jahanian2fa646d2011-10-28 20:06:07 +00003203 }
3204 return ACR_okay;
3205 }
3206
John McCall4124c492011-10-17 18:40:02 +00003207 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
3208
3209 // Allow all of these types to be cast to integer types (but not
3210 // vice-versa).
3211 if (castACTC == ACTC_none && castType->isIntegralType(Context))
3212 return ACR_okay;
3213
3214 // Allow casts between pointers to lifetime types (e.g., __strong id*)
3215 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
3216 // must be explicit.
3217 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
3218 return ACR_okay;
3219 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
3220 CCK != CCK_ImplicitConversion)
3221 return ACR_okay;
3222
Fariborz Jahanian36986c62012-07-27 22:37:07 +00003223 switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) {
John McCall4124c492011-10-17 18:40:02 +00003224 // For invalid casts, fall through.
3225 case ACC_invalid:
3226 break;
3227
3228 // Do nothing for both bottom and +0.
3229 case ACC_bottom:
3230 case ACC_plusZero:
3231 return ACR_okay;
3232
3233 // If the result is +1, consume it here.
3234 case ACC_plusOne:
3235 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3236 CK_ARCConsumeObject, castExpr,
3237 0, VK_RValue);
3238 ExprNeedsCleanups = true;
3239 return ACR_okay;
3240 }
3241
3242 // If this is a non-implicit cast from id or block type to a
3243 // CoreFoundation type, delay complaining in case the cast is used
3244 // in an acceptable context.
3245 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3246 CCK != CCK_ImplicitConversion)
3247 return ACR_unbridged;
3248
Fariborz Jahanian25eef192013-07-31 21:40:51 +00003249 // Do not issue "bridge cast" diagnostic when implicit casting
3250 // a retainable object to a CF type parameter belonging to an audited
3251 // CF API function. Let caller issue a normal type mismatched diagnostic
3252 // instead.
3253 if (!DiagnoseCFAudited || exprACTC != ACTC_retainable ||
3254 castACTC != ACTC_coreFoundation)
3255 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3256 castExpr, castExpr, exprACTC, CCK);
John McCall4124c492011-10-17 18:40:02 +00003257 return ACR_okay;
3258}
3259
3260/// Given that we saw an expression with the ARCUnbridgedCastTy
3261/// placeholder type, complain bitterly.
3262void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3263 // We expect the spurious ImplicitCastExpr to already have been stripped.
3264 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3265 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3266
3267 SourceRange castRange;
3268 QualType castType;
3269 CheckedConversionKind CCK;
3270
3271 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3272 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3273 castType = cast->getTypeAsWritten();
3274 CCK = CCK_CStyleCast;
3275 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3276 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3277 castType = cast->getTypeAsWritten();
3278 CCK = CCK_OtherCast;
3279 } else {
3280 castType = cast->getType();
3281 CCK = CCK_ImplicitConversion;
3282 }
3283
3284 ARCConversionTypeClass castACTC =
3285 classifyTypeForARCConversion(castType.getNonReferenceType());
3286
3287 Expr *castExpr = realCast->getSubExpr();
3288 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3289
3290 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
Fariborz Jahanianf0738712013-02-22 22:02:53 +00003291 castExpr, realCast, ACTC_retainable, CCK);
John McCall4124c492011-10-17 18:40:02 +00003292}
3293
3294/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3295/// type, remove the placeholder cast.
3296Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3297 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3298
3299 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3300 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3301 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3302 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3303 assert(uo->getOpcode() == UO_Extension);
3304 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3305 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3306 sub->getValueKind(), sub->getObjectKind(),
3307 uo->getOperatorLoc());
3308 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3309 assert(!gse->isResultDependent());
3310
3311 unsigned n = gse->getNumAssocs();
3312 SmallVector<Expr*, 4> subExprs(n);
3313 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3314 for (unsigned i = 0; i != n; ++i) {
3315 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3316 Expr *sub = gse->getAssocExpr(i);
3317 if (i == gse->getResultIndex())
3318 sub = stripARCUnbridgedCast(sub);
3319 subExprs[i] = sub;
3320 }
3321
3322 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3323 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003324 subTypes, subExprs,
3325 gse->getDefaultLoc(),
John McCall4124c492011-10-17 18:40:02 +00003326 gse->getRParenLoc(),
3327 gse->containsUnexpandedParameterPack(),
3328 gse->getResultIndex());
3329 } else {
3330 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3331 return cast<ImplicitCastExpr>(e)->getSubExpr();
3332 }
3333}
3334
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003335bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3336 QualType exprType) {
3337 QualType canCastType =
3338 Context.getCanonicalType(castType).getUnqualifiedType();
3339 QualType canExprType =
3340 Context.getCanonicalType(exprType).getUnqualifiedType();
3341 if (isa<ObjCObjectPointerType>(canCastType) &&
3342 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3343 canExprType->isObjCObjectPointerType()) {
3344 if (const ObjCObjectPointerType *ObjT =
3345 canExprType->getAs<ObjCObjectPointerType>())
Richard Smith802c4b72012-08-23 06:16:52 +00003346 if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl())
3347 return !ObjI->isArcWeakrefUnavailable();
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00003348 }
3349 return true;
3350}
3351
John McCall4db5c3c2011-07-07 06:58:02 +00003352/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3353static Expr *maybeUndoReclaimObject(Expr *e) {
3354 // For now, we just undo operands that are *immediately* reclaim
3355 // expressions, which prevents the vast majority of potential
3356 // problems here. To catch them all, we'd need to rebuild arbitrary
3357 // value-propagating subexpressions --- we can't reliably rebuild
3358 // in-place because of expression sharing.
3359 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall2d637d22011-09-10 06:18:15 +00003360 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall4db5c3c2011-07-07 06:58:02 +00003361 return ice->getSubExpr();
3362
3363 return e;
3364}
3365
John McCall31168b02011-06-15 23:02:42 +00003366ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3367 ObjCBridgeCastKind Kind,
3368 SourceLocation BridgeKeywordLoc,
3369 TypeSourceInfo *TSInfo,
3370 Expr *SubExpr) {
John McCalleb075542011-08-26 00:48:42 +00003371 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3372 if (SubResult.isInvalid()) return ExprError();
3373 SubExpr = SubResult.take();
3374
John McCall31168b02011-06-15 23:02:42 +00003375 QualType T = TSInfo->getType();
3376 QualType FromType = SubExpr->getType();
3377
John McCall9320b872011-09-09 05:25:32 +00003378 CastKind CK;
3379
John McCall31168b02011-06-15 23:02:42 +00003380 bool MustConsume = false;
3381 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3382 // Okay: we'll build a dependent expression type.
John McCall9320b872011-09-09 05:25:32 +00003383 CK = CK_Dependent;
John McCall31168b02011-06-15 23:02:42 +00003384 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3385 // Casting CF -> id
John McCall9320b872011-09-09 05:25:32 +00003386 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3387 : CK_CPointerToObjCPointerCast);
John McCall31168b02011-06-15 23:02:42 +00003388 switch (Kind) {
3389 case OBC_Bridge:
3390 break;
3391
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003392 case OBC_BridgeRetained: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003393 bool br = isKnownName("CFBridgingRelease");
John McCall31168b02011-06-15 23:02:42 +00003394 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3395 << 2
3396 << FromType
3397 << (T->isBlockPointerType()? 1 : 0)
3398 << T
3399 << SubExpr->getSourceRange()
3400 << Kind;
3401 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3402 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3403 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003404 << FromType << br
John McCall31168b02011-06-15 23:02:42 +00003405 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003406 br ? "CFBridgingRelease "
3407 : "__bridge_transfer ");
John McCall31168b02011-06-15 23:02:42 +00003408
3409 Kind = OBC_Bridge;
3410 break;
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003411 }
John McCall31168b02011-06-15 23:02:42 +00003412
3413 case OBC_BridgeTransfer:
3414 // We must consume the Objective-C object produced by the cast.
3415 MustConsume = true;
3416 break;
3417 }
3418 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3419 // Okay: id -> CF
John McCall9320b872011-09-09 05:25:32 +00003420 CK = CK_BitCast;
John McCall31168b02011-06-15 23:02:42 +00003421 switch (Kind) {
3422 case OBC_Bridge:
John McCall4db5c3c2011-07-07 06:58:02 +00003423 // Reclaiming a value that's going to be __bridge-casted to CF
3424 // is very dangerous, so we don't do it.
3425 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCall31168b02011-06-15 23:02:42 +00003426 break;
3427
3428 case OBC_BridgeRetained:
3429 // Produce the object before casting it.
3430 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall2d637d22011-09-10 06:18:15 +00003431 CK_ARCProduceObject,
John McCall31168b02011-06-15 23:02:42 +00003432 SubExpr, 0, VK_RValue);
3433 break;
3434
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003435 case OBC_BridgeTransfer: {
Argyrios Kyrtzidis273c7c42012-06-01 00:10:47 +00003436 bool br = isKnownName("CFBridgingRetain");
John McCall31168b02011-06-15 23:02:42 +00003437 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3438 << (FromType->isBlockPointerType()? 1 : 0)
3439 << FromType
3440 << 2
3441 << T
3442 << SubExpr->getSourceRange()
3443 << Kind;
3444
3445 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3446 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3447 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003448 << T << br
3449 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3450 br ? "CFBridgingRetain " : "__bridge_retained");
John McCall31168b02011-06-15 23:02:42 +00003451
3452 Kind = OBC_Bridge;
3453 break;
3454 }
Fariborz Jahanian30febeb2012-02-01 22:56:20 +00003455 }
John McCall31168b02011-06-15 23:02:42 +00003456 } else {
3457 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3458 << FromType << T << Kind
3459 << SubExpr->getSourceRange()
3460 << TSInfo->getTypeLoc().getSourceRange();
3461 return ExprError();
3462 }
3463
John McCall9320b872011-09-09 05:25:32 +00003464 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCall31168b02011-06-15 23:02:42 +00003465 BridgeKeywordLoc,
3466 TSInfo, SubExpr);
3467
3468 if (MustConsume) {
3469 ExprNeedsCleanups = true;
John McCall2d637d22011-09-10 06:18:15 +00003470 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCall31168b02011-06-15 23:02:42 +00003471 0, VK_RValue);
3472 }
3473
3474 return Result;
3475}
3476
3477ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3478 SourceLocation LParenLoc,
3479 ObjCBridgeCastKind Kind,
3480 SourceLocation BridgeKeywordLoc,
3481 ParsedType Type,
3482 SourceLocation RParenLoc,
3483 Expr *SubExpr) {
3484 TypeSourceInfo *TSInfo = 0;
3485 QualType T = GetTypeFromParser(Type, &TSInfo);
3486 if (!TSInfo)
3487 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3488 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3489 SubExpr);
3490}