blob: 24f4437b61ae860b208eb244ff2db08b04259275 [file] [log] [blame]
Chris Lattner85a932e2008-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000016#include "clang/Sema/Scope.h"
John McCall26743b22011-02-03 09:00:02 +000017#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000018#include "clang/Sema/Initialization.h"
John McCall2cf031d2011-10-01 01:01:08 +000019#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenekebcb57a2012-03-06 20:05:56 +000020#include "clang/Edit/Rewriters.h"
21#include "clang/Edit/Commit.h"
Chris Lattner85a932e2008-01-04 22:32:30 +000022#include "clang/AST/ASTContext.h"
23#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000024#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000026#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000027#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000028#include "clang/Lex/Preprocessor.h"
29
Chris Lattner85a932e2008-01-04 22:32:30 +000030using namespace clang;
John McCall26743b22011-02-03 09:00:02 +000031using namespace sema;
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +000032using llvm::makeArrayRef;
Chris Lattner85a932e2008-01-04 22:32:30 +000033
John McCallf312b1e2010-08-26 23:41:50 +000034ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 Expr **strings,
36 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000037 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
Chris Lattnerf4b136f2009-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 Lattner39c28bb2009-02-18 06:48:40 +000043 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000044
Chris Lattnerf4b136f2009-02-18 06:13:04 +000045 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000047 // Concatenate objc strings.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000048 SmallString<128> StrBuf;
Chris Lattner5f9e2722011-07-23 10:55:15 +000049 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000050
Chris Lattner726e1682009-02-18 05:49:11 +000051 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000052 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000053
Douglas Gregor5cee1192011-07-27 05:40:30 +000054 // ObjC strings can't be wide or UTF.
55 if (!S->isAscii()) {
Chris Lattnerf4b136f2009-02-18 06:13:04 +000056 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
58 return true;
59 }
Mike Stump1eb44332009-09-09 15:08:12 +000060
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +000061 // Append the string.
62 StrBuf += S->getString();
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattner39c28bb2009-02-18 06:48:40 +000064 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattner85a932e2008-01-04 22:32:30 +000066 }
Mike Stump1eb44332009-09-09 15:08:12 +000067
Chris Lattner39c28bb2009-02-18 06:48:40 +000068 // Create the aggregate string with the appropriate content and location
69 // information.
Jay Foad65aa6882011-06-21 15:13:30 +000070 S = StringLiteral::Create(Context, StrBuf,
Douglas Gregor5cee1192011-07-27 05:40:30 +000071 StringLiteral::Ascii, /*Pascal=*/false,
Chris Lattner2085fd62009-02-18 06:40:38 +000072 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000073 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000074 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +000075
76 return BuildObjCStringLiteral(AtLocs[0], S);
77}
Mike Stump1eb44332009-09-09 15:08:12 +000078
Ted Kremenekebcb57a2012-03-06 20:05:56 +000079ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner69039812009-02-18 06:01:06 +000080 // Verify that this composite string is acceptable for ObjC strings.
81 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000082 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000083
84 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-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 Lattnera0af1fe2009-02-18 06:06:56 +000088 QualType Ty = Context.getObjCConstantStringInterface();
89 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000090 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikie4e4d0842012-03-11 07:00:24 +000091 } else if (getLangOpts().NoConstantCFStrings) {
Fariborz Jahanian4c733072010-10-19 17:19:29 +000092 IdentifierInfo *NSIdent=0;
David Blaikie4e4d0842012-03-11 07:00:24 +000093 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian4c733072010-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 Kremenekebcb57a2012-03-06 20:05:56 +0000100 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian8a437762010-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 Lattner13fd7e52008-06-21 21:44:18 +0000113 } else {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000114 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000115 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorc83c6872010-04-15 22:33:43 +0000116 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000117 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
118 Context.setObjCConstantStringInterface(StrIF);
119 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000120 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000121 } else {
Fariborz Jahanianf64bc202012-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 Lattnera0af1fe2009-02-18 06:06:56 +0000137 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000138 }
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000140 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
141}
142
143/// \brief Retrieve the NSNumber factory method that should be used to create
144/// an Objective-C literal for the given type.
145static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beardeb382ec2012-04-19 00:25:12 +0000146 QualType NumberType,
147 bool isLiteral = false,
148 SourceRange R = SourceRange()) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000149 llvm::Optional<NSAPI::NSNumberLiteralMethodKind> Kind
Patrick Beardeb382ec2012-04-19 00:25:12 +0000150 = S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000151
152 if (!Kind) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000153 if (isLiteral) {
154 S.Diag(Loc, diag::err_invalid_nsnumber_type)
155 << NumberType << R;
156 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000157 return 0;
158 }
Patrick Beardeb382ec2012-04-19 00:25:12 +0000159
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000160 // If we already looked up this method, we're done.
161 if (S.NSNumberLiteralMethods[*Kind])
162 return S.NSNumberLiteralMethods[*Kind];
163
164 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
165 /*Instance=*/false);
166
Patrick Beardeb382ec2012-04-19 00:25:12 +0000167 ASTContext &CX = S.Context;
168
169 // Look up the NSNumber class, if we haven't done so already. It's cached
170 // in the Sema instance.
171 if (!S.NSNumberDecl) {
172 IdentifierInfo *NSNumberId = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
173 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
174 Loc, Sema::LookupOrdinaryName);
175 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
176 if (!S.NSNumberDecl) {
177 if (S.getLangOpts().DebuggerObjCLiteral) {
178 // Create a stub definition of NSNumber.
179 S.NSNumberDecl = ObjCInterfaceDecl::Create (CX,
180 CX.getTranslationUnitDecl(),
181 SourceLocation(), NSNumberId,
182 0, SourceLocation());
183 } else {
184 // Otherwise, require a declaration of NSNumber.
185 S.Diag(Loc, diag::err_undeclared_nsnumber);
186 return 0;
187 }
188 } else if (!S.NSNumberDecl->hasDefinition()) {
189 S.Diag(Loc, diag::err_undeclared_nsnumber);
190 return 0;
191 }
192
193 // generate the pointer to NSNumber type.
194 S.NSNumberPointer = CX.getObjCObjectPointerType(CX.getObjCInterfaceType(S.NSNumberDecl));
195 }
196
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000197 // Look for the appropriate method within NSNumber.
198 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);;
David Blaikie4e4d0842012-03-11 07:00:24 +0000199 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000200 // create a stub definition this NSNumber factory method.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000201 TypeSourceInfo *ResultTInfo = 0;
Patrick Beardeb382ec2012-04-19 00:25:12 +0000202 Method = ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
203 S.NSNumberPointer, ResultTInfo, S.NSNumberDecl,
204 /*isInstance=*/false, /*isVariadic=*/false,
205 /*isSynthesized=*/false,
206 /*isImplicitlyDeclared=*/true,
207 /*isDefined=*/false, ObjCMethodDecl::Required,
208 /*HasRelatedResultType=*/false);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000209 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
210 SourceLocation(), SourceLocation(),
Patrick Beardeb382ec2012-04-19 00:25:12 +0000211 &CX.Idents.get("value"),
212 NumberType, /*TInfo=*/0, SC_None, SC_None, 0);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000213 Method->setMethodParams(S.Context, value, ArrayRef<SourceLocation>());
214 }
215
216 if (!Method) {
Jordy Rose99446d92012-05-12 15:53:41 +0000217 // FIXME: Is there a better way to avoid quotes than using getName()?
218 S.Diag(Loc, diag::err_undeclared_boxing_method)
219 << Sel << S.NSNumberDecl->getName();
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000220 return 0;
221 }
222
223 // Make sure the return type is reasonable.
224 if (!Method->getResultType()->isObjCObjectPointerType()) {
225 S.Diag(Loc, diag::err_objc_literal_method_sig)
226 << Sel;
227 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
228 << Method->getResultType();
229 return 0;
230 }
231
232 // Note: if the parameter type is out-of-line, we'll catch it later in the
233 // implicit conversion.
234
235 S.NSNumberLiteralMethods[*Kind] = Method;
236 return Method;
237}
238
Patrick Beardeb382ec2012-04-19 00:25:12 +0000239/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
240/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000241ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000242 // Determine the type of the literal.
243 QualType NumberType = Number->getType();
244 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
245 // In C, character literals have type 'int'. That's not the type we want
246 // to use to determine the Objective-c literal kind.
247 switch (Char->getKind()) {
248 case CharacterLiteral::Ascii:
249 NumberType = Context.CharTy;
250 break;
251
252 case CharacterLiteral::Wide:
253 NumberType = Context.getWCharType();
254 break;
255
256 case CharacterLiteral::UTF16:
257 NumberType = Context.Char16Ty;
258 break;
259
260 case CharacterLiteral::UTF32:
261 NumberType = Context.Char32Ty;
262 break;
263 }
264 }
265
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000266 // Look for the appropriate method within NSNumber.
267 // Construct the literal.
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000268 SourceRange NR(Number->getSourceRange());
Patrick Beardeb382ec2012-04-19 00:25:12 +0000269 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000270 true, NR);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000271 if (!Method)
272 return ExprError();
273
274 // Convert the number to the type that the parameter expects.
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000275 ParmVarDecl *ParamDecl = Method->param_begin()[0];
276 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
277 ParamDecl);
278 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
279 SourceLocation(),
280 Owned(Number));
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000281 if (ConvertedNumber.isInvalid())
282 return ExprError();
283 Number = ConvertedNumber.get();
284
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000285 // Use the effective source range of the literal, including the leading '@'.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000286 return MaybeBindToTemporary(
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000287 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
288 SourceRange(AtLoc, NR.getEnd())));
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000289}
290
291ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
292 SourceLocation ValueLoc,
293 bool Value) {
294 ExprResult Inner;
David Blaikie4e4d0842012-03-11 07:00:24 +0000295 if (getLangOpts().CPlusPlus) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000296 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
297 } else {
298 // C doesn't actually have a way to represent literal values of type
299 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
300 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
301 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
302 CK_IntegralToBoolean);
303 }
304
305 return BuildObjCNumericLiteral(AtLoc, Inner.get());
306}
307
308/// \brief Check that the given expression is a valid element of an Objective-C
309/// collection literal.
310static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
311 QualType T) {
312 // If the expression is type-dependent, there's nothing for us to do.
313 if (Element->isTypeDependent())
314 return Element;
315
316 ExprResult Result = S.CheckPlaceholderExpr(Element);
317 if (Result.isInvalid())
318 return ExprError();
319 Element = Result.get();
320
321 // In C++, check for an implicit conversion to an Objective-C object pointer
322 // type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000323 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000324 InitializedEntity Entity
325 = InitializedEntity::InitializeParameter(S.Context, T, /*Consumed=*/false);
326 InitializationKind Kind
327 = InitializationKind::CreateCopy(Element->getLocStart(), SourceLocation());
328 InitializationSequence Seq(S, Entity, Kind, &Element, 1);
329 if (!Seq.Failed())
330 return Seq.Perform(S, Entity, Kind, MultiExprArg(S, &Element, 1));
331 }
332
333 Expr *OrigElement = Element;
334
335 // Perform lvalue-to-rvalue conversion.
336 Result = S.DefaultLvalueConversion(Element);
337 if (Result.isInvalid())
338 return ExprError();
339 Element = Result.get();
340
341 // Make sure that we have an Objective-C pointer type or block.
342 if (!Element->getType()->isObjCObjectPointerType() &&
343 !Element->getType()->isBlockPointerType()) {
344 bool Recovered = false;
345
346 // If this is potentially an Objective-C numeric literal, add the '@'.
347 if (isa<IntegerLiteral>(OrigElement) ||
348 isa<CharacterLiteral>(OrigElement) ||
349 isa<FloatingLiteral>(OrigElement) ||
350 isa<ObjCBoolLiteralExpr>(OrigElement) ||
351 isa<CXXBoolLiteralExpr>(OrigElement)) {
352 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
353 int Which = isa<CharacterLiteral>(OrigElement) ? 1
354 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
355 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
356 : 3;
357
358 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
359 << Which << OrigElement->getSourceRange()
360 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
361
362 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
363 OrigElement);
364 if (Result.isInvalid())
365 return ExprError();
366
367 Element = Result.get();
368 Recovered = true;
369 }
370 }
371 // If this is potentially an Objective-C string literal, add the '@'.
372 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
373 if (String->isAscii()) {
374 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
375 << 0 << OrigElement->getSourceRange()
376 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
377
378 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
379 if (Result.isInvalid())
380 return ExprError();
381
382 Element = Result.get();
383 Recovered = true;
384 }
385 }
386
387 if (!Recovered) {
388 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
389 << Element->getType();
390 return ExprError();
391 }
392 }
393
394 // Make sure that the element has the type that the container factory
395 // function expects.
396 return S.PerformCopyInitialization(
397 InitializedEntity::InitializeParameter(S.Context, T,
398 /*Consumed=*/false),
399 Element->getLocStart(), Element);
400}
401
Patrick Beardeb382ec2012-04-19 00:25:12 +0000402ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
403 if (ValueExpr->isTypeDependent()) {
404 ObjCBoxedExpr *BoxedExpr =
405 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR);
406 return Owned(BoxedExpr);
407 }
408 ObjCMethodDecl *BoxingMethod = NULL;
409 QualType BoxedType;
410 // Convert the expression to an RValue, so we can check for pointer types...
411 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
412 if (RValue.isInvalid()) {
413 return ExprError();
414 }
415 ValueExpr = RValue.get();
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000416 QualType ValueType(ValueExpr->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +0000417 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
418 QualType PointeeType = PT->getPointeeType();
419 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
420
421 if (!NSStringDecl) {
422 IdentifierInfo *NSStringId =
423 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
424 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
425 SR.getBegin(), LookupOrdinaryName);
426 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
427 if (!NSStringDecl) {
428 if (getLangOpts().DebuggerObjCLiteral) {
429 // Support boxed expressions in the debugger w/o NSString declaration.
430 NSStringDecl = ObjCInterfaceDecl::Create(Context,
431 Context.getTranslationUnitDecl(),
432 SourceLocation(), NSStringId,
433 0, SourceLocation());
434 } else {
435 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
436 return ExprError();
437 }
438 } else if (!NSStringDecl->hasDefinition()) {
439 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
440 return ExprError();
441 }
442 assert(NSStringDecl && "NSStringDecl should not be NULL");
443 NSStringPointer =
444 Context.getObjCObjectPointerType(Context.getObjCInterfaceType(NSStringDecl));
445 }
446
447 if (!StringWithUTF8StringMethod) {
448 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
449 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
450
451 // Look for the appropriate method within NSString.
452 StringWithUTF8StringMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
453 if (!StringWithUTF8StringMethod && getLangOpts().DebuggerObjCLiteral) {
454 // Debugger needs to work even if NSString hasn't been defined.
455 TypeSourceInfo *ResultTInfo = 0;
456 ObjCMethodDecl *M =
457 ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(),
458 stringWithUTF8String, NSStringPointer,
459 ResultTInfo, NSStringDecl,
460 /*isInstance=*/false, /*isVariadic=*/false,
461 /*isSynthesized=*/false,
462 /*isImplicitlyDeclared=*/true,
463 /*isDefined=*/false,
464 ObjCMethodDecl::Required,
465 /*HasRelatedResultType=*/false);
466 ParmVarDecl *value =
467 ParmVarDecl::Create(Context, M,
468 SourceLocation(), SourceLocation(),
469 &Context.Idents.get("value"),
470 Context.getPointerType(Context.CharTy.withConst()),
471 /*TInfo=*/0,
472 SC_None, SC_None, 0);
473 M->setMethodParams(Context, value, ArrayRef<SourceLocation>());
474 StringWithUTF8StringMethod = M;
475 }
Jordy Rose99446d92012-05-12 15:53:41 +0000476
477 // FIXME: Copied from getNSNumberFactoryMethod().
478 if (!StringWithUTF8StringMethod) {
479 // FIXME: Is there a better way to avoid quotes than using getName()?
480 Diag(SR.getBegin(), diag::err_undeclared_boxing_method)
481 << stringWithUTF8String << NSStringDecl->getName();
482 return ExprError();
483 }
484
485 // Make sure the return type is reasonable.
486 QualType ResultType = StringWithUTF8StringMethod->getResultType();
487 if (!ResultType->isObjCObjectPointerType()) {
488 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
489 << stringWithUTF8String;
490 Diag(StringWithUTF8StringMethod->getLocation(),
491 diag::note_objc_literal_method_return)
492 << ResultType;
493 return ExprError();
494 }
Patrick Beardeb382ec2012-04-19 00:25:12 +0000495 }
496
497 BoxingMethod = StringWithUTF8StringMethod;
498 BoxedType = NSStringPointer;
499 }
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000500 } else if (ValueType->isBuiltinType()) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000501 // The other types we support are numeric, char and BOOL/bool. We could also
502 // provide limited support for structure types, such as NSRange, NSRect, and
503 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
504 // for more details.
505
506 // Check for a top-level character literal.
507 if (const CharacterLiteral *Char =
508 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
509 // In C, character literals have type 'int'. That's not the type we want
510 // to use to determine the Objective-c literal kind.
511 switch (Char->getKind()) {
512 case CharacterLiteral::Ascii:
513 ValueType = Context.CharTy;
514 break;
515
516 case CharacterLiteral::Wide:
517 ValueType = Context.getWCharType();
518 break;
519
520 case CharacterLiteral::UTF16:
521 ValueType = Context.Char16Ty;
522 break;
523
524 case CharacterLiteral::UTF32:
525 ValueType = Context.Char32Ty;
526 break;
527 }
528 }
529
530 // FIXME: Do I need to do anything special with BoolTy expressions?
531
532 // Look for the appropriate method within NSNumber.
533 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
534 BoxedType = NSNumberPointer;
535 }
536
537 if (!BoxingMethod) {
538 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
539 << ValueType << ValueExpr->getSourceRange();
540 return ExprError();
541 }
542
543 // Convert the expression to the type that the parameter requires.
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000544 ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0];
545 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
546 ParamDecl);
547 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
548 SourceLocation(),
549 Owned(ValueExpr));
Patrick Beardeb382ec2012-04-19 00:25:12 +0000550 if (ConvertedValueExpr.isInvalid())
551 return ExprError();
552 ValueExpr = ConvertedValueExpr.get();
553
554 ObjCBoxedExpr *BoxedExpr =
555 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
556 BoxingMethod, SR);
557 return MaybeBindToTemporary(BoxedExpr);
558}
559
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000560ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
561 Expr *IndexExpr,
562 ObjCMethodDecl *getterMethod,
563 ObjCMethodDecl *setterMethod) {
564 // Feature support is for modern abi.
565 if (!LangOpts.ObjCNonFragileABI)
566 return ExprError();
567 // If the expression is type-dependent, there's nothing for us to do.
568 assert ((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
569 "base or index cannot have dependent type here");
570 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
571 if (Result.isInvalid())
572 return ExprError();
573 IndexExpr = Result.get();
574
575 // Perform lvalue-to-rvalue conversion.
576 Result = DefaultLvalueConversion(BaseExpr);
577 if (Result.isInvalid())
578 return ExprError();
579 BaseExpr = Result.get();
580 return Owned(ObjCSubscriptRefExpr::Create(Context,
581 BaseExpr,
582 IndexExpr,
583 Context.PseudoObjectTy,
584 getterMethod,
585 setterMethod, RB));
586
587}
588
589ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
590 // Look up the NSArray class, if we haven't done so already.
591 if (!NSArrayDecl) {
592 NamedDecl *IF = LookupSingleName(TUScope,
593 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
594 SR.getBegin(),
595 LookupOrdinaryName);
596 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikie4e4d0842012-03-11 07:00:24 +0000597 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000598 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
599 Context.getTranslationUnitDecl(),
600 SourceLocation(),
601 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
602 0, SourceLocation());
603
604 if (!NSArrayDecl) {
605 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
606 return ExprError();
607 }
608 }
609
610 // Find the arrayWithObjects:count: method, if we haven't done so already.
611 QualType IdT = Context.getObjCIdType();
612 if (!ArrayWithObjectsMethod) {
613 Selector
614 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
615 ArrayWithObjectsMethod = NSArrayDecl->lookupClassMethod(Sel);
David Blaikie4e4d0842012-03-11 07:00:24 +0000616 if (!ArrayWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000617 TypeSourceInfo *ResultTInfo = 0;
618 ArrayWithObjectsMethod =
619 ObjCMethodDecl::Create(Context,
620 SourceLocation(), SourceLocation(), Sel,
621 IdT,
622 ResultTInfo,
623 Context.getTranslationUnitDecl(),
624 false /*Instance*/, false/*isVariadic*/,
625 /*isSynthesized=*/false,
626 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
627 ObjCMethodDecl::Required,
628 false);
629 SmallVector<ParmVarDecl *, 2> Params;
630 ParmVarDecl *objects = ParmVarDecl::Create(Context, ArrayWithObjectsMethod,
631 SourceLocation(), SourceLocation(),
632 &Context.Idents.get("objects"),
633 Context.getPointerType(IdT),
634 /*TInfo=*/0,
635 SC_None,
636 SC_None,
637 0);
638 Params.push_back(objects);
639 ParmVarDecl *cnt = ParmVarDecl::Create(Context, ArrayWithObjectsMethod,
640 SourceLocation(), SourceLocation(),
641 &Context.Idents.get("cnt"),
642 Context.UnsignedLongTy,
643 /*TInfo=*/0,
644 SC_None,
645 SC_None,
646 0);
647 Params.push_back(cnt);
648 ArrayWithObjectsMethod->setMethodParams(Context, Params,
649 ArrayRef<SourceLocation>());
650
651
652 }
653
654 if (!ArrayWithObjectsMethod) {
Jordy Rose99446d92012-05-12 15:53:41 +0000655 // FIXME: Is there a better way to avoid quotes than using getName()?
656 Diag(SR.getBegin(), diag::err_undeclared_boxing_method)
657 << Sel << NSArrayDecl->getName();
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000658 return ExprError();
659 }
660 }
661
662 // Make sure the return type is reasonable.
663 if (!ArrayWithObjectsMethod->getResultType()->isObjCObjectPointerType()) {
664 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
665 << ArrayWithObjectsMethod->getSelector();
666 Diag(ArrayWithObjectsMethod->getLocation(),
667 diag::note_objc_literal_method_return)
668 << ArrayWithObjectsMethod->getResultType();
669 return ExprError();
670 }
671
672 // Dig out the type that all elements should be converted to.
673 QualType T = ArrayWithObjectsMethod->param_begin()[0]->getType();
674 const PointerType *PtrT = T->getAs<PointerType>();
675 if (!PtrT ||
676 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
677 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
678 << ArrayWithObjectsMethod->getSelector();
679 Diag(ArrayWithObjectsMethod->param_begin()[0]->getLocation(),
680 diag::note_objc_literal_method_param)
681 << 0 << T
682 << Context.getPointerType(IdT.withConst());
683 return ExprError();
684 }
685 T = PtrT->getPointeeType();
686
687 // Check that the 'count' parameter is integral.
688 if (!ArrayWithObjectsMethod->param_begin()[1]->getType()->isIntegerType()) {
689 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
690 << ArrayWithObjectsMethod->getSelector();
691 Diag(ArrayWithObjectsMethod->param_begin()[1]->getLocation(),
692 diag::note_objc_literal_method_param)
693 << 1
694 << ArrayWithObjectsMethod->param_begin()[1]->getType()
695 << "integral";
696 return ExprError();
697 }
698
699 // Check that each of the elements provided is valid in a collection literal,
700 // performing conversions as necessary.
701 Expr **ElementsBuffer = Elements.get();
702 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
703 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
704 ElementsBuffer[I],
705 T);
706 if (Converted.isInvalid())
707 return ExprError();
708
709 ElementsBuffer[I] = Converted.get();
710 }
711
712 QualType Ty
713 = Context.getObjCObjectPointerType(
714 Context.getObjCInterfaceType(NSArrayDecl));
715
716 return MaybeBindToTemporary(
717 ObjCArrayLiteral::Create(Context,
718 llvm::makeArrayRef(Elements.get(),
719 Elements.size()),
720 Ty, ArrayWithObjectsMethod, SR));
721}
722
723ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
724 ObjCDictionaryElement *Elements,
725 unsigned NumElements) {
726 // Look up the NSDictionary class, if we haven't done so already.
727 if (!NSDictionaryDecl) {
728 NamedDecl *IF = LookupSingleName(TUScope,
729 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
730 SR.getBegin(), LookupOrdinaryName);
731 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikie4e4d0842012-03-11 07:00:24 +0000732 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000733 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
734 Context.getTranslationUnitDecl(),
735 SourceLocation(),
736 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
737 0, SourceLocation());
738
739 if (!NSDictionaryDecl) {
740 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
741 return ExprError();
742 }
743 }
744
745 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
746 // so already.
747 QualType IdT = Context.getObjCIdType();
748 if (!DictionaryWithObjectsMethod) {
749 Selector Sel = NSAPIObj->getNSDictionarySelector(
750 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
751 DictionaryWithObjectsMethod = NSDictionaryDecl->lookupClassMethod(Sel);
David Blaikie4e4d0842012-03-11 07:00:24 +0000752 if (!DictionaryWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000753 DictionaryWithObjectsMethod =
754 ObjCMethodDecl::Create(Context,
755 SourceLocation(), SourceLocation(), Sel,
756 IdT,
757 0 /*TypeSourceInfo */,
758 Context.getTranslationUnitDecl(),
759 false /*Instance*/, false/*isVariadic*/,
760 /*isSynthesized=*/false,
761 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
762 ObjCMethodDecl::Required,
763 false);
764 SmallVector<ParmVarDecl *, 3> Params;
765 ParmVarDecl *objects = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
766 SourceLocation(), SourceLocation(),
767 &Context.Idents.get("objects"),
768 Context.getPointerType(IdT),
769 /*TInfo=*/0,
770 SC_None,
771 SC_None,
772 0);
773 Params.push_back(objects);
774 ParmVarDecl *keys = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
775 SourceLocation(), SourceLocation(),
776 &Context.Idents.get("keys"),
777 Context.getPointerType(IdT),
778 /*TInfo=*/0,
779 SC_None,
780 SC_None,
781 0);
782 Params.push_back(keys);
783 ParmVarDecl *cnt = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
784 SourceLocation(), SourceLocation(),
785 &Context.Idents.get("cnt"),
786 Context.UnsignedLongTy,
787 /*TInfo=*/0,
788 SC_None,
789 SC_None,
790 0);
791 Params.push_back(cnt);
792 DictionaryWithObjectsMethod->setMethodParams(Context, Params,
793 ArrayRef<SourceLocation>());
794 }
795
796 if (!DictionaryWithObjectsMethod) {
Jordy Rose99446d92012-05-12 15:53:41 +0000797 // FIXME: Is there a better way to avoid quotes than using getName()?
798 Diag(SR.getBegin(), diag::err_undeclared_boxing_method)
799 << Sel << NSDictionaryDecl->getName();
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000800 return ExprError();
801 }
802 }
803
804 // Make sure the return type is reasonable.
805 if (!DictionaryWithObjectsMethod->getResultType()->isObjCObjectPointerType()){
806 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
807 << DictionaryWithObjectsMethod->getSelector();
808 Diag(DictionaryWithObjectsMethod->getLocation(),
809 diag::note_objc_literal_method_return)
810 << DictionaryWithObjectsMethod->getResultType();
811 return ExprError();
812 }
813
814 // Dig out the type that all values should be converted to.
815 QualType ValueT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
816 const PointerType *PtrValue = ValueT->getAs<PointerType>();
817 if (!PtrValue ||
818 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
819 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
820 << DictionaryWithObjectsMethod->getSelector();
821 Diag(DictionaryWithObjectsMethod->param_begin()[0]->getLocation(),
822 diag::note_objc_literal_method_param)
823 << 0 << ValueT
824 << Context.getPointerType(IdT.withConst());
825 return ExprError();
826 }
827 ValueT = PtrValue->getPointeeType();
828
829 // Dig out the type that all keys should be converted to.
830 QualType KeyT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
831 const PointerType *PtrKey = KeyT->getAs<PointerType>();
832 if (!PtrKey ||
833 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
834 IdT)) {
835 bool err = true;
836 if (PtrKey) {
837 if (QIDNSCopying.isNull()) {
838 // key argument of selector is id<NSCopying>?
839 if (ObjCProtocolDecl *NSCopyingPDecl =
840 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
841 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
842 QIDNSCopying =
843 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
844 (ObjCProtocolDecl**) PQ,1);
845 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
846 }
847 }
848 if (!QIDNSCopying.isNull())
849 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
850 QIDNSCopying);
851 }
852
853 if (err) {
854 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
855 << DictionaryWithObjectsMethod->getSelector();
856 Diag(DictionaryWithObjectsMethod->param_begin()[1]->getLocation(),
857 diag::note_objc_literal_method_param)
858 << 1 << KeyT
859 << Context.getPointerType(IdT.withConst());
860 return ExprError();
861 }
862 }
863 KeyT = PtrKey->getPointeeType();
864
865 // Check that the 'count' parameter is integral.
866 if (!DictionaryWithObjectsMethod->param_begin()[2]->getType()
867 ->isIntegerType()) {
868 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
869 << DictionaryWithObjectsMethod->getSelector();
870 Diag(DictionaryWithObjectsMethod->param_begin()[2]->getLocation(),
871 diag::note_objc_literal_method_param)
872 << 2
873 << DictionaryWithObjectsMethod->param_begin()[2]->getType()
874 << "integral";
875 return ExprError();
876 }
877
878 // Check that each of the keys and values provided is valid in a collection
879 // literal, performing conversions as necessary.
880 bool HasPackExpansions = false;
881 for (unsigned I = 0, N = NumElements; I != N; ++I) {
882 // Check the key.
883 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
884 KeyT);
885 if (Key.isInvalid())
886 return ExprError();
887
888 // Check the value.
889 ExprResult Value
890 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
891 if (Value.isInvalid())
892 return ExprError();
893
894 Elements[I].Key = Key.get();
895 Elements[I].Value = Value.get();
896
897 if (Elements[I].EllipsisLoc.isInvalid())
898 continue;
899
900 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
901 !Elements[I].Value->containsUnexpandedParameterPack()) {
902 Diag(Elements[I].EllipsisLoc,
903 diag::err_pack_expansion_without_parameter_packs)
904 << SourceRange(Elements[I].Key->getLocStart(),
905 Elements[I].Value->getLocEnd());
906 return ExprError();
907 }
908
909 HasPackExpansions = true;
910 }
911
912
913 QualType Ty
914 = Context.getObjCObjectPointerType(
915 Context.getObjCInterfaceType(NSDictionaryDecl));
916 return MaybeBindToTemporary(
917 ObjCDictionaryLiteral::Create(Context,
918 llvm::makeArrayRef(Elements,
919 NumElements),
920 HasPackExpansions,
921 Ty,
922 DictionaryWithObjectsMethod, SR));
Chris Lattner85a932e2008-01-04 22:32:30 +0000923}
924
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000925ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000926 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000927 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000928 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000929 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000930 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000931 StrTy = Context.DependentTy;
932 else {
Fariborz Jahanian6c916152011-06-16 22:34:44 +0000933 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
934 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000935 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregord10099e2012-05-04 16:32:21 +0000936 diag::err_incomplete_type_objc_at_encode,
937 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000938 return ExprError();
939
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000940 std::string Str;
941 Context.getObjCEncodingForType(EncodedType, Str);
942
943 // The type of @encode is the same as the type of the corresponding string,
944 // which is an array type.
945 StrTy = Context.CharTy;
946 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +0000947 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000948 StrTy.addConst();
949 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
950 ArrayType::Normal, 0);
951 }
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Douglas Gregor81d34662010-04-20 15:39:42 +0000953 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000954}
955
John McCallf312b1e2010-08-26 23:41:50 +0000956ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
957 SourceLocation EncodeLoc,
958 SourceLocation LParenLoc,
959 ParsedType ty,
960 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000961 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000962 TypeSourceInfo *TInfo;
963 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
964 if (!TInfo)
965 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
966 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000967
Douglas Gregor81d34662010-04-20 15:39:42 +0000968 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000969}
970
John McCallf312b1e2010-08-26 23:41:50 +0000971ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
972 SourceLocation AtLoc,
973 SourceLocation SelLoc,
974 SourceLocation LParenLoc,
975 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000976 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000977 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000978 if (!Method)
979 Method = LookupFactoryMethodInGlobalPool(Sel,
980 SourceRange(LParenLoc, RParenLoc));
981 if (!Method)
982 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian4c91d892011-07-13 19:05:43 +0000983
984 if (!Method ||
985 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
986 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
987 = ReferencedSelectors.find(Sel);
988 if (Pos == ReferencedSelectors.end())
989 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
990 }
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000991
John McCallf85e1932011-06-15 23:02:42 +0000992 // In ARC, forbid the user from using @selector for
993 // retain/release/autorelease/dealloc/retainCount.
David Blaikie4e4d0842012-03-11 07:00:24 +0000994 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +0000995 switch (Sel.getMethodFamily()) {
996 case OMF_retain:
997 case OMF_release:
998 case OMF_autorelease:
999 case OMF_retainCount:
1000 case OMF_dealloc:
1001 Diag(AtLoc, diag::err_arc_illegal_selector) <<
1002 Sel << SourceRange(LParenLoc, RParenLoc);
1003 break;
1004
1005 case OMF_None:
1006 case OMF_alloc:
1007 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00001008 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00001009 case OMF_init:
1010 case OMF_mutableCopy:
1011 case OMF_new:
1012 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001013 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +00001014 break;
1015 }
1016 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +00001017 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +00001018 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +00001019}
1020
John McCallf312b1e2010-08-26 23:41:50 +00001021ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
1022 SourceLocation AtLoc,
1023 SourceLocation ProtoLoc,
1024 SourceLocation LParenLoc,
1025 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00001026 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +00001027 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001028 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +00001029 return true;
1030 }
Mike Stump1eb44332009-09-09 15:08:12 +00001031
Chris Lattnera0af1fe2009-02-18 06:06:56 +00001032 QualType Ty = Context.getObjCProtoType();
1033 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +00001034 return true;
Steve Naroff14108da2009-07-10 23:34:53 +00001035 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +00001036 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +00001037}
1038
John McCall26743b22011-02-03 09:00:02 +00001039/// Try to capture an implicit reference to 'self'.
Eli Friedmanb942cb22012-02-03 22:47:37 +00001040ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1041 DeclContext *DC = getFunctionLevelDeclContext();
John McCall26743b22011-02-03 09:00:02 +00001042
1043 // If we're not in an ObjC method, error out. Note that, unlike the
1044 // C++ case, we don't require an instance method --- class methods
1045 // still have a 'self', and we really do still need to capture it!
1046 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1047 if (!method)
1048 return 0;
1049
Douglas Gregor999713e2012-02-18 09:37:24 +00001050 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall26743b22011-02-03 09:00:02 +00001051
1052 return method;
1053}
1054
Douglas Gregor5c16d632011-09-09 20:05:21 +00001055static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1056 if (T == Context.getObjCInstanceType())
1057 return Context.getObjCIdType();
1058
1059 return T;
1060}
1061
Douglas Gregor926df6c2011-06-11 01:09:30 +00001062QualType Sema::getMessageSendResultType(QualType ReceiverType,
1063 ObjCMethodDecl *Method,
1064 bool isClassMessage, bool isSuperMessage) {
1065 assert(Method && "Must have a method");
1066 if (!Method->hasRelatedResultType())
1067 return Method->getSendResultType();
1068
1069 // If a method has a related return type:
1070 // - if the method found is an instance method, but the message send
1071 // was a class message send, T is the declared return type of the method
1072 // found
1073 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor5c16d632011-09-09 20:05:21 +00001074 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001075
1076 // - if the receiver is super, T is a pointer to the class of the
1077 // enclosing method definition
1078 if (isSuperMessage) {
1079 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1080 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1081 return Context.getObjCObjectPointerType(
1082 Context.getObjCInterfaceType(Class));
1083 }
1084
1085 // - if the receiver is the name of a class U, T is a pointer to U
1086 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1087 ReceiverType->isObjCQualifiedInterfaceType())
1088 return Context.getObjCObjectPointerType(ReceiverType);
1089 // - if the receiver is of type Class or qualified Class type,
1090 // T is the declared return type of the method.
1091 if (ReceiverType->isObjCClassType() ||
1092 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor5c16d632011-09-09 20:05:21 +00001093 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001094
1095 // - if the receiver is id, qualified id, Class, or qualified Class, T
1096 // is the receiver type, otherwise
1097 // - T is the type of the receiver expression.
1098 return ReceiverType;
1099}
John McCall26743b22011-02-03 09:00:02 +00001100
Douglas Gregor926df6c2011-06-11 01:09:30 +00001101void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1102 E = E->IgnoreParenImpCasts();
1103 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1104 if (!MsgSend)
1105 return;
1106
1107 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1108 if (!Method)
1109 return;
1110
1111 if (!Method->hasRelatedResultType())
1112 return;
1113
1114 if (Context.hasSameUnqualifiedType(Method->getResultType()
1115 .getNonReferenceType(),
1116 MsgSend->getType()))
1117 return;
1118
Douglas Gregore97179c2011-09-08 01:46:34 +00001119 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
1120 Context.getObjCInstanceType()))
1121 return;
1122
Douglas Gregor926df6c2011-06-11 01:09:30 +00001123 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1124 << Method->isInstanceMethod() << Method->getSelector()
1125 << MsgSend->getType();
1126}
1127
1128bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
1129 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00001130 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +00001131 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001132 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +00001133 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001134 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +00001135 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +00001136 for (unsigned i = 0; i != NumArgs; i++) {
1137 if (Args[i]->isTypeDependent())
1138 continue;
1139
John Wiegley429bb272011-04-08 18:41:53 +00001140 ExprResult Result = DefaultArgumentPromotion(Args[i]);
1141 if (Result.isInvalid())
1142 return true;
1143 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +00001144 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +00001145
John McCallf85e1932011-06-15 23:02:42 +00001146 unsigned DiagID;
David Blaikie4e4d0842012-03-11 07:00:24 +00001147 if (getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00001148 DiagID = diag::err_arc_method_not_found;
1149 else
1150 DiagID = isClassMessage ? diag::warn_class_method_not_found
1151 : diag::warn_inst_method_not_found;
David Blaikie4e4d0842012-03-11 07:00:24 +00001152 if (!getLangOpts().DebuggerSupport)
John McCall819e7452011-08-31 20:57:36 +00001153 Diag(lbrac, DiagID)
1154 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +00001155
1156 // In debuggers, we want to use __unknown_anytype for these
1157 // results so that clients can cast them.
David Blaikie4e4d0842012-03-11 07:00:24 +00001158 if (getLangOpts().DebuggerSupport) {
John McCall48218c62011-07-13 17:56:40 +00001159 ReturnType = Context.UnknownAnyTy;
1160 } else {
1161 ReturnType = Context.getObjCIdType();
1162 }
John McCallf89e55a2010-11-18 06:31:45 +00001163 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001164 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001165 }
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Douglas Gregor926df6c2011-06-11 01:09:30 +00001167 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1168 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +00001169 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +00001170
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001171 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +00001172 // Method might have more arguments than selector indicates. This is due
1173 // to addition of c-style arguments in method.
1174 if (Method->param_size() > Sel.getNumArgs())
1175 NumNamedArgs = Method->param_size();
1176 // FIXME. This need be cleaned up.
1177 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +00001178 Diag(lbrac, diag::err_typecheck_call_too_few_args)
1179 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +00001180 return false;
1181 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001182
Chris Lattner312531a2009-04-12 08:11:20 +00001183 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001184 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001185 // We can't do any type-checking on a type-dependent argument.
1186 if (Args[i]->isTypeDependent())
1187 continue;
1188
Chris Lattner85a932e2008-01-04 22:32:30 +00001189 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +00001190
John McCall5acb0c92011-10-17 18:40:02 +00001191 ParmVarDecl *param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +00001192 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +00001193
John McCall5acb0c92011-10-17 18:40:02 +00001194 // Strip the unbridged-cast placeholder expression off unless it's
1195 // a consumed argument.
1196 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1197 !param->hasAttr<CFConsumedAttr>())
1198 argExpr = stripARCUnbridgedCast(argExpr);
1199
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001200 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall5acb0c92011-10-17 18:40:02 +00001201 param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00001202 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001203 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +00001204
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001205 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall5acb0c92011-10-17 18:40:02 +00001206 param);
John McCall3fa5cae2010-10-26 07:05:15 +00001207 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001208 if (ArgE.isInvalid())
1209 IsError = true;
1210 else
1211 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +00001212 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001213
1214 // Promote additional arguments to variadic methods.
1215 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001216 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
1217 if (Args[i]->isTypeDependent())
1218 continue;
1219
John Wiegley429bb272011-04-08 18:41:53 +00001220 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
1221 IsError |= Arg.isInvalid();
1222 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +00001223 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001224 } else {
1225 // Check for extra arguments to non-variadic methods.
1226 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001227 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001228 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001229 << 2 /*method*/ << NumNamedArgs << NumArgs
1230 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001231 << SourceRange(Args[NumNamedArgs]->getLocStart(),
1232 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001233 }
1234 }
1235
Douglas Gregor2725ca82010-04-21 19:57:20 +00001236 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001237
1238 // Do additional checkings on method.
1239 IsError |= CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
1240
Chris Lattner312531a2009-04-12 08:11:20 +00001241 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +00001242}
1243
Douglas Gregorc737acb2011-09-27 16:10:05 +00001244bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +00001245 // 'self' is objc 'self' in an objc method only.
John McCall4b9c2d22011-11-06 09:01:30 +00001246 ObjCMethodDecl *method =
1247 dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1248 if (!method) return false;
1249
John McCallf85e1932011-06-15 23:02:42 +00001250 receiver = receiver->IgnoreParenLValueCasts();
1251 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCall4b9c2d22011-11-06 09:01:30 +00001252 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregorc737acb2011-09-27 16:10:05 +00001253 return true;
1254 return false;
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001255}
1256
Steve Narofff1afaf62009-02-26 15:55:06 +00001257// Helper method for ActOnClassMethod/ActOnInstanceMethod.
1258// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +00001259// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +00001260// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +00001261ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +00001262 ObjCInterfaceDecl *ClassDecl) {
1263 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +00001264 // lookup in class and all superclasses
1265 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001266 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001267 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001268
Steve Naroff5609ec02009-03-08 18:56:13 +00001269 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001270 if (!Method)
1271 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Steve Naroff5609ec02009-03-08 18:56:13 +00001273 // Before we give up, check if the selector is an instance method.
1274 // But only in the root. This matches gcc's behaviour and what the
1275 // runtime expects.
1276 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001277 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001278 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +00001279 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +00001280 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +00001281 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1282 }
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Steve Naroff5609ec02009-03-08 18:56:13 +00001284 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +00001285 }
Steve Naroff5609ec02009-03-08 18:56:13 +00001286 return Method;
1287}
1288
1289ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
1290 ObjCInterfaceDecl *ClassDecl) {
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00001291 if (!ClassDecl->hasDefinition())
1292 return 0;
1293
Steve Naroff5609ec02009-03-08 18:56:13 +00001294 ObjCMethodDecl *Method = 0;
1295 while (ClassDecl && !Method) {
1296 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001297 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001298 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001299
Steve Naroff5609ec02009-03-08 18:56:13 +00001300 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001301 if (!Method)
1302 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +00001303 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +00001304 }
Steve Narofff1afaf62009-02-26 15:55:06 +00001305 return Method;
1306}
1307
John McCall3c3b7f92011-10-25 17:37:35 +00001308/// LookupMethodInType - Look up a method in an ObjCObjectType.
1309ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1310 bool isInstance) {
1311 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1312 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1313 // Look it up in the main interface (and categories, etc.)
1314 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1315 return method;
1316
1317 // Okay, look for "private" methods declared in any
1318 // @implementations we've seen.
1319 if (isInstance) {
1320 if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
1321 return method;
1322 } else {
1323 if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
1324 return method;
1325 }
1326 }
1327
1328 // Check qualifiers.
1329 for (ObjCObjectType::qual_iterator
1330 i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
1331 if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
1332 return method;
1333
1334 return 0;
1335}
1336
Fariborz Jahanian61478062011-03-09 20:18:06 +00001337/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1338/// list of a qualified objective pointer type.
1339ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1340 const ObjCObjectPointerType *OPT,
1341 bool Instance)
1342{
1343 ObjCMethodDecl *MD = 0;
1344 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1345 E = OPT->qual_end(); I != E; ++I) {
1346 ObjCProtocolDecl *PROTO = (*I);
1347 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1348 return MD;
1349 }
1350 }
1351 return 0;
1352}
1353
Fariborz Jahanian98795562012-04-19 23:49:39 +00001354static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1355 if (!Receiver)
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001356 return;
1357
Fariborz Jahanian98795562012-04-19 23:49:39 +00001358 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1359 SourceLocation Loc = RExpr->getLocStart();
1360 QualType T = RExpr->getType();
1361 ObjCPropertyDecl *PDecl = 0;
1362 ObjCMethodDecl *GDecl = 0;
1363 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1364 RExpr = POE->getSyntacticForm();
1365 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1366 if (PRE->isImplicitProperty()) {
1367 GDecl = PRE->getImplicitPropertyGetter();
1368 if (GDecl) {
1369 T = GDecl->getResultType();
1370 }
1371 }
1372 else {
1373 PDecl = PRE->getExplicitProperty();
1374 if (PDecl) {
1375 T = PDecl->getType();
1376 }
1377 }
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001378 }
Fariborz Jahanian98795562012-04-19 23:49:39 +00001379 }
1380
1381 if (T.getObjCLifetime() == Qualifiers::OCL_Weak) {
1382 S.Diag(Loc, diag::warn_receiver_is_weak)
1383 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1384 if (PDecl)
1385 S.Diag(PDecl->getLocation(), diag::note_property_declare);
1386 else if (GDecl)
1387 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001388 return;
1389 }
1390
Fariborz Jahanian98795562012-04-19 23:49:39 +00001391 if (PDecl &&
1392 (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)) {
1393 S.Diag(Loc, diag::warn_receiver_is_weak) << 1;
1394 S.Diag(PDecl->getLocation(), diag::note_property_declare);
1395 }
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001396}
1397
Chris Lattner7f816522010-04-11 07:45:24 +00001398/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1399/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001400ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +00001401HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001402 Expr *BaseExpr, SourceLocation OpLoc,
1403 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001404 SourceLocation MemberLoc,
1405 SourceLocation SuperLoc, QualType SuperType,
1406 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +00001407 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1408 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +00001409
1410 if (MemberName.getNameKind() != DeclarationName::Identifier) {
1411 Diag(MemberLoc, diag::err_invalid_property_name)
1412 << MemberName << QualType(OPT, 0);
1413 return ExprError();
1414 }
1415
Chris Lattner7f816522010-04-11 07:45:24 +00001416 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregorb3029962011-11-14 22:10:01 +00001417 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1418 : BaseExpr->getSourceRange();
1419 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00001420 diag::err_property_not_found_forward_class,
1421 MemberName, BaseRange))
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +00001422 return ExprError();
Douglas Gregorb3029962011-11-14 22:10:01 +00001423
Chris Lattner7f816522010-04-11 07:45:24 +00001424 // Search for a declared property first.
1425 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1426 // Check whether we can reference this property.
1427 if (DiagnoseUseOfDecl(PD, MemberLoc))
1428 return ExprError();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001429 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001430 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001431 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001432 MemberLoc,
1433 SuperLoc, SuperType));
1434 else
John McCall3c3b7f92011-10-25 17:37:35 +00001435 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001436 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001437 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001438 }
1439 // Check protocols on qualified interfaces.
1440 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1441 E = OPT->qual_end(); I != E; ++I)
1442 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1443 // Check whether we can reference this property.
1444 if (DiagnoseUseOfDecl(PD, MemberLoc))
1445 return ExprError();
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001446
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001447 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001448 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1449 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001450 VK_LValue,
1451 OK_ObjCProperty,
1452 MemberLoc,
1453 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001454 else
John McCall3c3b7f92011-10-25 17:37:35 +00001455 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1456 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001457 VK_LValue,
1458 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001459 MemberLoc,
1460 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001461 }
1462 // If that failed, look for an "implicit" property by seeing if the nullary
1463 // selector is implemented.
1464
1465 // FIXME: The logic for looking up nullary and unary selectors should be
1466 // shared with the code in ActOnInstanceMessage.
1467
1468 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1469 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001470
1471 // May be founf in property's qualified list.
1472 if (!Getter)
1473 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +00001474
1475 // If this reference is in an @implementation, check for 'private' methods.
1476 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001477 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +00001478
1479 // Look through local category implementations associated with the class.
1480 if (!Getter)
1481 Getter = IFace->getCategoryInstanceMethod(Sel);
1482 if (Getter) {
1483 // Check if we can reference this property.
1484 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1485 return ExprError();
1486 }
1487 // If we found a getter then this may be a valid dot-reference, we
1488 // will look for the matching setter, in case it is needed.
1489 Selector SetterSel =
1490 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1491 PP.getSelectorTable(), Member);
1492 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001493
1494 // May be founf in property's qualified list.
1495 if (!Setter)
1496 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1497
Chris Lattner7f816522010-04-11 07:45:24 +00001498 if (!Setter) {
1499 // If this reference is in an @implementation, also check for 'private'
1500 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001501 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +00001502 }
1503 // Look through local category implementations associated with the class.
1504 if (!Setter)
1505 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001506
Chris Lattner7f816522010-04-11 07:45:24 +00001507 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1508 return ExprError();
1509
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001510 if (Getter || Setter) {
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001511 if (Super)
John McCall12f78a62010-12-02 01:19:52 +00001512 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001513 Context.PseudoObjectTy,
1514 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001515 MemberLoc,
1516 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001517 else
John McCall12f78a62010-12-02 01:19:52 +00001518 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001519 Context.PseudoObjectTy,
1520 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001521 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001522
Chris Lattner7f816522010-04-11 07:45:24 +00001523 }
1524
1525 // Attempt to correct for typos in property names.
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001526 DeclFilterCCC<ObjCPropertyDecl> Validator;
1527 if (TypoCorrection Corrected = CorrectTypo(
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001528 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001529 NULL, Validator, IFace, false, OPT)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001530 ObjCPropertyDecl *Property =
1531 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001532 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +00001533 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001534 << MemberName << QualType(OPT, 0) << TypoResult
1535 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +00001536 Diag(Property->getLocation(), diag::note_previous_decl)
1537 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001538 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1539 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001540 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +00001541 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001542 ObjCInterfaceDecl *ClassDeclared;
1543 if (ObjCIvarDecl *Ivar =
1544 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1545 QualType T = Ivar->getType();
1546 if (const ObjCObjectPointerType * OBJPT =
1547 T->getAsObjCInterfacePointerType()) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001548 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00001549 diag::err_property_not_as_forward_class,
1550 MemberName, BaseExpr))
Douglas Gregorb3029962011-11-14 22:10:01 +00001551 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001552 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001553 Diag(MemberLoc,
1554 diag::err_ivar_access_using_property_syntax_suggest)
1555 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1556 << FixItHint::CreateReplacement(OpLoc, "->");
1557 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001558 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001559
Chris Lattner7f816522010-04-11 07:45:24 +00001560 Diag(MemberLoc, diag::err_property_not_found)
1561 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001562 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +00001563 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001564 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +00001565 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +00001566}
1567
1568
1569
John McCall60d7b3a2010-08-24 06:29:42 +00001570ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +00001571ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1572 IdentifierInfo &propertyName,
1573 SourceLocation receiverNameLoc,
1574 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001575
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001576 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +00001577 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1578 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +00001579
1580 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +00001581 if (IFace == 0) {
1582 // If the "receiver" is 'super' in a method, handle it as an expression-like
1583 // property reference.
John McCall26743b22011-02-03 09:00:02 +00001584 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001585 IsSuper = true;
1586
Eli Friedmanb942cb22012-02-03 22:47:37 +00001587 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnereb483eb2010-04-11 08:28:14 +00001588 if (CurMethod->isInstanceMethod()) {
1589 QualType T =
1590 Context.getObjCInterfaceType(CurMethod->getClassInterface());
1591 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001592
1593 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001594 /*BaseExpr*/0,
1595 SourceLocation()/*OpLoc*/,
1596 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001597 propertyNameLoc,
1598 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001599 }
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Chris Lattnereb483eb2010-04-11 08:28:14 +00001601 // Otherwise, if this is a class method, try dispatching to our
1602 // superclass.
1603 IFace = CurMethod->getClassInterface()->getSuperClass();
1604 }
John McCall26743b22011-02-03 09:00:02 +00001605 }
Chris Lattnereb483eb2010-04-11 08:28:14 +00001606
1607 if (IFace == 0) {
1608 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1609 return ExprError();
1610 }
1611 }
1612
1613 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +00001614 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001615 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001616
1617 // If this reference is in an @implementation, check for 'private' methods.
1618 if (!Getter)
1619 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1620 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001621 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001622 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001623
1624 if (Getter) {
1625 // FIXME: refactor/share with ActOnMemberReference().
1626 // Check if we can reference this property.
1627 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1628 return ExprError();
1629 }
Mike Stump1eb44332009-09-09 15:08:12 +00001630
Steve Naroff61f72cb2009-03-09 21:12:44 +00001631 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00001632 Selector SetterSel =
1633 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +00001634 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +00001635
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001636 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001637 if (!Setter) {
1638 // If this reference is in an @implementation, also check for 'private'
1639 // methods.
1640 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1641 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001642 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001643 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001644 }
1645 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001646 if (!Setter)
1647 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001648
1649 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1650 return ExprError();
1651
1652 if (Getter || Setter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001653 if (IsSuper)
1654 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001655 Context.PseudoObjectTy,
1656 VK_LValue, OK_ObjCProperty,
Douglas Gregor926df6c2011-06-11 01:09:30 +00001657 propertyNameLoc,
1658 receiverNameLoc,
1659 Context.getObjCInterfaceType(IFace)));
1660
John McCall12f78a62010-12-02 01:19:52 +00001661 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001662 Context.PseudoObjectTy,
1663 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001664 propertyNameLoc,
1665 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +00001666 }
1667 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1668 << &propertyName << Context.getObjCInterfaceType(IFace));
1669}
1670
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001671namespace {
1672
1673class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1674 public:
1675 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1676 // Determine whether "super" is acceptable in the current context.
1677 if (Method && Method->getClassInterface())
1678 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1679 }
1680
1681 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1682 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1683 candidate.isKeyword("super");
1684 }
1685};
1686
1687}
1688
Douglas Gregor47bd5432010-04-14 02:46:37 +00001689Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +00001690 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +00001691 SourceLocation NameLoc,
1692 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +00001693 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +00001694 ParsedType &ReceiverType) {
1695 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +00001696
Douglas Gregor47bd5432010-04-14 02:46:37 +00001697 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +00001698 // messaging super. If the identifier is "super" and there is a
1699 // trailing dot, it's an instance message.
1700 if (IsSuper && S->isInObjcMethodScope())
1701 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001702
1703 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1704 LookupName(Result, S);
1705
1706 switch (Result.getResultKind()) {
1707 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +00001708 // Normal name lookup didn't find anything. If we're in an
1709 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +00001710 // FIXME: This is a hack. Ivar lookup should be part of normal
1711 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +00001712 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidisccc9e762011-11-09 00:22:48 +00001713 if (!Method->getClassInterface()) {
1714 // Fall back: let the parser try to parse it as an instance message.
1715 return ObjCInstanceMessage;
1716 }
1717
Douglas Gregored464422010-04-19 20:09:36 +00001718 ObjCInterfaceDecl *ClassDeclared;
1719 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1720 ClassDeclared))
1721 return ObjCInstanceMessage;
1722 }
Douglas Gregor95f42922010-10-14 22:11:03 +00001723
Douglas Gregor47bd5432010-04-14 02:46:37 +00001724 // Break out; we'll perform typo correction below.
1725 break;
1726
1727 case LookupResult::NotFoundInCurrentInstantiation:
1728 case LookupResult::FoundOverloaded:
1729 case LookupResult::FoundUnresolvedValue:
1730 case LookupResult::Ambiguous:
1731 Result.suppressDiagnostics();
1732 return ObjCInstanceMessage;
1733
1734 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +00001735 // If the identifier is a class or not, and there is a trailing dot,
1736 // it's an instance message.
1737 if (HasTrailingDot)
1738 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001739 // We found something. If it's a type, then we have a class
1740 // message. Otherwise, it's an instance message.
1741 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +00001742 QualType T;
1743 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1744 T = Context.getObjCInterfaceType(Class);
1745 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
1746 T = Context.getTypeDeclType(Type);
1747 else
1748 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001749
Douglas Gregor1569f952010-04-21 20:38:13 +00001750 // We have a class message, and T is the type we're
1751 // messaging. Build source-location information for it.
1752 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +00001753 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +00001754 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001755 }
1756 }
1757
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001758 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001759 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1760 Result.getLookupKind(), S, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001761 Validator)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001762 if (Corrected.isKeyword()) {
1763 // If we've found the keyword "super" (the only keyword that would be
1764 // returned by CorrectTypo), this is a send to super.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001765 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001766 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +00001767 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +00001768 return ObjCSuperMessage;
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001769 } else if (ObjCInterfaceDecl *Class =
1770 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1771 // If we found a declaration, correct when it refers to an Objective-C
1772 // class.
1773 Diag(NameLoc, diag::err_unknown_receiver_suggest)
1774 << Name << Corrected.getCorrection()
1775 << FixItHint::CreateReplacement(SourceRange(NameLoc),
1776 Class->getNameAsString());
1777 Diag(Class->getLocation(), diag::note_previous_decl)
1778 << Corrected.getCorrection();
1779
1780 QualType T = Context.getObjCInterfaceType(Class);
1781 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1782 ReceiverType = CreateParsedType(T, TSInfo);
1783 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001784 }
1785 }
1786
1787 // Fall back: let the parser try to parse it as an instance message.
1788 return ObjCInstanceMessage;
1789}
Steve Naroff61f72cb2009-03-09 21:12:44 +00001790
John McCall60d7b3a2010-08-24 06:29:42 +00001791ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001792 SourceLocation SuperLoc,
1793 Selector Sel,
1794 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001795 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001796 SourceLocation RBracLoc,
1797 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001798 // Determine whether we are inside a method or not.
Eli Friedmanb942cb22012-02-03 22:47:37 +00001799 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregorf95861a2010-04-21 20:01:04 +00001800 if (!Method) {
1801 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1802 return ExprError();
1803 }
Chris Lattner85a932e2008-01-04 22:32:30 +00001804
Douglas Gregorf95861a2010-04-21 20:01:04 +00001805 ObjCInterfaceDecl *Class = Method->getClassInterface();
1806 if (!Class) {
1807 Diag(SuperLoc, diag::error_no_super_class_message)
1808 << Method->getDeclName();
1809 return ExprError();
1810 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001811
Douglas Gregorf95861a2010-04-21 20:01:04 +00001812 ObjCInterfaceDecl *Super = Class->getSuperClass();
1813 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001814 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +00001815 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1816 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001817 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +00001818 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001819
Douglas Gregorf95861a2010-04-21 20:01:04 +00001820 // We are in a method whose class has a superclass, so 'super'
1821 // is acting as a keyword.
1822 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +00001823 if (Sel.getMethodFamily() == OMF_dealloc)
1824 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00001825 if (Sel.getMethodFamily() == OMF_finalize)
1826 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +00001827
Douglas Gregorf95861a2010-04-21 20:01:04 +00001828 // Since we are in an instance method, this is an instance
1829 // message to the superclass instance.
1830 QualType SuperTy = Context.getObjCInterfaceType(Super);
1831 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +00001832 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001833 Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001834 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001835 }
Douglas Gregorf95861a2010-04-21 20:01:04 +00001836
1837 // Since we are in a class method, this is a class message to
1838 // the superclass.
1839 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1840 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001841 SuperLoc, Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001842 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001843}
1844
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001845
1846ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1847 bool isSuperReceiver,
1848 SourceLocation Loc,
1849 Selector Sel,
1850 ObjCMethodDecl *Method,
1851 MultiExprArg Args) {
1852 TypeSourceInfo *receiverTypeInfo = 0;
1853 if (!ReceiverType.isNull())
1854 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1855
1856 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1857 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1858 Sel, Method, Loc, Loc, Loc, Args,
1859 /*isImplicit=*/true);
1860
1861}
1862
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001863static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1864 unsigned DiagID,
1865 bool (*refactor)(const ObjCMessageExpr *,
1866 const NSAPI &, edit::Commit &)) {
1867 SourceLocation MsgLoc = Msg->getExprLoc();
1868 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
1869 return;
1870
1871 SourceManager &SM = S.SourceMgr;
1872 edit::Commit ECommit(SM, S.LangOpts);
1873 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1874 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1875 << Msg->getSelector() << Msg->getSourceRange();
1876 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1877 if (!ECommit.isCommitable())
1878 return;
1879 for (edit::Commit::edit_iterator
1880 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1881 const edit::Commit::Edit &Edit = *I;
1882 switch (Edit.Kind) {
1883 case edit::Commit::Act_Insert:
1884 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1885 Edit.Text,
1886 Edit.BeforePrev));
1887 break;
1888 case edit::Commit::Act_InsertFromRange:
1889 Builder.AddFixItHint(
1890 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1891 Edit.getInsertFromRange(SM),
1892 Edit.BeforePrev));
1893 break;
1894 case edit::Commit::Act_Remove:
1895 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1896 break;
1897 }
1898 }
1899 }
1900}
1901
1902static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1903 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1904 edit::rewriteObjCRedundantCallWithLiteral);
1905}
1906
Douglas Gregor2725ca82010-04-21 19:57:20 +00001907/// \brief Build an Objective-C class message expression.
1908///
1909/// This routine takes care of both normal class messages and
1910/// class messages to the superclass.
1911///
1912/// \param ReceiverTypeInfo Type source information that describes the
1913/// receiver of this message. This may be NULL, in which case we are
1914/// sending to the superclass and \p SuperLoc must be a valid source
1915/// location.
1916
1917/// \param ReceiverType The type of the object receiving the
1918/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1919/// type as that refers to. For a superclass send, this is the type of
1920/// the superclass.
1921///
1922/// \param SuperLoc The location of the "super" keyword in a
1923/// superclass message.
1924///
1925/// \param Sel The selector to which the message is being sent.
1926///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001927/// \param Method The method that this class message is invoking, if
1928/// already known.
1929///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001930/// \param LBracLoc The location of the opening square bracket ']'.
1931///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001932/// \param RBrac The location of the closing square bracket ']'.
1933///
1934/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001935ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001936 QualType ReceiverType,
1937 SourceLocation SuperLoc,
1938 Selector Sel,
1939 ObjCMethodDecl *Method,
1940 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001941 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001942 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001943 MultiExprArg ArgsIn,
1944 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001945 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001946 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001947 if (LBracLoc.isInvalid()) {
1948 Diag(Loc, diag::err_missing_open_square_message_send)
1949 << FixItHint::CreateInsertion(Loc, "[");
1950 LBracLoc = Loc;
1951 }
1952
Douglas Gregor92e986e2010-04-22 16:44:27 +00001953 if (ReceiverType->isDependentType()) {
1954 // If the receiver type is dependent, we can't type-check anything
1955 // at this point. Build a dependent expression.
1956 unsigned NumArgs = ArgsIn.size();
1957 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1958 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001959 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1960 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001961 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001962 makeArrayRef(Args, NumArgs),RBracLoc,
1963 isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001964 }
Chris Lattner15faee12010-04-12 05:38:43 +00001965
Douglas Gregor2725ca82010-04-21 19:57:20 +00001966 // Find the class to which we are sending this message.
1967 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001968 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1969 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001970 Diag(Loc, diag::err_invalid_receiver_class_message)
1971 << ReceiverType;
1972 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001973 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001974 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001975 // objc++ diagnoses during typename annotation.
David Blaikie4e4d0842012-03-11 07:00:24 +00001976 if (!getLangOpts().CPlusPlus)
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001977 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001978 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001979 if (!Method) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001980 SourceRange TypeRange
1981 = SuperLoc.isValid()? SourceRange(SuperLoc)
1982 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00001983 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikie4e4d0842012-03-11 07:00:24 +00001984 (getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001985 ? diag::err_arc_receiver_forward_class
1986 : diag::warn_receiver_forward_class),
1987 TypeRange)) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001988 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001989 Method = LookupFactoryMethodInGlobalPool(Sel,
1990 SourceRange(LBracLoc, RBracLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00001991 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001992 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1993 << Method->getDeclName();
1994 }
1995 if (!Method)
1996 Method = Class->lookupClassMethod(Sel);
1997
1998 // If we have an implementation in scope, check "private" methods.
1999 if (!Method)
2000 Method = LookupPrivateClassMethod(Sel, Class);
2001
2002 if (Method && DiagnoseUseOfDecl(Method, Loc))
2003 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00002004 }
Mike Stump1eb44332009-09-09 15:08:12 +00002005
Douglas Gregor2725ca82010-04-21 19:57:20 +00002006 // Check the argument types and determine the result type.
2007 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00002008 ExprValueKind VK = VK_RValue;
2009
Douglas Gregor2725ca82010-04-21 19:57:20 +00002010 unsigned NumArgs = ArgsIn.size();
2011 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00002012 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
2013 SuperLoc.isValid(), LBracLoc, RBracLoc,
2014 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00002015 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00002016
Douglas Gregor483dd2f2011-01-11 03:23:19 +00002017 if (Method && !Method->getResultType()->isVoidType() &&
2018 RequireCompleteType(LBracLoc, Method->getResultType(),
2019 diag::err_illegal_message_expr_incomplete_type))
2020 return ExprError();
2021
Douglas Gregor2725ca82010-04-21 19:57:20 +00002022 // Construct the appropriate ObjCMessageExpr.
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002023 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00002024 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00002025 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002026 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002027 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002028 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002029 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002030 else {
John McCallf89e55a2010-11-18 06:31:45 +00002031 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002032 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002033 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002034 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002035 if (!isImplicit)
2036 checkCocoaAPI(*this, Result);
2037 }
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002038 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00002039}
2040
Douglas Gregor2725ca82010-04-21 19:57:20 +00002041// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00002042// ArgExprs is optional - if it is present, the number of expressions
2043// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00002044ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00002045 ParsedType Receiver,
2046 Selector Sel,
2047 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002048 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor77328d12010-09-15 23:19:31 +00002049 SourceLocation RBracLoc,
2050 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002051 TypeSourceInfo *ReceiverTypeInfo;
2052 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2053 if (ReceiverType.isNull())
2054 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Douglas Gregor2725ca82010-04-21 19:57:20 +00002057 if (!ReceiverTypeInfo)
2058 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2059
2060 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00002061 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002062 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00002063}
2064
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002065ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2066 QualType ReceiverType,
2067 SourceLocation Loc,
2068 Selector Sel,
2069 ObjCMethodDecl *Method,
2070 MultiExprArg Args) {
2071 return BuildInstanceMessage(Receiver, ReceiverType,
2072 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2073 Sel, Method, Loc, Loc, Loc, Args,
2074 /*isImplicit=*/true);
2075}
2076
Douglas Gregor2725ca82010-04-21 19:57:20 +00002077/// \brief Build an Objective-C instance message expression.
2078///
2079/// This routine takes care of both normal instance messages and
2080/// instance messages to the superclass instance.
2081///
2082/// \param Receiver The expression that computes the object that will
2083/// receive this message. This may be empty, in which case we are
2084/// sending to the superclass instance and \p SuperLoc must be a valid
2085/// source location.
2086///
2087/// \param ReceiverType The (static) type of the object receiving the
2088/// message. When a \p Receiver expression is provided, this is the
2089/// same type as that expression. For a superclass instance send, this
2090/// is a pointer to the type of the superclass.
2091///
2092/// \param SuperLoc The location of the "super" keyword in a
2093/// superclass instance message.
2094///
2095/// \param Sel The selector to which the message is being sent.
2096///
Douglas Gregorf49bb082010-04-22 17:01:48 +00002097/// \param Method The method that this instance message is invoking, if
2098/// already known.
2099///
Douglas Gregor2725ca82010-04-21 19:57:20 +00002100/// \param LBracLoc The location of the opening square bracket ']'.
2101///
Douglas Gregor2725ca82010-04-21 19:57:20 +00002102/// \param RBrac The location of the closing square bracket ']'.
2103///
2104/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00002105ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002106 QualType ReceiverType,
2107 SourceLocation SuperLoc,
2108 Selector Sel,
2109 ObjCMethodDecl *Method,
2110 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002111 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002112 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002113 MultiExprArg ArgsIn,
2114 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00002115 // The location of the receiver.
2116 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2117
2118 if (LBracLoc.isInvalid()) {
2119 Diag(Loc, diag::err_missing_open_square_message_send)
2120 << FixItHint::CreateInsertion(Loc, "[");
2121 LBracLoc = Loc;
2122 }
2123
Douglas Gregor2725ca82010-04-21 19:57:20 +00002124 // If we have a receiver expression, perform appropriate promotions
2125 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00002126 if (Receiver) {
John McCall5acb0c92011-10-17 18:40:02 +00002127 if (Receiver->hasPlaceholderType()) {
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00002128 ExprResult Result;
2129 if (Receiver->getType() == Context.UnknownAnyTy)
2130 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2131 else
2132 Result = CheckPlaceholderExpr(Receiver);
2133 if (Result.isInvalid()) return ExprError();
2134 Receiver = Result.take();
John McCall5acb0c92011-10-17 18:40:02 +00002135 }
2136
Douglas Gregor92e986e2010-04-22 16:44:27 +00002137 if (Receiver->isTypeDependent()) {
2138 // If the receiver is type-dependent, we can't type-check anything
2139 // at this point. Build a dependent expression.
2140 unsigned NumArgs = ArgsIn.size();
2141 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2142 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2143 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00002144 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002145 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002146 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002147 RBracLoc, isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00002148 }
2149
Douglas Gregor2725ca82010-04-21 19:57:20 +00002150 // If necessary, apply function/array conversion to the receiver.
2151 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00002152 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2153 if (Result.isInvalid())
2154 return ExprError();
2155 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00002156 ReceiverType = Receiver->getType();
2157 }
2158
Douglas Gregorf49bb082010-04-22 17:01:48 +00002159 if (!Method) {
2160 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00002161 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002162 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00002163 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2164 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002165 SourceRange(LBracLoc, RBracLoc),
2166 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002167 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00002168 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002169 SourceRange(LBracLoc, RBracLoc),
2170 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002171 } else if (ReceiverType->isObjCClassType() ||
2172 ReceiverType->isObjCQualifiedClassType()) {
2173 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002174 // We allow sending a message to a qualified Class ("Class<foo>"), which
2175 // is ok as long as one of the protocols implements the selector (if not, warn).
2176 if (const ObjCObjectPointerType *QClassTy
2177 = ReceiverType->getAsObjCQualifiedClassType()) {
2178 // Search protocols for class methods.
2179 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2180 if (!Method) {
2181 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2182 // warn if instance method found for a Class message.
2183 if (Method) {
2184 Diag(Loc, diag::warn_instance_method_on_class_found)
2185 << Method->getSelector() << Sel;
Ted Kremenek3306ec12012-02-27 22:55:11 +00002186 Diag(Method->getLocation(), diag::note_method_declared_at)
2187 << Method->getDeclName();
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002188 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00002189 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002190 } else {
2191 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2192 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2193 // First check the public methods in the class interface.
2194 Method = ClassDecl->lookupClassMethod(Sel);
2195
2196 if (!Method)
2197 Method = LookupPrivateClassMethod(Sel, ClassDecl);
2198 }
2199 if (Method && DiagnoseUseOfDecl(Method, Loc))
2200 return ExprError();
2201 }
2202 if (!Method) {
2203 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00002204 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002205 Method = LookupFactoryMethodInGlobalPool(Sel,
2206 SourceRange(LBracLoc, RBracLoc),
2207 true);
2208 if (!Method) {
2209 // If no class (factory) method was found, check if an _instance_
2210 // method of the same name exists in the root class only.
2211 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002212 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002213 true);
2214 if (Method)
2215 if (const ObjCInterfaceDecl *ID =
2216 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2217 if (ID->getSuperClass())
2218 Diag(Loc, diag::warn_root_inst_method_not_found)
2219 << Sel << SourceRange(LBracLoc, RBracLoc);
2220 }
2221 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002222 }
2223 }
2224 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002225 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002226 ObjCInterfaceDecl* ClassDecl = 0;
2227
2228 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2229 // long as one of the protocols implements the selector (if not, warn).
2230 if (const ObjCObjectPointerType *QIdTy
2231 = ReceiverType->getAsObjCQualifiedIdType()) {
2232 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002233 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2234 if (!Method)
2235 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002236 } else if (const ObjCObjectPointerType *OCIType
2237 = ReceiverType->getAsObjCInterfacePointerType()) {
2238 // We allow sending a message to a pointer to an interface (an object).
2239 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00002240
Douglas Gregorb3029962011-11-14 22:10:01 +00002241 // Try to complete the type. Under ARC, this is a hard error from which
2242 // we don't try to recover.
2243 const ObjCInterfaceDecl *forwardClass = 0;
2244 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002245 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00002246 ? diag::err_arc_receiver_forward_instance
2247 : diag::warn_receiver_forward_instance,
2248 Receiver? Receiver->getSourceRange()
2249 : SourceRange(SuperLoc))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002250 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregorb3029962011-11-14 22:10:01 +00002251 return ExprError();
2252
2253 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00002254 Diag(Receiver ? Receiver->getLocStart()
2255 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00002256 Method = 0;
2257 } else {
2258 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCallf85e1932011-06-15 23:02:42 +00002259 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002260
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002261 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002262 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002263 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2264
Douglas Gregorf49bb082010-04-22 17:01:48 +00002265 if (!Method) {
2266 // If we have implementations in scope, check "private" methods.
2267 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
2268
David Blaikie4e4d0842012-03-11 07:00:24 +00002269 if (!Method && getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002270 Diag(Loc, diag::err_arc_may_not_respond)
2271 << OCIType->getPointeeType() << Sel;
2272 return ExprError();
2273 }
2274
Douglas Gregorc737acb2011-09-27 16:10:05 +00002275 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002276 // If we still haven't found a method, look in the global pool. This
2277 // behavior isn't very desirable, however we need it for GCC
2278 // compatibility. FIXME: should we deviate??
2279 if (OCIType->qual_empty()) {
2280 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002281 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002282 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002283 Diag(Loc, diag::warn_maynot_respond)
2284 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
2285 }
2286 }
2287 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002288 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00002289 return ExprError();
David Blaikie4e4d0842012-03-11 07:00:24 +00002290 } else if (!getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002291 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00002292 (ReceiverType->isPointerType() ||
2293 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002294 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00002295 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00002296 Diag(Loc, diag::warn_bad_receiver_type)
2297 << ReceiverType
2298 << Receiver->getSourceRange();
2299 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00002300 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002301 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00002302 else {
2303 // TODO: specialized warning on null receivers?
2304 bool IsNull = Receiver->isNullPointerConstant(Context,
2305 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00002306 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2307 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00002308 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002309 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00002310 } else {
John Wiegley429bb272011-04-08 18:41:53 +00002311 ExprResult ReceiverRes;
David Blaikie4e4d0842012-03-11 07:00:24 +00002312 if (getLangOpts().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00002313 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00002314 if (ReceiverRes.isUsable()) {
2315 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00002316 return BuildInstanceMessage(Receiver,
2317 ReceiverType,
2318 SuperLoc,
2319 Sel,
2320 Method,
2321 LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002322 SelectorLocs,
John Wiegley429bb272011-04-08 18:41:53 +00002323 RBracLoc,
2324 move(ArgsIn));
2325 } else {
2326 // Reject other random receiver types (e.g. structs).
2327 Diag(Loc, diag::err_bad_receiver_type)
2328 << ReceiverType << Receiver->getSourceRange();
2329 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00002330 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002331 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002332 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00002333 }
Mike Stump1eb44332009-09-09 15:08:12 +00002334
Douglas Gregor2725ca82010-04-21 19:57:20 +00002335 // Check the message arguments.
2336 unsigned NumArgs = ArgsIn.size();
2337 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2338 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00002339 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00002340 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2341 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00002342 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
2343 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00002344 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00002345 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00002346
Douglas Gregor483dd2f2011-01-11 03:23:19 +00002347 if (Method && !Method->getResultType()->isVoidType() &&
2348 RequireCompleteType(LBracLoc, Method->getResultType(),
2349 diag::err_illegal_message_expr_incomplete_type))
2350 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002351
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002352 SourceLocation SelLoc = SelectorLocs.front();
2353
John McCallf85e1932011-06-15 23:02:42 +00002354 // In ARC, forbid the user from sending messages to
2355 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002356 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002357 ObjCMethodFamily family =
2358 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2359 switch (family) {
2360 case OMF_init:
2361 if (Method)
2362 checkInitMethod(Method, ReceiverType);
2363
2364 case OMF_None:
2365 case OMF_alloc:
2366 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00002367 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00002368 case OMF_mutableCopy:
2369 case OMF_new:
2370 case OMF_self:
2371 break;
2372
2373 case OMF_dealloc:
2374 case OMF_retain:
2375 case OMF_release:
2376 case OMF_autorelease:
2377 case OMF_retainCount:
2378 Diag(Loc, diag::err_arc_illegal_explicit_message)
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002379 << Sel << SelLoc;
John McCallf85e1932011-06-15 23:02:42 +00002380 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002381
2382 case OMF_performSelector:
2383 if (Method && NumArgs >= 1) {
2384 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2385 Selector ArgSel = SelExp->getSelector();
2386 ObjCMethodDecl *SelMethod =
2387 LookupInstanceMethodInGlobalPool(ArgSel,
2388 SelExp->getSourceRange());
2389 if (!SelMethod)
2390 SelMethod =
2391 LookupFactoryMethodInGlobalPool(ArgSel,
2392 SelExp->getSourceRange());
2393 if (SelMethod) {
2394 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2395 switch (SelFamily) {
2396 case OMF_alloc:
2397 case OMF_copy:
2398 case OMF_mutableCopy:
2399 case OMF_new:
2400 case OMF_self:
2401 case OMF_init:
2402 // Issue error, unless ns_returns_not_retained.
2403 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2404 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002405 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002406 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002407 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2408 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002409 }
2410 break;
2411 default:
2412 // +0 call. OK. unless ns_returns_retained.
2413 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2414 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002415 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002416 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002417 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2418 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002419 }
2420 break;
2421 }
2422 }
2423 } else {
2424 // error (may leak).
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002425 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002426 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2427 }
2428 }
2429 break;
John McCallf85e1932011-06-15 23:02:42 +00002430 }
2431 }
2432
Douglas Gregor2725ca82010-04-21 19:57:20 +00002433 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00002434 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00002435 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00002436 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002437 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002438 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002439 makeArrayRef(Args, NumArgs), RBracLoc,
2440 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002441 else {
John McCallf89e55a2010-11-18 06:31:45 +00002442 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002443 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002444 makeArrayRef(Args, NumArgs), RBracLoc,
2445 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002446 if (!isImplicit)
2447 checkCocoaAPI(*this, Result);
2448 }
John McCallf85e1932011-06-15 23:02:42 +00002449
David Blaikie4e4d0842012-03-11 07:00:24 +00002450 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian98795562012-04-19 23:49:39 +00002451 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian878f8502012-04-04 20:05:25 +00002452
John McCallf85e1932011-06-15 23:02:42 +00002453 // In ARC, annotate delegate init calls.
2454 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00002455 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00002456 // Only consider init calls *directly* in init implementations,
2457 // not within blocks.
2458 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2459 if (method && method->getMethodFamily() == OMF_init) {
2460 // The implicit assignment to self means we also don't want to
2461 // consume the result.
2462 Result->setDelegateInitCall(true);
2463 return Owned(Result);
2464 }
2465 }
2466
2467 // In ARC, check for message sends which are likely to introduce
2468 // retain cycles.
2469 checkRetainCycles(Result);
2470 }
2471
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002472 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00002473}
2474
2475// ActOnInstanceMessage - used for both unary and keyword messages.
2476// ArgExprs is optional - if it is present, the number of expressions
2477// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00002478ExprResult Sema::ActOnInstanceMessage(Scope *S,
2479 Expr *Receiver,
2480 Selector Sel,
2481 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002482 ArrayRef<SourceLocation> SelectorLocs,
John McCall60d7b3a2010-08-24 06:29:42 +00002483 SourceLocation RBracLoc,
2484 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002485 if (!Receiver)
2486 return ExprError();
2487
John McCall9ae2f072010-08-23 23:25:46 +00002488 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00002489 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002490 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00002491}
Chris Lattnereca7be62008-04-07 05:30:13 +00002492
John McCallf85e1932011-06-15 23:02:42 +00002493enum ARCConversionTypeClass {
John McCall2cf031d2011-10-01 01:01:08 +00002494 /// int, void, struct A
John McCallf85e1932011-06-15 23:02:42 +00002495 ACTC_none,
John McCall2cf031d2011-10-01 01:01:08 +00002496
2497 /// id, void (^)()
John McCallf85e1932011-06-15 23:02:42 +00002498 ACTC_retainable,
John McCall2cf031d2011-10-01 01:01:08 +00002499
2500 /// id*, id***, void (^*)(),
2501 ACTC_indirectRetainable,
2502
2503 /// void* might be a normal C type, or it might a CF type.
2504 ACTC_voidPtr,
2505
2506 /// struct A*
2507 ACTC_coreFoundation
John McCallf85e1932011-06-15 23:02:42 +00002508};
John McCall2cf031d2011-10-01 01:01:08 +00002509static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2510 return (ACTC == ACTC_retainable ||
2511 ACTC == ACTC_coreFoundation ||
2512 ACTC == ACTC_voidPtr);
2513}
2514static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2515 return ACTC == ACTC_none ||
2516 ACTC == ACTC_voidPtr ||
2517 ACTC == ACTC_coreFoundation;
2518}
2519
John McCallf85e1932011-06-15 23:02:42 +00002520static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCall2cf031d2011-10-01 01:01:08 +00002521 bool isIndirect = false;
John McCallf85e1932011-06-15 23:02:42 +00002522
2523 // Ignore an outermost reference type.
John McCall2cf031d2011-10-01 01:01:08 +00002524 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCallf85e1932011-06-15 23:02:42 +00002525 type = ref->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002526 isIndirect = true;
2527 }
John McCallf85e1932011-06-15 23:02:42 +00002528
2529 // Drill through pointers and arrays recursively.
2530 while (true) {
2531 if (const PointerType *ptr = type->getAs<PointerType>()) {
2532 type = ptr->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002533
2534 // The first level of pointer may be the innermost pointer on a CF type.
2535 if (!isIndirect) {
2536 if (type->isVoidType()) return ACTC_voidPtr;
2537 if (type->isRecordType()) return ACTC_coreFoundation;
2538 }
John McCallf85e1932011-06-15 23:02:42 +00002539 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2540 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2541 } else {
2542 break;
2543 }
John McCall2cf031d2011-10-01 01:01:08 +00002544 isIndirect = true;
John McCallf85e1932011-06-15 23:02:42 +00002545 }
2546
John McCall2cf031d2011-10-01 01:01:08 +00002547 if (isIndirect) {
2548 if (type->isObjCARCBridgableType())
2549 return ACTC_indirectRetainable;
2550 return ACTC_none;
2551 }
2552
2553 if (type->isObjCARCBridgableType())
2554 return ACTC_retainable;
2555
2556 return ACTC_none;
John McCallf85e1932011-06-15 23:02:42 +00002557}
2558
2559namespace {
John McCall2cf031d2011-10-01 01:01:08 +00002560 /// A result from the cast checker.
2561 enum ACCResult {
2562 /// Cannot be casted.
2563 ACC_invalid,
2564
2565 /// Can be safely retained or not retained.
2566 ACC_bottom,
2567
2568 /// Can be casted at +0.
2569 ACC_plusZero,
2570
2571 /// Can be casted at +1.
2572 ACC_plusOne
2573 };
2574 ACCResult merge(ACCResult left, ACCResult right) {
2575 if (left == right) return left;
2576 if (left == ACC_bottom) return right;
2577 if (right == ACC_bottom) return left;
2578 return ACC_invalid;
2579 }
2580
2581 /// A checker which white-lists certain expressions whose conversion
2582 /// to or from retainable type would otherwise be forbidden in ARC.
2583 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2584 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2585
John McCallf85e1932011-06-15 23:02:42 +00002586 ASTContext &Context;
John McCall2cf031d2011-10-01 01:01:08 +00002587 ARCConversionTypeClass SourceClass;
2588 ARCConversionTypeClass TargetClass;
2589
2590 static bool isCFType(QualType type) {
2591 // Someday this can use ns_bridged. For now, it has to do this.
2592 return type->isCARCBridgableType();
John McCallf85e1932011-06-15 23:02:42 +00002593 }
John McCall2cf031d2011-10-01 01:01:08 +00002594
2595 public:
2596 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2597 ARCConversionTypeClass target)
2598 : Context(Context), SourceClass(source), TargetClass(target) {}
2599
2600 using super::Visit;
2601 ACCResult Visit(Expr *e) {
2602 return super::Visit(e->IgnoreParens());
2603 }
2604
2605 ACCResult VisitStmt(Stmt *s) {
2606 return ACC_invalid;
2607 }
2608
2609 /// Null pointer constants can be casted however you please.
2610 ACCResult VisitExpr(Expr *e) {
2611 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2612 return ACC_bottom;
2613 return ACC_invalid;
2614 }
2615
2616 /// Objective-C string literals can be safely casted.
2617 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2618 // If we're casting to any retainable type, go ahead. Global
2619 // strings are immune to retains, so this is bottom.
2620 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2621
2622 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002623 }
2624
John McCall2cf031d2011-10-01 01:01:08 +00002625 /// Look through certain implicit and explicit casts.
2626 ACCResult VisitCastExpr(CastExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002627 switch (e->getCastKind()) {
2628 case CK_NullToPointer:
John McCall2cf031d2011-10-01 01:01:08 +00002629 return ACC_bottom;
2630
John McCallf85e1932011-06-15 23:02:42 +00002631 case CK_NoOp:
2632 case CK_LValueToRValue:
2633 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002634 case CK_CPointerToObjCPointerCast:
2635 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002636 case CK_AnyPointerToBlockPointerCast:
2637 return Visit(e->getSubExpr());
John McCall2cf031d2011-10-01 01:01:08 +00002638
John McCallf85e1932011-06-15 23:02:42 +00002639 default:
John McCall2cf031d2011-10-01 01:01:08 +00002640 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002641 }
2642 }
John McCall2cf031d2011-10-01 01:01:08 +00002643
2644 /// Look through unary extension.
2645 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002646 return Visit(e->getSubExpr());
2647 }
John McCall2cf031d2011-10-01 01:01:08 +00002648
2649 /// Ignore the LHS of a comma operator.
2650 ACCResult VisitBinComma(BinaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002651 return Visit(e->getRHS());
2652 }
John McCall2cf031d2011-10-01 01:01:08 +00002653
2654 /// Conditional operators are okay if both sides are okay.
2655 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2656 ACCResult left = Visit(e->getTrueExpr());
2657 if (left == ACC_invalid) return ACC_invalid;
2658 return merge(left, Visit(e->getFalseExpr()));
John McCallf85e1932011-06-15 23:02:42 +00002659 }
John McCall2cf031d2011-10-01 01:01:08 +00002660
John McCall4b9c2d22011-11-06 09:01:30 +00002661 /// Look through pseudo-objects.
2662 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2663 // If we're getting here, we should always have a result.
2664 return Visit(e->getResultExpr());
2665 }
2666
John McCall2cf031d2011-10-01 01:01:08 +00002667 /// Statement expressions are okay if their result expression is okay.
2668 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002669 return Visit(e->getSubStmt()->body_back());
2670 }
John McCallf85e1932011-06-15 23:02:42 +00002671
John McCall2cf031d2011-10-01 01:01:08 +00002672 /// Some declaration references are okay.
2673 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2674 // References to global constants from system headers are okay.
2675 // These are things like 'kCFStringTransformToLatin'. They are
2676 // can also be assumed to be immune to retains.
2677 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2678 if (isAnyRetainable(TargetClass) &&
2679 isAnyRetainable(SourceClass) &&
2680 var &&
2681 var->getStorageClass() == SC_Extern &&
2682 var->getType().isConstQualified() &&
2683 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2684 return ACC_bottom;
2685 }
2686
2687 // Nothing else.
2688 return ACC_invalid;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00002689 }
John McCall2cf031d2011-10-01 01:01:08 +00002690
2691 /// Some calls are okay.
2692 ACCResult VisitCallExpr(CallExpr *e) {
2693 if (FunctionDecl *fn = e->getDirectCallee())
2694 if (ACCResult result = checkCallToFunction(fn))
2695 return result;
2696
2697 return super::VisitCallExpr(e);
2698 }
2699
2700 ACCResult checkCallToFunction(FunctionDecl *fn) {
2701 // Require a CF*Ref return type.
2702 if (!isCFType(fn->getResultType()))
2703 return ACC_invalid;
2704
2705 if (!isAnyRetainable(TargetClass))
2706 return ACC_invalid;
2707
2708 // Honor an explicit 'not retained' attribute.
2709 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2710 return ACC_plusZero;
2711
2712 // Honor an explicit 'retained' attribute, except that for
2713 // now we're not going to permit implicit handling of +1 results,
2714 // because it's a bit frightening.
2715 if (fn->hasAttr<CFReturnsRetainedAttr>())
2716 return ACC_invalid; // ACC_plusOne if we start accepting this
2717
2718 // Recognize this specific builtin function, which is used by CFSTR.
2719 unsigned builtinID = fn->getBuiltinID();
2720 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2721 return ACC_bottom;
2722
2723 // Otherwise, don't do anything implicit with an unaudited function.
2724 if (!fn->hasAttr<CFAuditedTransferAttr>())
2725 return ACC_invalid;
2726
2727 // Otherwise, it's +0 unless it follows the create convention.
2728 if (ento::coreFoundation::followsCreateRule(fn))
2729 return ACC_invalid; // ACC_plusOne if we start accepting this
2730
2731 return ACC_plusZero;
2732 }
2733
2734 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2735 return checkCallToMethod(e->getMethodDecl());
2736 }
2737
2738 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2739 ObjCMethodDecl *method;
2740 if (e->isExplicitProperty())
2741 method = e->getExplicitProperty()->getGetterMethodDecl();
2742 else
2743 method = e->getImplicitPropertyGetter();
2744 return checkCallToMethod(method);
2745 }
2746
2747 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2748 if (!method) return ACC_invalid;
2749
2750 // Check for message sends to functions returning CF types. We
2751 // just obey the Cocoa conventions with these, even though the
2752 // return type is CF.
2753 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2754 return ACC_invalid;
2755
2756 // If the method is explicitly marked not-retained, it's +0.
2757 if (method->hasAttr<CFReturnsNotRetainedAttr>())
2758 return ACC_plusZero;
2759
2760 // If the method is explicitly marked as returning retained, or its
2761 // selector follows a +1 Cocoa convention, treat it as +1.
2762 if (method->hasAttr<CFReturnsRetainedAttr>())
2763 return ACC_plusOne;
2764
2765 switch (method->getSelector().getMethodFamily()) {
2766 case OMF_alloc:
2767 case OMF_copy:
2768 case OMF_mutableCopy:
2769 case OMF_new:
2770 return ACC_plusOne;
2771
2772 default:
2773 // Otherwise, treat it as +0.
2774 return ACC_plusZero;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00002775 }
2776 }
John McCall2cf031d2011-10-01 01:01:08 +00002777 };
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00002778}
2779
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002780static bool
2781KnownName(Sema &S, const char *name) {
2782 LookupResult R(S, &S.Context.Idents.get(name), SourceLocation(),
2783 Sema::LookupOrdinaryName);
2784 return S.LookupName(R, S.TUScope, false);
2785}
2786
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002787static void addFixitForObjCARCConversion(Sema &S,
2788 DiagnosticBuilder &DiagB,
2789 Sema::CheckedConversionKind CCK,
2790 SourceLocation afterLParen,
2791 QualType castType,
2792 Expr *castExpr,
2793 const char *bridgeKeyword,
2794 const char *CFBridgeName) {
2795 // We handle C-style and implicit casts here.
2796 switch (CCK) {
2797 case Sema::CCK_ImplicitConversion:
2798 case Sema::CCK_CStyleCast:
2799 break;
2800 case Sema::CCK_FunctionalCast:
2801 case Sema::CCK_OtherCast:
2802 return;
2803 }
2804
2805 if (CFBridgeName) {
2806 Expr *castedE = castExpr;
2807 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2808 castedE = CCE->getSubExpr();
2809 castedE = castedE->IgnoreImpCasts();
2810 SourceRange range = castedE->getSourceRange();
2811 if (isa<ParenExpr>(castedE)) {
2812 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2813 CFBridgeName));
2814 } else {
2815 std::string namePlusParen = CFBridgeName;
2816 namePlusParen += "(";
2817 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2818 namePlusParen));
2819 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2820 S.PP.getLocForEndOfToken(range.getEnd()),
2821 ")"));
2822 }
2823 return;
2824 }
2825
2826 if (CCK == Sema::CCK_CStyleCast) {
2827 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
2828 } else {
2829 std::string castCode = "(";
2830 castCode += bridgeKeyword;
2831 castCode += castType.getAsString();
2832 castCode += ")";
2833 Expr *castedE = castExpr->IgnoreImpCasts();
2834 SourceRange range = castedE->getSourceRange();
2835 if (isa<ParenExpr>(castedE)) {
2836 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2837 castCode));
2838 } else {
2839 castCode += "(";
2840 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2841 castCode));
2842 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2843 S.PP.getLocForEndOfToken(range.getEnd()),
2844 ")"));
2845 }
2846 }
2847}
2848
John McCall5acb0c92011-10-17 18:40:02 +00002849static void
2850diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
2851 QualType castType, ARCConversionTypeClass castACTC,
2852 Expr *castExpr, ARCConversionTypeClass exprACTC,
2853 Sema::CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00002854 SourceLocation loc =
John McCall2cf031d2011-10-01 01:01:08 +00002855 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00002856
John McCall5acb0c92011-10-17 18:40:02 +00002857 if (S.makeUnavailableInSystemHeader(loc,
John McCall2cf031d2011-10-01 01:01:08 +00002858 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCallf85e1932011-06-15 23:02:42 +00002859 return;
John McCall5acb0c92011-10-17 18:40:02 +00002860
2861 QualType castExprType = castExpr->getType();
John McCallf85e1932011-06-15 23:02:42 +00002862
John McCall71c482c2011-06-17 06:50:50 +00002863 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00002864 switch (exprACTC) {
John McCall2cf031d2011-10-01 01:01:08 +00002865 case ACTC_none:
2866 case ACTC_coreFoundation:
2867 case ACTC_voidPtr:
2868 srcKind = (castExprType->isPointerType() ? 1 : 0);
2869 break;
2870 case ACTC_retainable:
2871 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
2872 break;
2873 case ACTC_indirectRetainable:
2874 srcKind = 4;
2875 break;
John McCallf85e1932011-06-15 23:02:42 +00002876 }
2877
John McCall5acb0c92011-10-17 18:40:02 +00002878 // Check whether this could be fixed with a bridge cast.
2879 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
2880 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCallf85e1932011-06-15 23:02:42 +00002881
John McCall5acb0c92011-10-17 18:40:02 +00002882 // Bridge from an ARC type to a CF type.
2883 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002884
John McCall5acb0c92011-10-17 18:40:02 +00002885 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2886 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2887 << 2 // of C pointer type
2888 << castExprType
2889 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
2890 << castType
2891 << castRange
2892 << castExpr->getSourceRange();
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002893 bool br = KnownName(S, "CFBridgingRelease");
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002894 {
2895 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2896 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2897 castType, castExpr, "__bridge ", 0);
2898 }
2899 {
2900 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_transfer)
2901 << castExprType << br;
2902 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2903 castType, castExpr, "__bridge_transfer ",
2904 br ? "CFBridgingRelease" : 0);
2905 }
John McCall5acb0c92011-10-17 18:40:02 +00002906
2907 return;
2908 }
2909
2910 // Bridge from a CF type to an ARC type.
2911 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002912 bool br = KnownName(S, "CFBridgingRetain");
John McCall5acb0c92011-10-17 18:40:02 +00002913 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2914 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2915 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
2916 << castExprType
2917 << 2 // to C pointer type
2918 << castType
2919 << castRange
2920 << castExpr->getSourceRange();
2921
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002922 {
2923 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2924 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2925 castType, castExpr, "__bridge ", 0);
2926 }
2927 {
2928 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_retained)
2929 << castType << br;
2930 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2931 castType, castExpr, "__bridge_retained ",
2932 br ? "CFBridgingRetain" : 0);
2933 }
John McCall5acb0c92011-10-17 18:40:02 +00002934
2935 return;
John McCallf85e1932011-06-15 23:02:42 +00002936 }
2937
John McCall5acb0c92011-10-17 18:40:02 +00002938 S.Diag(loc, diag::err_arc_mismatched_cast)
2939 << (CCK != Sema::CCK_ImplicitConversion)
2940 << srcKind << castExprType << castType
John McCallf85e1932011-06-15 23:02:42 +00002941 << castRange << castExpr->getSourceRange();
2942}
2943
John McCall5acb0c92011-10-17 18:40:02 +00002944Sema::ARCConversionResult
2945Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
2946 Expr *&castExpr, CheckedConversionKind CCK) {
2947 QualType castExprType = castExpr->getType();
2948
2949 // For the purposes of the classification, we assume reference types
2950 // will bind to temporaries.
2951 QualType effCastType = castType;
2952 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
2953 effCastType = ref->getPointeeType();
2954
2955 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
2956 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002957 if (exprACTC == castACTC) {
2958 // check for viablity and report error if casting an rvalue to a
2959 // life-time qualifier.
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002960 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002961 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002962 (castType != castExprType)) {
2963 const Type *DT = castType.getTypePtr();
2964 QualType QDT = castType;
2965 // We desugar some types but not others. We ignore those
2966 // that cannot happen in a cast; i.e. auto, and those which
2967 // should not be de-sugared; i.e typedef.
2968 if (const ParenType *PT = dyn_cast<ParenType>(DT))
2969 QDT = PT->desugar();
2970 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
2971 QDT = TP->desugar();
2972 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
2973 QDT = AT->desugar();
2974 if (QDT != castType &&
2975 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
2976 SourceLocation loc =
2977 (castRange.isValid() ? castRange.getBegin()
2978 : castExpr->getExprLoc());
2979 Diag(loc, diag::err_arc_nolifetime_behavior);
2980 }
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002981 }
2982 return ACR_okay;
2983 }
2984
John McCall5acb0c92011-10-17 18:40:02 +00002985 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
2986
2987 // Allow all of these types to be cast to integer types (but not
2988 // vice-versa).
2989 if (castACTC == ACTC_none && castType->isIntegralType(Context))
2990 return ACR_okay;
2991
2992 // Allow casts between pointers to lifetime types (e.g., __strong id*)
2993 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
2994 // must be explicit.
2995 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
2996 return ACR_okay;
2997 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
2998 CCK != CCK_ImplicitConversion)
2999 return ACR_okay;
3000
3001 switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
3002 // For invalid casts, fall through.
3003 case ACC_invalid:
3004 break;
3005
3006 // Do nothing for both bottom and +0.
3007 case ACC_bottom:
3008 case ACC_plusZero:
3009 return ACR_okay;
3010
3011 // If the result is +1, consume it here.
3012 case ACC_plusOne:
3013 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
3014 CK_ARCConsumeObject, castExpr,
3015 0, VK_RValue);
3016 ExprNeedsCleanups = true;
3017 return ACR_okay;
3018 }
3019
3020 // If this is a non-implicit cast from id or block type to a
3021 // CoreFoundation type, delay complaining in case the cast is used
3022 // in an acceptable context.
3023 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3024 CCK != CCK_ImplicitConversion)
3025 return ACR_unbridged;
3026
3027 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3028 castExpr, exprACTC, CCK);
3029 return ACR_okay;
3030}
3031
3032/// Given that we saw an expression with the ARCUnbridgedCastTy
3033/// placeholder type, complain bitterly.
3034void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3035 // We expect the spurious ImplicitCastExpr to already have been stripped.
3036 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3037 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3038
3039 SourceRange castRange;
3040 QualType castType;
3041 CheckedConversionKind CCK;
3042
3043 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3044 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3045 castType = cast->getTypeAsWritten();
3046 CCK = CCK_CStyleCast;
3047 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3048 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3049 castType = cast->getTypeAsWritten();
3050 CCK = CCK_OtherCast;
3051 } else {
3052 castType = cast->getType();
3053 CCK = CCK_ImplicitConversion;
3054 }
3055
3056 ARCConversionTypeClass castACTC =
3057 classifyTypeForARCConversion(castType.getNonReferenceType());
3058
3059 Expr *castExpr = realCast->getSubExpr();
3060 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3061
3062 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3063 castExpr, ACTC_retainable, CCK);
3064}
3065
3066/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3067/// type, remove the placeholder cast.
3068Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3069 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3070
3071 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3072 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3073 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3074 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3075 assert(uo->getOpcode() == UO_Extension);
3076 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3077 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3078 sub->getValueKind(), sub->getObjectKind(),
3079 uo->getOperatorLoc());
3080 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3081 assert(!gse->isResultDependent());
3082
3083 unsigned n = gse->getNumAssocs();
3084 SmallVector<Expr*, 4> subExprs(n);
3085 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3086 for (unsigned i = 0; i != n; ++i) {
3087 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3088 Expr *sub = gse->getAssocExpr(i);
3089 if (i == gse->getResultIndex())
3090 sub = stripARCUnbridgedCast(sub);
3091 subExprs[i] = sub;
3092 }
3093
3094 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3095 gse->getControllingExpr(),
3096 subTypes.data(), subExprs.data(),
3097 n, gse->getDefaultLoc(),
3098 gse->getRParenLoc(),
3099 gse->containsUnexpandedParameterPack(),
3100 gse->getResultIndex());
3101 } else {
3102 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3103 return cast<ImplicitCastExpr>(e)->getSubExpr();
3104 }
3105}
3106
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00003107bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3108 QualType exprType) {
3109 QualType canCastType =
3110 Context.getCanonicalType(castType).getUnqualifiedType();
3111 QualType canExprType =
3112 Context.getCanonicalType(exprType).getUnqualifiedType();
3113 if (isa<ObjCObjectPointerType>(canCastType) &&
3114 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3115 canExprType->isObjCObjectPointerType()) {
3116 if (const ObjCObjectPointerType *ObjT =
3117 canExprType->getAs<ObjCObjectPointerType>())
3118 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
3119 return false;
3120 }
3121 return true;
3122}
3123
John McCall7e5e5f42011-07-07 06:58:02 +00003124/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3125static Expr *maybeUndoReclaimObject(Expr *e) {
3126 // For now, we just undo operands that are *immediately* reclaim
3127 // expressions, which prevents the vast majority of potential
3128 // problems here. To catch them all, we'd need to rebuild arbitrary
3129 // value-propagating subexpressions --- we can't reliably rebuild
3130 // in-place because of expression sharing.
3131 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00003132 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00003133 return ice->getSubExpr();
3134
3135 return e;
3136}
3137
John McCallf85e1932011-06-15 23:02:42 +00003138ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3139 ObjCBridgeCastKind Kind,
3140 SourceLocation BridgeKeywordLoc,
3141 TypeSourceInfo *TSInfo,
3142 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00003143 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3144 if (SubResult.isInvalid()) return ExprError();
3145 SubExpr = SubResult.take();
3146
John McCallf85e1932011-06-15 23:02:42 +00003147 QualType T = TSInfo->getType();
3148 QualType FromType = SubExpr->getType();
3149
John McCall1d9b3b22011-09-09 05:25:32 +00003150 CastKind CK;
3151
John McCallf85e1932011-06-15 23:02:42 +00003152 bool MustConsume = false;
3153 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3154 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00003155 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00003156 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3157 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00003158 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3159 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00003160 switch (Kind) {
3161 case OBC_Bridge:
3162 break;
3163
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003164 case OBC_BridgeRetained: {
3165 bool br = KnownName(*this, "CFBridgingRelease");
John McCallf85e1932011-06-15 23:02:42 +00003166 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3167 << 2
3168 << FromType
3169 << (T->isBlockPointerType()? 1 : 0)
3170 << T
3171 << SubExpr->getSourceRange()
3172 << Kind;
3173 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3174 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3175 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003176 << FromType << br
John McCallf85e1932011-06-15 23:02:42 +00003177 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003178 br ? "CFBridgingRelease "
3179 : "__bridge_transfer ");
John McCallf85e1932011-06-15 23:02:42 +00003180
3181 Kind = OBC_Bridge;
3182 break;
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003183 }
John McCallf85e1932011-06-15 23:02:42 +00003184
3185 case OBC_BridgeTransfer:
3186 // We must consume the Objective-C object produced by the cast.
3187 MustConsume = true;
3188 break;
3189 }
3190 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3191 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00003192 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00003193 switch (Kind) {
3194 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00003195 // Reclaiming a value that's going to be __bridge-casted to CF
3196 // is very dangerous, so we don't do it.
3197 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00003198 break;
3199
3200 case OBC_BridgeRetained:
3201 // Produce the object before casting it.
3202 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00003203 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00003204 SubExpr, 0, VK_RValue);
3205 break;
3206
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003207 case OBC_BridgeTransfer: {
3208 bool br = KnownName(*this, "CFBridgingRetain");
John McCallf85e1932011-06-15 23:02:42 +00003209 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3210 << (FromType->isBlockPointerType()? 1 : 0)
3211 << FromType
3212 << 2
3213 << T
3214 << SubExpr->getSourceRange()
3215 << Kind;
3216
3217 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3218 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3219 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003220 << T << br
3221 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3222 br ? "CFBridgingRetain " : "__bridge_retained");
John McCallf85e1932011-06-15 23:02:42 +00003223
3224 Kind = OBC_Bridge;
3225 break;
3226 }
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003227 }
John McCallf85e1932011-06-15 23:02:42 +00003228 } else {
3229 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3230 << FromType << T << Kind
3231 << SubExpr->getSourceRange()
3232 << TSInfo->getTypeLoc().getSourceRange();
3233 return ExprError();
3234 }
3235
John McCall1d9b3b22011-09-09 05:25:32 +00003236 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00003237 BridgeKeywordLoc,
3238 TSInfo, SubExpr);
3239
3240 if (MustConsume) {
3241 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00003242 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00003243 0, VK_RValue);
3244 }
3245
3246 return Result;
3247}
3248
3249ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3250 SourceLocation LParenLoc,
3251 ObjCBridgeCastKind Kind,
3252 SourceLocation BridgeKeywordLoc,
3253 ParsedType Type,
3254 SourceLocation RParenLoc,
3255 Expr *SubExpr) {
3256 TypeSourceInfo *TSInfo = 0;
3257 QualType T = GetTypeFromParser(Type, &TSInfo);
3258 if (!TSInfo)
3259 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3260 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3261 SubExpr);
3262}