blob: b45b7c92ce280b6709099e3cc57abe85fb1d708a [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) {
217 S.Diag(Loc, diag::err_undeclared_nsnumber_method) << Sel;
218 return 0;
219 }
220
221 // Make sure the return type is reasonable.
222 if (!Method->getResultType()->isObjCObjectPointerType()) {
223 S.Diag(Loc, diag::err_objc_literal_method_sig)
224 << Sel;
225 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
226 << Method->getResultType();
227 return 0;
228 }
229
230 // Note: if the parameter type is out-of-line, we'll catch it later in the
231 // implicit conversion.
232
233 S.NSNumberLiteralMethods[*Kind] = Method;
234 return Method;
235}
236
Patrick Beardeb382ec2012-04-19 00:25:12 +0000237/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
238/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000239ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000240 // Determine the type of the literal.
241 QualType NumberType = Number->getType();
242 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
243 // In C, character literals have type 'int'. That's not the type we want
244 // to use to determine the Objective-c literal kind.
245 switch (Char->getKind()) {
246 case CharacterLiteral::Ascii:
247 NumberType = Context.CharTy;
248 break;
249
250 case CharacterLiteral::Wide:
251 NumberType = Context.getWCharType();
252 break;
253
254 case CharacterLiteral::UTF16:
255 NumberType = Context.Char16Ty;
256 break;
257
258 case CharacterLiteral::UTF32:
259 NumberType = Context.Char32Ty;
260 break;
261 }
262 }
263
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000264 // Look for the appropriate method within NSNumber.
265 // Construct the literal.
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000266 SourceRange NR(Number->getSourceRange());
Patrick Beardeb382ec2012-04-19 00:25:12 +0000267 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000268 true, NR);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000269 if (!Method)
270 return ExprError();
271
272 // Convert the number to the type that the parameter expects.
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000273 ParmVarDecl *ParamDecl = Method->param_begin()[0];
274 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
275 ParamDecl);
276 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
277 SourceLocation(),
278 Owned(Number));
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000279 if (ConvertedNumber.isInvalid())
280 return ExprError();
281 Number = ConvertedNumber.get();
282
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000283 // Use the effective source range of the literal, including the leading '@'.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000284 return MaybeBindToTemporary(
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000285 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
286 SourceRange(AtLoc, NR.getEnd())));
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000287}
288
289ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
290 SourceLocation ValueLoc,
291 bool Value) {
292 ExprResult Inner;
David Blaikie4e4d0842012-03-11 07:00:24 +0000293 if (getLangOpts().CPlusPlus) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000294 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
295 } else {
296 // C doesn't actually have a way to represent literal values of type
297 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
298 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
299 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
300 CK_IntegralToBoolean);
301 }
302
303 return BuildObjCNumericLiteral(AtLoc, Inner.get());
304}
305
306/// \brief Check that the given expression is a valid element of an Objective-C
307/// collection literal.
308static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
309 QualType T) {
310 // If the expression is type-dependent, there's nothing for us to do.
311 if (Element->isTypeDependent())
312 return Element;
313
314 ExprResult Result = S.CheckPlaceholderExpr(Element);
315 if (Result.isInvalid())
316 return ExprError();
317 Element = Result.get();
318
319 // In C++, check for an implicit conversion to an Objective-C object pointer
320 // type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000321 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000322 InitializedEntity Entity
323 = InitializedEntity::InitializeParameter(S.Context, T, /*Consumed=*/false);
324 InitializationKind Kind
325 = InitializationKind::CreateCopy(Element->getLocStart(), SourceLocation());
326 InitializationSequence Seq(S, Entity, Kind, &Element, 1);
327 if (!Seq.Failed())
328 return Seq.Perform(S, Entity, Kind, MultiExprArg(S, &Element, 1));
329 }
330
331 Expr *OrigElement = Element;
332
333 // Perform lvalue-to-rvalue conversion.
334 Result = S.DefaultLvalueConversion(Element);
335 if (Result.isInvalid())
336 return ExprError();
337 Element = Result.get();
338
339 // Make sure that we have an Objective-C pointer type or block.
340 if (!Element->getType()->isObjCObjectPointerType() &&
341 !Element->getType()->isBlockPointerType()) {
342 bool Recovered = false;
343
344 // If this is potentially an Objective-C numeric literal, add the '@'.
345 if (isa<IntegerLiteral>(OrigElement) ||
346 isa<CharacterLiteral>(OrigElement) ||
347 isa<FloatingLiteral>(OrigElement) ||
348 isa<ObjCBoolLiteralExpr>(OrigElement) ||
349 isa<CXXBoolLiteralExpr>(OrigElement)) {
350 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
351 int Which = isa<CharacterLiteral>(OrigElement) ? 1
352 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
353 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
354 : 3;
355
356 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
357 << Which << OrigElement->getSourceRange()
358 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
359
360 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
361 OrigElement);
362 if (Result.isInvalid())
363 return ExprError();
364
365 Element = Result.get();
366 Recovered = true;
367 }
368 }
369 // If this is potentially an Objective-C string literal, add the '@'.
370 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
371 if (String->isAscii()) {
372 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
373 << 0 << OrigElement->getSourceRange()
374 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
375
376 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
377 if (Result.isInvalid())
378 return ExprError();
379
380 Element = Result.get();
381 Recovered = true;
382 }
383 }
384
385 if (!Recovered) {
386 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
387 << Element->getType();
388 return ExprError();
389 }
390 }
391
392 // Make sure that the element has the type that the container factory
393 // function expects.
394 return S.PerformCopyInitialization(
395 InitializedEntity::InitializeParameter(S.Context, T,
396 /*Consumed=*/false),
397 Element->getLocStart(), Element);
398}
399
Patrick Beardeb382ec2012-04-19 00:25:12 +0000400ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
401 if (ValueExpr->isTypeDependent()) {
402 ObjCBoxedExpr *BoxedExpr =
403 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR);
404 return Owned(BoxedExpr);
405 }
406 ObjCMethodDecl *BoxingMethod = NULL;
407 QualType BoxedType;
408 // Convert the expression to an RValue, so we can check for pointer types...
409 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
410 if (RValue.isInvalid()) {
411 return ExprError();
412 }
413 ValueExpr = RValue.get();
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000414 QualType ValueType(ValueExpr->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +0000415 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
416 QualType PointeeType = PT->getPointeeType();
417 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
418
419 if (!NSStringDecl) {
420 IdentifierInfo *NSStringId =
421 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
422 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
423 SR.getBegin(), LookupOrdinaryName);
424 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
425 if (!NSStringDecl) {
426 if (getLangOpts().DebuggerObjCLiteral) {
427 // Support boxed expressions in the debugger w/o NSString declaration.
428 NSStringDecl = ObjCInterfaceDecl::Create(Context,
429 Context.getTranslationUnitDecl(),
430 SourceLocation(), NSStringId,
431 0, SourceLocation());
432 } else {
433 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
434 return ExprError();
435 }
436 } else if (!NSStringDecl->hasDefinition()) {
437 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
438 return ExprError();
439 }
440 assert(NSStringDecl && "NSStringDecl should not be NULL");
441 NSStringPointer =
442 Context.getObjCObjectPointerType(Context.getObjCInterfaceType(NSStringDecl));
443 }
444
445 if (!StringWithUTF8StringMethod) {
446 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
447 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
448
449 // Look for the appropriate method within NSString.
450 StringWithUTF8StringMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
451 if (!StringWithUTF8StringMethod && getLangOpts().DebuggerObjCLiteral) {
452 // Debugger needs to work even if NSString hasn't been defined.
453 TypeSourceInfo *ResultTInfo = 0;
454 ObjCMethodDecl *M =
455 ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(),
456 stringWithUTF8String, NSStringPointer,
457 ResultTInfo, NSStringDecl,
458 /*isInstance=*/false, /*isVariadic=*/false,
459 /*isSynthesized=*/false,
460 /*isImplicitlyDeclared=*/true,
461 /*isDefined=*/false,
462 ObjCMethodDecl::Required,
463 /*HasRelatedResultType=*/false);
464 ParmVarDecl *value =
465 ParmVarDecl::Create(Context, M,
466 SourceLocation(), SourceLocation(),
467 &Context.Idents.get("value"),
468 Context.getPointerType(Context.CharTy.withConst()),
469 /*TInfo=*/0,
470 SC_None, SC_None, 0);
471 M->setMethodParams(Context, value, ArrayRef<SourceLocation>());
472 StringWithUTF8StringMethod = M;
473 }
474 assert(StringWithUTF8StringMethod &&
475 "StringWithUTF8StringMethod should not be NULL");
476 }
477
478 BoxingMethod = StringWithUTF8StringMethod;
479 BoxedType = NSStringPointer;
480 }
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000481 } else if (ValueType->isBuiltinType()) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000482 // The other types we support are numeric, char and BOOL/bool. We could also
483 // provide limited support for structure types, such as NSRange, NSRect, and
484 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
485 // for more details.
486
487 // Check for a top-level character literal.
488 if (const CharacterLiteral *Char =
489 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
490 // In C, character literals have type 'int'. That's not the type we want
491 // to use to determine the Objective-c literal kind.
492 switch (Char->getKind()) {
493 case CharacterLiteral::Ascii:
494 ValueType = Context.CharTy;
495 break;
496
497 case CharacterLiteral::Wide:
498 ValueType = Context.getWCharType();
499 break;
500
501 case CharacterLiteral::UTF16:
502 ValueType = Context.Char16Ty;
503 break;
504
505 case CharacterLiteral::UTF32:
506 ValueType = Context.Char32Ty;
507 break;
508 }
509 }
510
511 // FIXME: Do I need to do anything special with BoolTy expressions?
512
513 // Look for the appropriate method within NSNumber.
514 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
515 BoxedType = NSNumberPointer;
516 }
517
518 if (!BoxingMethod) {
519 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
520 << ValueType << ValueExpr->getSourceRange();
521 return ExprError();
522 }
523
524 // Convert the expression to the type that the parameter requires.
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000525 ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0];
526 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
527 ParamDecl);
528 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
529 SourceLocation(),
530 Owned(ValueExpr));
Patrick Beardeb382ec2012-04-19 00:25:12 +0000531 if (ConvertedValueExpr.isInvalid())
532 return ExprError();
533 ValueExpr = ConvertedValueExpr.get();
534
535 ObjCBoxedExpr *BoxedExpr =
536 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
537 BoxingMethod, SR);
538 return MaybeBindToTemporary(BoxedExpr);
539}
540
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000541ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
542 Expr *IndexExpr,
543 ObjCMethodDecl *getterMethod,
544 ObjCMethodDecl *setterMethod) {
545 // Feature support is for modern abi.
546 if (!LangOpts.ObjCNonFragileABI)
547 return ExprError();
548 // If the expression is type-dependent, there's nothing for us to do.
549 assert ((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
550 "base or index cannot have dependent type here");
551 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
552 if (Result.isInvalid())
553 return ExprError();
554 IndexExpr = Result.get();
555
556 // Perform lvalue-to-rvalue conversion.
557 Result = DefaultLvalueConversion(BaseExpr);
558 if (Result.isInvalid())
559 return ExprError();
560 BaseExpr = Result.get();
561 return Owned(ObjCSubscriptRefExpr::Create(Context,
562 BaseExpr,
563 IndexExpr,
564 Context.PseudoObjectTy,
565 getterMethod,
566 setterMethod, RB));
567
568}
569
570ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
571 // Look up the NSArray class, if we haven't done so already.
572 if (!NSArrayDecl) {
573 NamedDecl *IF = LookupSingleName(TUScope,
574 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
575 SR.getBegin(),
576 LookupOrdinaryName);
577 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikie4e4d0842012-03-11 07:00:24 +0000578 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000579 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
580 Context.getTranslationUnitDecl(),
581 SourceLocation(),
582 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
583 0, SourceLocation());
584
585 if (!NSArrayDecl) {
586 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
587 return ExprError();
588 }
589 }
590
591 // Find the arrayWithObjects:count: method, if we haven't done so already.
592 QualType IdT = Context.getObjCIdType();
593 if (!ArrayWithObjectsMethod) {
594 Selector
595 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
596 ArrayWithObjectsMethod = NSArrayDecl->lookupClassMethod(Sel);
David Blaikie4e4d0842012-03-11 07:00:24 +0000597 if (!ArrayWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000598 TypeSourceInfo *ResultTInfo = 0;
599 ArrayWithObjectsMethod =
600 ObjCMethodDecl::Create(Context,
601 SourceLocation(), SourceLocation(), Sel,
602 IdT,
603 ResultTInfo,
604 Context.getTranslationUnitDecl(),
605 false /*Instance*/, false/*isVariadic*/,
606 /*isSynthesized=*/false,
607 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
608 ObjCMethodDecl::Required,
609 false);
610 SmallVector<ParmVarDecl *, 2> Params;
611 ParmVarDecl *objects = ParmVarDecl::Create(Context, ArrayWithObjectsMethod,
612 SourceLocation(), SourceLocation(),
613 &Context.Idents.get("objects"),
614 Context.getPointerType(IdT),
615 /*TInfo=*/0,
616 SC_None,
617 SC_None,
618 0);
619 Params.push_back(objects);
620 ParmVarDecl *cnt = ParmVarDecl::Create(Context, ArrayWithObjectsMethod,
621 SourceLocation(), SourceLocation(),
622 &Context.Idents.get("cnt"),
623 Context.UnsignedLongTy,
624 /*TInfo=*/0,
625 SC_None,
626 SC_None,
627 0);
628 Params.push_back(cnt);
629 ArrayWithObjectsMethod->setMethodParams(Context, Params,
630 ArrayRef<SourceLocation>());
631
632
633 }
634
635 if (!ArrayWithObjectsMethod) {
636 Diag(SR.getBegin(), diag::err_undeclared_arraywithobjects) << Sel;
637 return ExprError();
638 }
639 }
640
641 // Make sure the return type is reasonable.
642 if (!ArrayWithObjectsMethod->getResultType()->isObjCObjectPointerType()) {
643 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
644 << ArrayWithObjectsMethod->getSelector();
645 Diag(ArrayWithObjectsMethod->getLocation(),
646 diag::note_objc_literal_method_return)
647 << ArrayWithObjectsMethod->getResultType();
648 return ExprError();
649 }
650
651 // Dig out the type that all elements should be converted to.
652 QualType T = ArrayWithObjectsMethod->param_begin()[0]->getType();
653 const PointerType *PtrT = T->getAs<PointerType>();
654 if (!PtrT ||
655 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
656 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
657 << ArrayWithObjectsMethod->getSelector();
658 Diag(ArrayWithObjectsMethod->param_begin()[0]->getLocation(),
659 diag::note_objc_literal_method_param)
660 << 0 << T
661 << Context.getPointerType(IdT.withConst());
662 return ExprError();
663 }
664 T = PtrT->getPointeeType();
665
666 // Check that the 'count' parameter is integral.
667 if (!ArrayWithObjectsMethod->param_begin()[1]->getType()->isIntegerType()) {
668 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
669 << ArrayWithObjectsMethod->getSelector();
670 Diag(ArrayWithObjectsMethod->param_begin()[1]->getLocation(),
671 diag::note_objc_literal_method_param)
672 << 1
673 << ArrayWithObjectsMethod->param_begin()[1]->getType()
674 << "integral";
675 return ExprError();
676 }
677
678 // Check that each of the elements provided is valid in a collection literal,
679 // performing conversions as necessary.
680 Expr **ElementsBuffer = Elements.get();
681 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
682 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
683 ElementsBuffer[I],
684 T);
685 if (Converted.isInvalid())
686 return ExprError();
687
688 ElementsBuffer[I] = Converted.get();
689 }
690
691 QualType Ty
692 = Context.getObjCObjectPointerType(
693 Context.getObjCInterfaceType(NSArrayDecl));
694
695 return MaybeBindToTemporary(
696 ObjCArrayLiteral::Create(Context,
697 llvm::makeArrayRef(Elements.get(),
698 Elements.size()),
699 Ty, ArrayWithObjectsMethod, SR));
700}
701
702ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
703 ObjCDictionaryElement *Elements,
704 unsigned NumElements) {
705 // Look up the NSDictionary class, if we haven't done so already.
706 if (!NSDictionaryDecl) {
707 NamedDecl *IF = LookupSingleName(TUScope,
708 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
709 SR.getBegin(), LookupOrdinaryName);
710 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikie4e4d0842012-03-11 07:00:24 +0000711 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000712 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
713 Context.getTranslationUnitDecl(),
714 SourceLocation(),
715 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
716 0, SourceLocation());
717
718 if (!NSDictionaryDecl) {
719 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
720 return ExprError();
721 }
722 }
723
724 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
725 // so already.
726 QualType IdT = Context.getObjCIdType();
727 if (!DictionaryWithObjectsMethod) {
728 Selector Sel = NSAPIObj->getNSDictionarySelector(
729 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
730 DictionaryWithObjectsMethod = NSDictionaryDecl->lookupClassMethod(Sel);
David Blaikie4e4d0842012-03-11 07:00:24 +0000731 if (!DictionaryWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000732 DictionaryWithObjectsMethod =
733 ObjCMethodDecl::Create(Context,
734 SourceLocation(), SourceLocation(), Sel,
735 IdT,
736 0 /*TypeSourceInfo */,
737 Context.getTranslationUnitDecl(),
738 false /*Instance*/, false/*isVariadic*/,
739 /*isSynthesized=*/false,
740 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
741 ObjCMethodDecl::Required,
742 false);
743 SmallVector<ParmVarDecl *, 3> Params;
744 ParmVarDecl *objects = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
745 SourceLocation(), SourceLocation(),
746 &Context.Idents.get("objects"),
747 Context.getPointerType(IdT),
748 /*TInfo=*/0,
749 SC_None,
750 SC_None,
751 0);
752 Params.push_back(objects);
753 ParmVarDecl *keys = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
754 SourceLocation(), SourceLocation(),
755 &Context.Idents.get("keys"),
756 Context.getPointerType(IdT),
757 /*TInfo=*/0,
758 SC_None,
759 SC_None,
760 0);
761 Params.push_back(keys);
762 ParmVarDecl *cnt = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
763 SourceLocation(), SourceLocation(),
764 &Context.Idents.get("cnt"),
765 Context.UnsignedLongTy,
766 /*TInfo=*/0,
767 SC_None,
768 SC_None,
769 0);
770 Params.push_back(cnt);
771 DictionaryWithObjectsMethod->setMethodParams(Context, Params,
772 ArrayRef<SourceLocation>());
773 }
774
775 if (!DictionaryWithObjectsMethod) {
776 Diag(SR.getBegin(), diag::err_undeclared_dictwithobjects) << Sel;
777 return ExprError();
778 }
779 }
780
781 // Make sure the return type is reasonable.
782 if (!DictionaryWithObjectsMethod->getResultType()->isObjCObjectPointerType()){
783 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
784 << DictionaryWithObjectsMethod->getSelector();
785 Diag(DictionaryWithObjectsMethod->getLocation(),
786 diag::note_objc_literal_method_return)
787 << DictionaryWithObjectsMethod->getResultType();
788 return ExprError();
789 }
790
791 // Dig out the type that all values should be converted to.
792 QualType ValueT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
793 const PointerType *PtrValue = ValueT->getAs<PointerType>();
794 if (!PtrValue ||
795 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
796 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
797 << DictionaryWithObjectsMethod->getSelector();
798 Diag(DictionaryWithObjectsMethod->param_begin()[0]->getLocation(),
799 diag::note_objc_literal_method_param)
800 << 0 << ValueT
801 << Context.getPointerType(IdT.withConst());
802 return ExprError();
803 }
804 ValueT = PtrValue->getPointeeType();
805
806 // Dig out the type that all keys should be converted to.
807 QualType KeyT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
808 const PointerType *PtrKey = KeyT->getAs<PointerType>();
809 if (!PtrKey ||
810 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
811 IdT)) {
812 bool err = true;
813 if (PtrKey) {
814 if (QIDNSCopying.isNull()) {
815 // key argument of selector is id<NSCopying>?
816 if (ObjCProtocolDecl *NSCopyingPDecl =
817 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
818 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
819 QIDNSCopying =
820 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
821 (ObjCProtocolDecl**) PQ,1);
822 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
823 }
824 }
825 if (!QIDNSCopying.isNull())
826 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
827 QIDNSCopying);
828 }
829
830 if (err) {
831 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
832 << DictionaryWithObjectsMethod->getSelector();
833 Diag(DictionaryWithObjectsMethod->param_begin()[1]->getLocation(),
834 diag::note_objc_literal_method_param)
835 << 1 << KeyT
836 << Context.getPointerType(IdT.withConst());
837 return ExprError();
838 }
839 }
840 KeyT = PtrKey->getPointeeType();
841
842 // Check that the 'count' parameter is integral.
843 if (!DictionaryWithObjectsMethod->param_begin()[2]->getType()
844 ->isIntegerType()) {
845 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
846 << DictionaryWithObjectsMethod->getSelector();
847 Diag(DictionaryWithObjectsMethod->param_begin()[2]->getLocation(),
848 diag::note_objc_literal_method_param)
849 << 2
850 << DictionaryWithObjectsMethod->param_begin()[2]->getType()
851 << "integral";
852 return ExprError();
853 }
854
855 // Check that each of the keys and values provided is valid in a collection
856 // literal, performing conversions as necessary.
857 bool HasPackExpansions = false;
858 for (unsigned I = 0, N = NumElements; I != N; ++I) {
859 // Check the key.
860 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
861 KeyT);
862 if (Key.isInvalid())
863 return ExprError();
864
865 // Check the value.
866 ExprResult Value
867 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
868 if (Value.isInvalid())
869 return ExprError();
870
871 Elements[I].Key = Key.get();
872 Elements[I].Value = Value.get();
873
874 if (Elements[I].EllipsisLoc.isInvalid())
875 continue;
876
877 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
878 !Elements[I].Value->containsUnexpandedParameterPack()) {
879 Diag(Elements[I].EllipsisLoc,
880 diag::err_pack_expansion_without_parameter_packs)
881 << SourceRange(Elements[I].Key->getLocStart(),
882 Elements[I].Value->getLocEnd());
883 return ExprError();
884 }
885
886 HasPackExpansions = true;
887 }
888
889
890 QualType Ty
891 = Context.getObjCObjectPointerType(
892 Context.getObjCInterfaceType(NSDictionaryDecl));
893 return MaybeBindToTemporary(
894 ObjCDictionaryLiteral::Create(Context,
895 llvm::makeArrayRef(Elements,
896 NumElements),
897 HasPackExpansions,
898 Ty,
899 DictionaryWithObjectsMethod, SR));
Chris Lattner85a932e2008-01-04 22:32:30 +0000900}
901
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000902ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000903 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000904 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000905 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000906 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000907 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000908 StrTy = Context.DependentTy;
909 else {
Fariborz Jahanian6c916152011-06-16 22:34:44 +0000910 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
911 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000912 if (RequireCompleteType(AtLoc, EncodedType,
913 PDiag(diag::err_incomplete_type_objc_at_encode)
914 << EncodedTypeInfo->getTypeLoc().getSourceRange()))
915 return ExprError();
916
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000917 std::string Str;
918 Context.getObjCEncodingForType(EncodedType, Str);
919
920 // The type of @encode is the same as the type of the corresponding string,
921 // which is an array type.
922 StrTy = Context.CharTy;
923 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +0000924 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000925 StrTy.addConst();
926 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
927 ArrayType::Normal, 0);
928 }
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Douglas Gregor81d34662010-04-20 15:39:42 +0000930 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000931}
932
John McCallf312b1e2010-08-26 23:41:50 +0000933ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
934 SourceLocation EncodeLoc,
935 SourceLocation LParenLoc,
936 ParsedType ty,
937 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000938 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000939 TypeSourceInfo *TInfo;
940 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
941 if (!TInfo)
942 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
943 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000944
Douglas Gregor81d34662010-04-20 15:39:42 +0000945 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000946}
947
John McCallf312b1e2010-08-26 23:41:50 +0000948ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
949 SourceLocation AtLoc,
950 SourceLocation SelLoc,
951 SourceLocation LParenLoc,
952 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000953 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000954 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000955 if (!Method)
956 Method = LookupFactoryMethodInGlobalPool(Sel,
957 SourceRange(LParenLoc, RParenLoc));
958 if (!Method)
959 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian4c91d892011-07-13 19:05:43 +0000960
961 if (!Method ||
962 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
963 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
964 = ReferencedSelectors.find(Sel);
965 if (Pos == ReferencedSelectors.end())
966 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
967 }
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000968
John McCallf85e1932011-06-15 23:02:42 +0000969 // In ARC, forbid the user from using @selector for
970 // retain/release/autorelease/dealloc/retainCount.
David Blaikie4e4d0842012-03-11 07:00:24 +0000971 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +0000972 switch (Sel.getMethodFamily()) {
973 case OMF_retain:
974 case OMF_release:
975 case OMF_autorelease:
976 case OMF_retainCount:
977 case OMF_dealloc:
978 Diag(AtLoc, diag::err_arc_illegal_selector) <<
979 Sel << SourceRange(LParenLoc, RParenLoc);
980 break;
981
982 case OMF_None:
983 case OMF_alloc:
984 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +0000985 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +0000986 case OMF_init:
987 case OMF_mutableCopy:
988 case OMF_new:
989 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +0000990 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +0000991 break;
992 }
993 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000994 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000995 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000996}
997
John McCallf312b1e2010-08-26 23:41:50 +0000998ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
999 SourceLocation AtLoc,
1000 SourceLocation ProtoLoc,
1001 SourceLocation LParenLoc,
1002 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +00001003 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +00001004 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001005 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +00001006 return true;
1007 }
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Chris Lattnera0af1fe2009-02-18 06:06:56 +00001009 QualType Ty = Context.getObjCProtoType();
1010 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +00001011 return true;
Steve Naroff14108da2009-07-10 23:34:53 +00001012 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +00001013 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +00001014}
1015
John McCall26743b22011-02-03 09:00:02 +00001016/// Try to capture an implicit reference to 'self'.
Eli Friedmanb942cb22012-02-03 22:47:37 +00001017ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1018 DeclContext *DC = getFunctionLevelDeclContext();
John McCall26743b22011-02-03 09:00:02 +00001019
1020 // If we're not in an ObjC method, error out. Note that, unlike the
1021 // C++ case, we don't require an instance method --- class methods
1022 // still have a 'self', and we really do still need to capture it!
1023 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1024 if (!method)
1025 return 0;
1026
Douglas Gregor999713e2012-02-18 09:37:24 +00001027 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall26743b22011-02-03 09:00:02 +00001028
1029 return method;
1030}
1031
Douglas Gregor5c16d632011-09-09 20:05:21 +00001032static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1033 if (T == Context.getObjCInstanceType())
1034 return Context.getObjCIdType();
1035
1036 return T;
1037}
1038
Douglas Gregor926df6c2011-06-11 01:09:30 +00001039QualType Sema::getMessageSendResultType(QualType ReceiverType,
1040 ObjCMethodDecl *Method,
1041 bool isClassMessage, bool isSuperMessage) {
1042 assert(Method && "Must have a method");
1043 if (!Method->hasRelatedResultType())
1044 return Method->getSendResultType();
1045
1046 // If a method has a related return type:
1047 // - if the method found is an instance method, but the message send
1048 // was a class message send, T is the declared return type of the method
1049 // found
1050 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor5c16d632011-09-09 20:05:21 +00001051 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001052
1053 // - if the receiver is super, T is a pointer to the class of the
1054 // enclosing method definition
1055 if (isSuperMessage) {
1056 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1057 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1058 return Context.getObjCObjectPointerType(
1059 Context.getObjCInterfaceType(Class));
1060 }
1061
1062 // - if the receiver is the name of a class U, T is a pointer to U
1063 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1064 ReceiverType->isObjCQualifiedInterfaceType())
1065 return Context.getObjCObjectPointerType(ReceiverType);
1066 // - if the receiver is of type Class or qualified Class type,
1067 // T is the declared return type of the method.
1068 if (ReceiverType->isObjCClassType() ||
1069 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor5c16d632011-09-09 20:05:21 +00001070 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001071
1072 // - if the receiver is id, qualified id, Class, or qualified Class, T
1073 // is the receiver type, otherwise
1074 // - T is the type of the receiver expression.
1075 return ReceiverType;
1076}
John McCall26743b22011-02-03 09:00:02 +00001077
Douglas Gregor926df6c2011-06-11 01:09:30 +00001078void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1079 E = E->IgnoreParenImpCasts();
1080 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1081 if (!MsgSend)
1082 return;
1083
1084 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1085 if (!Method)
1086 return;
1087
1088 if (!Method->hasRelatedResultType())
1089 return;
1090
1091 if (Context.hasSameUnqualifiedType(Method->getResultType()
1092 .getNonReferenceType(),
1093 MsgSend->getType()))
1094 return;
1095
Douglas Gregore97179c2011-09-08 01:46:34 +00001096 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
1097 Context.getObjCInstanceType()))
1098 return;
1099
Douglas Gregor926df6c2011-06-11 01:09:30 +00001100 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1101 << Method->isInstanceMethod() << Method->getSelector()
1102 << MsgSend->getType();
1103}
1104
1105bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
1106 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00001107 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +00001108 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001109 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +00001110 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001111 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +00001112 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +00001113 for (unsigned i = 0; i != NumArgs; i++) {
1114 if (Args[i]->isTypeDependent())
1115 continue;
1116
John Wiegley429bb272011-04-08 18:41:53 +00001117 ExprResult Result = DefaultArgumentPromotion(Args[i]);
1118 if (Result.isInvalid())
1119 return true;
1120 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +00001121 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +00001122
John McCallf85e1932011-06-15 23:02:42 +00001123 unsigned DiagID;
David Blaikie4e4d0842012-03-11 07:00:24 +00001124 if (getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00001125 DiagID = diag::err_arc_method_not_found;
1126 else
1127 DiagID = isClassMessage ? diag::warn_class_method_not_found
1128 : diag::warn_inst_method_not_found;
David Blaikie4e4d0842012-03-11 07:00:24 +00001129 if (!getLangOpts().DebuggerSupport)
John McCall819e7452011-08-31 20:57:36 +00001130 Diag(lbrac, DiagID)
1131 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +00001132
1133 // In debuggers, we want to use __unknown_anytype for these
1134 // results so that clients can cast them.
David Blaikie4e4d0842012-03-11 07:00:24 +00001135 if (getLangOpts().DebuggerSupport) {
John McCall48218c62011-07-13 17:56:40 +00001136 ReturnType = Context.UnknownAnyTy;
1137 } else {
1138 ReturnType = Context.getObjCIdType();
1139 }
John McCallf89e55a2010-11-18 06:31:45 +00001140 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001141 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001142 }
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Douglas Gregor926df6c2011-06-11 01:09:30 +00001144 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1145 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +00001146 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001148 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +00001149 // Method might have more arguments than selector indicates. This is due
1150 // to addition of c-style arguments in method.
1151 if (Method->param_size() > Sel.getNumArgs())
1152 NumNamedArgs = Method->param_size();
1153 // FIXME. This need be cleaned up.
1154 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +00001155 Diag(lbrac, diag::err_typecheck_call_too_few_args)
1156 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +00001157 return false;
1158 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001159
Chris Lattner312531a2009-04-12 08:11:20 +00001160 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001161 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001162 // We can't do any type-checking on a type-dependent argument.
1163 if (Args[i]->isTypeDependent())
1164 continue;
1165
Chris Lattner85a932e2008-01-04 22:32:30 +00001166 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +00001167
John McCall5acb0c92011-10-17 18:40:02 +00001168 ParmVarDecl *param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +00001169 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +00001170
John McCall5acb0c92011-10-17 18:40:02 +00001171 // Strip the unbridged-cast placeholder expression off unless it's
1172 // a consumed argument.
1173 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1174 !param->hasAttr<CFConsumedAttr>())
1175 argExpr = stripARCUnbridgedCast(argExpr);
1176
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001177 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall5acb0c92011-10-17 18:40:02 +00001178 param->getType(),
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001179 PDiag(diag::err_call_incomplete_argument)
1180 << argExpr->getSourceRange()))
1181 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +00001182
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001183 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall5acb0c92011-10-17 18:40:02 +00001184 param);
John McCall3fa5cae2010-10-26 07:05:15 +00001185 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001186 if (ArgE.isInvalid())
1187 IsError = true;
1188 else
1189 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +00001190 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001191
1192 // Promote additional arguments to variadic methods.
1193 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001194 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
1195 if (Args[i]->isTypeDependent())
1196 continue;
1197
John Wiegley429bb272011-04-08 18:41:53 +00001198 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
1199 IsError |= Arg.isInvalid();
1200 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +00001201 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001202 } else {
1203 // Check for extra arguments to non-variadic methods.
1204 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001205 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001206 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001207 << 2 /*method*/ << NumNamedArgs << NumArgs
1208 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001209 << SourceRange(Args[NumNamedArgs]->getLocStart(),
1210 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001211 }
1212 }
1213
Douglas Gregor2725ca82010-04-21 19:57:20 +00001214 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001215
1216 // Do additional checkings on method.
1217 IsError |= CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
1218
Chris Lattner312531a2009-04-12 08:11:20 +00001219 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +00001220}
1221
Douglas Gregorc737acb2011-09-27 16:10:05 +00001222bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +00001223 // 'self' is objc 'self' in an objc method only.
John McCall4b9c2d22011-11-06 09:01:30 +00001224 ObjCMethodDecl *method =
1225 dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1226 if (!method) return false;
1227
John McCallf85e1932011-06-15 23:02:42 +00001228 receiver = receiver->IgnoreParenLValueCasts();
1229 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCall4b9c2d22011-11-06 09:01:30 +00001230 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregorc737acb2011-09-27 16:10:05 +00001231 return true;
1232 return false;
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001233}
1234
Steve Narofff1afaf62009-02-26 15:55:06 +00001235// Helper method for ActOnClassMethod/ActOnInstanceMethod.
1236// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +00001237// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +00001238// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +00001239ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +00001240 ObjCInterfaceDecl *ClassDecl) {
1241 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +00001242 // lookup in class and all superclasses
1243 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001244 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001245 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Steve Naroff5609ec02009-03-08 18:56:13 +00001247 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001248 if (!Method)
1249 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001250
Steve Naroff5609ec02009-03-08 18:56:13 +00001251 // Before we give up, check if the selector is an instance method.
1252 // But only in the root. This matches gcc's behaviour and what the
1253 // runtime expects.
1254 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001255 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001256 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +00001257 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +00001258 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +00001259 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1260 }
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Steve Naroff5609ec02009-03-08 18:56:13 +00001262 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +00001263 }
Steve Naroff5609ec02009-03-08 18:56:13 +00001264 return Method;
1265}
1266
1267ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
1268 ObjCInterfaceDecl *ClassDecl) {
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00001269 if (!ClassDecl->hasDefinition())
1270 return 0;
1271
Steve Naroff5609ec02009-03-08 18:56:13 +00001272 ObjCMethodDecl *Method = 0;
1273 while (ClassDecl && !Method) {
1274 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001275 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001276 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Steve Naroff5609ec02009-03-08 18:56:13 +00001278 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001279 if (!Method)
1280 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +00001281 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +00001282 }
Steve Narofff1afaf62009-02-26 15:55:06 +00001283 return Method;
1284}
1285
John McCall3c3b7f92011-10-25 17:37:35 +00001286/// LookupMethodInType - Look up a method in an ObjCObjectType.
1287ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1288 bool isInstance) {
1289 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1290 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1291 // Look it up in the main interface (and categories, etc.)
1292 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1293 return method;
1294
1295 // Okay, look for "private" methods declared in any
1296 // @implementations we've seen.
1297 if (isInstance) {
1298 if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
1299 return method;
1300 } else {
1301 if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
1302 return method;
1303 }
1304 }
1305
1306 // Check qualifiers.
1307 for (ObjCObjectType::qual_iterator
1308 i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
1309 if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
1310 return method;
1311
1312 return 0;
1313}
1314
Fariborz Jahanian61478062011-03-09 20:18:06 +00001315/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1316/// list of a qualified objective pointer type.
1317ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1318 const ObjCObjectPointerType *OPT,
1319 bool Instance)
1320{
1321 ObjCMethodDecl *MD = 0;
1322 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1323 E = OPT->qual_end(); I != E; ++I) {
1324 ObjCProtocolDecl *PROTO = (*I);
1325 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1326 return MD;
1327 }
1328 }
1329 return 0;
1330}
1331
Fariborz Jahanian98795562012-04-19 23:49:39 +00001332static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1333 if (!Receiver)
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001334 return;
1335
Fariborz Jahanian98795562012-04-19 23:49:39 +00001336 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1337 SourceLocation Loc = RExpr->getLocStart();
1338 QualType T = RExpr->getType();
1339 ObjCPropertyDecl *PDecl = 0;
1340 ObjCMethodDecl *GDecl = 0;
1341 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1342 RExpr = POE->getSyntacticForm();
1343 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1344 if (PRE->isImplicitProperty()) {
1345 GDecl = PRE->getImplicitPropertyGetter();
1346 if (GDecl) {
1347 T = GDecl->getResultType();
1348 }
1349 }
1350 else {
1351 PDecl = PRE->getExplicitProperty();
1352 if (PDecl) {
1353 T = PDecl->getType();
1354 }
1355 }
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001356 }
Fariborz Jahanian98795562012-04-19 23:49:39 +00001357 }
1358
1359 if (T.getObjCLifetime() == Qualifiers::OCL_Weak) {
1360 S.Diag(Loc, diag::warn_receiver_is_weak)
1361 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1362 if (PDecl)
1363 S.Diag(PDecl->getLocation(), diag::note_property_declare);
1364 else if (GDecl)
1365 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001366 return;
1367 }
1368
Fariborz Jahanian98795562012-04-19 23:49:39 +00001369 if (PDecl &&
1370 (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)) {
1371 S.Diag(Loc, diag::warn_receiver_is_weak) << 1;
1372 S.Diag(PDecl->getLocation(), diag::note_property_declare);
1373 }
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001374}
1375
Chris Lattner7f816522010-04-11 07:45:24 +00001376/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1377/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001378ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +00001379HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001380 Expr *BaseExpr, SourceLocation OpLoc,
1381 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001382 SourceLocation MemberLoc,
1383 SourceLocation SuperLoc, QualType SuperType,
1384 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +00001385 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1386 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +00001387
1388 if (MemberName.getNameKind() != DeclarationName::Identifier) {
1389 Diag(MemberLoc, diag::err_invalid_property_name)
1390 << MemberName << QualType(OPT, 0);
1391 return ExprError();
1392 }
1393
Chris Lattner7f816522010-04-11 07:45:24 +00001394 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregorb3029962011-11-14 22:10:01 +00001395 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1396 : BaseExpr->getSourceRange();
1397 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1398 PDiag(diag::err_property_not_found_forward_class)
1399 << MemberName << BaseRange))
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +00001400 return ExprError();
Douglas Gregorb3029962011-11-14 22:10:01 +00001401
Chris Lattner7f816522010-04-11 07:45:24 +00001402 // Search for a declared property first.
1403 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1404 // Check whether we can reference this property.
1405 if (DiagnoseUseOfDecl(PD, MemberLoc))
1406 return ExprError();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001407 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001408 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001409 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001410 MemberLoc,
1411 SuperLoc, SuperType));
1412 else
John McCall3c3b7f92011-10-25 17:37:35 +00001413 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001414 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001415 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001416 }
1417 // Check protocols on qualified interfaces.
1418 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1419 E = OPT->qual_end(); I != E; ++I)
1420 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1421 // Check whether we can reference this property.
1422 if (DiagnoseUseOfDecl(PD, MemberLoc))
1423 return ExprError();
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001424
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001425 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001426 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1427 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001428 VK_LValue,
1429 OK_ObjCProperty,
1430 MemberLoc,
1431 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001432 else
John McCall3c3b7f92011-10-25 17:37:35 +00001433 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1434 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001435 VK_LValue,
1436 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001437 MemberLoc,
1438 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001439 }
1440 // If that failed, look for an "implicit" property by seeing if the nullary
1441 // selector is implemented.
1442
1443 // FIXME: The logic for looking up nullary and unary selectors should be
1444 // shared with the code in ActOnInstanceMessage.
1445
1446 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1447 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001448
1449 // May be founf in property's qualified list.
1450 if (!Getter)
1451 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +00001452
1453 // If this reference is in an @implementation, check for 'private' methods.
1454 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001455 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +00001456
1457 // Look through local category implementations associated with the class.
1458 if (!Getter)
1459 Getter = IFace->getCategoryInstanceMethod(Sel);
1460 if (Getter) {
1461 // Check if we can reference this property.
1462 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1463 return ExprError();
1464 }
1465 // If we found a getter then this may be a valid dot-reference, we
1466 // will look for the matching setter, in case it is needed.
1467 Selector SetterSel =
1468 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1469 PP.getSelectorTable(), Member);
1470 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001471
1472 // May be founf in property's qualified list.
1473 if (!Setter)
1474 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1475
Chris Lattner7f816522010-04-11 07:45:24 +00001476 if (!Setter) {
1477 // If this reference is in an @implementation, also check for 'private'
1478 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001479 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +00001480 }
1481 // Look through local category implementations associated with the class.
1482 if (!Setter)
1483 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001484
Chris Lattner7f816522010-04-11 07:45:24 +00001485 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1486 return ExprError();
1487
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001488 if (Getter || Setter) {
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001489 if (Super)
John McCall12f78a62010-12-02 01:19:52 +00001490 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001491 Context.PseudoObjectTy,
1492 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001493 MemberLoc,
1494 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001495 else
John McCall12f78a62010-12-02 01:19:52 +00001496 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001497 Context.PseudoObjectTy,
1498 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001499 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001500
Chris Lattner7f816522010-04-11 07:45:24 +00001501 }
1502
1503 // Attempt to correct for typos in property names.
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001504 DeclFilterCCC<ObjCPropertyDecl> Validator;
1505 if (TypoCorrection Corrected = CorrectTypo(
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001506 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001507 NULL, Validator, IFace, false, OPT)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001508 ObjCPropertyDecl *Property =
1509 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001510 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +00001511 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001512 << MemberName << QualType(OPT, 0) << TypoResult
1513 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +00001514 Diag(Property->getLocation(), diag::note_previous_decl)
1515 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001516 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1517 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001518 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +00001519 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001520 ObjCInterfaceDecl *ClassDeclared;
1521 if (ObjCIvarDecl *Ivar =
1522 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1523 QualType T = Ivar->getType();
1524 if (const ObjCObjectPointerType * OBJPT =
1525 T->getAsObjCInterfacePointerType()) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001526 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1527 PDiag(diag::err_property_not_as_forward_class)
1528 << MemberName << BaseExpr->getSourceRange()))
1529 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001530 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001531 Diag(MemberLoc,
1532 diag::err_ivar_access_using_property_syntax_suggest)
1533 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1534 << FixItHint::CreateReplacement(OpLoc, "->");
1535 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001536 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001537
Chris Lattner7f816522010-04-11 07:45:24 +00001538 Diag(MemberLoc, diag::err_property_not_found)
1539 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001540 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +00001541 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001542 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +00001543 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +00001544}
1545
1546
1547
John McCall60d7b3a2010-08-24 06:29:42 +00001548ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +00001549ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1550 IdentifierInfo &propertyName,
1551 SourceLocation receiverNameLoc,
1552 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001553
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001554 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +00001555 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1556 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +00001557
1558 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +00001559 if (IFace == 0) {
1560 // If the "receiver" is 'super' in a method, handle it as an expression-like
1561 // property reference.
John McCall26743b22011-02-03 09:00:02 +00001562 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001563 IsSuper = true;
1564
Eli Friedmanb942cb22012-02-03 22:47:37 +00001565 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnereb483eb2010-04-11 08:28:14 +00001566 if (CurMethod->isInstanceMethod()) {
1567 QualType T =
1568 Context.getObjCInterfaceType(CurMethod->getClassInterface());
1569 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001570
1571 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001572 /*BaseExpr*/0,
1573 SourceLocation()/*OpLoc*/,
1574 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001575 propertyNameLoc,
1576 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001577 }
Mike Stump1eb44332009-09-09 15:08:12 +00001578
Chris Lattnereb483eb2010-04-11 08:28:14 +00001579 // Otherwise, if this is a class method, try dispatching to our
1580 // superclass.
1581 IFace = CurMethod->getClassInterface()->getSuperClass();
1582 }
John McCall26743b22011-02-03 09:00:02 +00001583 }
Chris Lattnereb483eb2010-04-11 08:28:14 +00001584
1585 if (IFace == 0) {
1586 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1587 return ExprError();
1588 }
1589 }
1590
1591 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +00001592 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001593 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001594
1595 // If this reference is in an @implementation, check for 'private' methods.
1596 if (!Getter)
1597 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1598 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001599 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001600 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001601
1602 if (Getter) {
1603 // FIXME: refactor/share with ActOnMemberReference().
1604 // Check if we can reference this property.
1605 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1606 return ExprError();
1607 }
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Steve Naroff61f72cb2009-03-09 21:12:44 +00001609 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00001610 Selector SetterSel =
1611 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +00001612 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +00001613
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001614 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001615 if (!Setter) {
1616 // If this reference is in an @implementation, also check for 'private'
1617 // methods.
1618 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1619 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001620 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001621 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001622 }
1623 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001624 if (!Setter)
1625 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001626
1627 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1628 return ExprError();
1629
1630 if (Getter || Setter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001631 if (IsSuper)
1632 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001633 Context.PseudoObjectTy,
1634 VK_LValue, OK_ObjCProperty,
Douglas Gregor926df6c2011-06-11 01:09:30 +00001635 propertyNameLoc,
1636 receiverNameLoc,
1637 Context.getObjCInterfaceType(IFace)));
1638
John McCall12f78a62010-12-02 01:19:52 +00001639 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001640 Context.PseudoObjectTy,
1641 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001642 propertyNameLoc,
1643 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +00001644 }
1645 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1646 << &propertyName << Context.getObjCInterfaceType(IFace));
1647}
1648
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001649namespace {
1650
1651class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1652 public:
1653 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1654 // Determine whether "super" is acceptable in the current context.
1655 if (Method && Method->getClassInterface())
1656 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1657 }
1658
1659 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1660 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1661 candidate.isKeyword("super");
1662 }
1663};
1664
1665}
1666
Douglas Gregor47bd5432010-04-14 02:46:37 +00001667Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +00001668 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +00001669 SourceLocation NameLoc,
1670 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +00001671 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +00001672 ParsedType &ReceiverType) {
1673 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +00001674
Douglas Gregor47bd5432010-04-14 02:46:37 +00001675 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +00001676 // messaging super. If the identifier is "super" and there is a
1677 // trailing dot, it's an instance message.
1678 if (IsSuper && S->isInObjcMethodScope())
1679 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001680
1681 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1682 LookupName(Result, S);
1683
1684 switch (Result.getResultKind()) {
1685 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +00001686 // Normal name lookup didn't find anything. If we're in an
1687 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +00001688 // FIXME: This is a hack. Ivar lookup should be part of normal
1689 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +00001690 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidisccc9e762011-11-09 00:22:48 +00001691 if (!Method->getClassInterface()) {
1692 // Fall back: let the parser try to parse it as an instance message.
1693 return ObjCInstanceMessage;
1694 }
1695
Douglas Gregored464422010-04-19 20:09:36 +00001696 ObjCInterfaceDecl *ClassDeclared;
1697 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1698 ClassDeclared))
1699 return ObjCInstanceMessage;
1700 }
Douglas Gregor95f42922010-10-14 22:11:03 +00001701
Douglas Gregor47bd5432010-04-14 02:46:37 +00001702 // Break out; we'll perform typo correction below.
1703 break;
1704
1705 case LookupResult::NotFoundInCurrentInstantiation:
1706 case LookupResult::FoundOverloaded:
1707 case LookupResult::FoundUnresolvedValue:
1708 case LookupResult::Ambiguous:
1709 Result.suppressDiagnostics();
1710 return ObjCInstanceMessage;
1711
1712 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +00001713 // If the identifier is a class or not, and there is a trailing dot,
1714 // it's an instance message.
1715 if (HasTrailingDot)
1716 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001717 // We found something. If it's a type, then we have a class
1718 // message. Otherwise, it's an instance message.
1719 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +00001720 QualType T;
1721 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1722 T = Context.getObjCInterfaceType(Class);
1723 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
1724 T = Context.getTypeDeclType(Type);
1725 else
1726 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001727
Douglas Gregor1569f952010-04-21 20:38:13 +00001728 // We have a class message, and T is the type we're
1729 // messaging. Build source-location information for it.
1730 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +00001731 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +00001732 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001733 }
1734 }
1735
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001736 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001737 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1738 Result.getLookupKind(), S, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001739 Validator)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001740 if (Corrected.isKeyword()) {
1741 // If we've found the keyword "super" (the only keyword that would be
1742 // returned by CorrectTypo), this is a send to super.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001743 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001744 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +00001745 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +00001746 return ObjCSuperMessage;
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001747 } else if (ObjCInterfaceDecl *Class =
1748 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1749 // If we found a declaration, correct when it refers to an Objective-C
1750 // class.
1751 Diag(NameLoc, diag::err_unknown_receiver_suggest)
1752 << Name << Corrected.getCorrection()
1753 << FixItHint::CreateReplacement(SourceRange(NameLoc),
1754 Class->getNameAsString());
1755 Diag(Class->getLocation(), diag::note_previous_decl)
1756 << Corrected.getCorrection();
1757
1758 QualType T = Context.getObjCInterfaceType(Class);
1759 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1760 ReceiverType = CreateParsedType(T, TSInfo);
1761 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001762 }
1763 }
1764
1765 // Fall back: let the parser try to parse it as an instance message.
1766 return ObjCInstanceMessage;
1767}
Steve Naroff61f72cb2009-03-09 21:12:44 +00001768
John McCall60d7b3a2010-08-24 06:29:42 +00001769ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001770 SourceLocation SuperLoc,
1771 Selector Sel,
1772 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001773 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001774 SourceLocation RBracLoc,
1775 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001776 // Determine whether we are inside a method or not.
Eli Friedmanb942cb22012-02-03 22:47:37 +00001777 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregorf95861a2010-04-21 20:01:04 +00001778 if (!Method) {
1779 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1780 return ExprError();
1781 }
Chris Lattner85a932e2008-01-04 22:32:30 +00001782
Douglas Gregorf95861a2010-04-21 20:01:04 +00001783 ObjCInterfaceDecl *Class = Method->getClassInterface();
1784 if (!Class) {
1785 Diag(SuperLoc, diag::error_no_super_class_message)
1786 << Method->getDeclName();
1787 return ExprError();
1788 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001789
Douglas Gregorf95861a2010-04-21 20:01:04 +00001790 ObjCInterfaceDecl *Super = Class->getSuperClass();
1791 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001792 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +00001793 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1794 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001795 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +00001796 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001797
Douglas Gregorf95861a2010-04-21 20:01:04 +00001798 // We are in a method whose class has a superclass, so 'super'
1799 // is acting as a keyword.
1800 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +00001801 if (Sel.getMethodFamily() == OMF_dealloc)
1802 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00001803 if (Sel.getMethodFamily() == OMF_finalize)
1804 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +00001805
Douglas Gregorf95861a2010-04-21 20:01:04 +00001806 // Since we are in an instance method, this is an instance
1807 // message to the superclass instance.
1808 QualType SuperTy = Context.getObjCInterfaceType(Super);
1809 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +00001810 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001811 Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001812 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001813 }
Douglas Gregorf95861a2010-04-21 20:01:04 +00001814
1815 // Since we are in a class method, this is a class message to
1816 // the superclass.
1817 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1818 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001819 SuperLoc, Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001820 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001821}
1822
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001823
1824ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1825 bool isSuperReceiver,
1826 SourceLocation Loc,
1827 Selector Sel,
1828 ObjCMethodDecl *Method,
1829 MultiExprArg Args) {
1830 TypeSourceInfo *receiverTypeInfo = 0;
1831 if (!ReceiverType.isNull())
1832 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1833
1834 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1835 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1836 Sel, Method, Loc, Loc, Loc, Args,
1837 /*isImplicit=*/true);
1838
1839}
1840
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001841static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1842 unsigned DiagID,
1843 bool (*refactor)(const ObjCMessageExpr *,
1844 const NSAPI &, edit::Commit &)) {
1845 SourceLocation MsgLoc = Msg->getExprLoc();
1846 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
1847 return;
1848
1849 SourceManager &SM = S.SourceMgr;
1850 edit::Commit ECommit(SM, S.LangOpts);
1851 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1852 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1853 << Msg->getSelector() << Msg->getSourceRange();
1854 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1855 if (!ECommit.isCommitable())
1856 return;
1857 for (edit::Commit::edit_iterator
1858 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1859 const edit::Commit::Edit &Edit = *I;
1860 switch (Edit.Kind) {
1861 case edit::Commit::Act_Insert:
1862 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1863 Edit.Text,
1864 Edit.BeforePrev));
1865 break;
1866 case edit::Commit::Act_InsertFromRange:
1867 Builder.AddFixItHint(
1868 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1869 Edit.getInsertFromRange(SM),
1870 Edit.BeforePrev));
1871 break;
1872 case edit::Commit::Act_Remove:
1873 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1874 break;
1875 }
1876 }
1877 }
1878}
1879
1880static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1881 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1882 edit::rewriteObjCRedundantCallWithLiteral);
1883}
1884
Douglas Gregor2725ca82010-04-21 19:57:20 +00001885/// \brief Build an Objective-C class message expression.
1886///
1887/// This routine takes care of both normal class messages and
1888/// class messages to the superclass.
1889///
1890/// \param ReceiverTypeInfo Type source information that describes the
1891/// receiver of this message. This may be NULL, in which case we are
1892/// sending to the superclass and \p SuperLoc must be a valid source
1893/// location.
1894
1895/// \param ReceiverType The type of the object receiving the
1896/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1897/// type as that refers to. For a superclass send, this is the type of
1898/// the superclass.
1899///
1900/// \param SuperLoc The location of the "super" keyword in a
1901/// superclass message.
1902///
1903/// \param Sel The selector to which the message is being sent.
1904///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001905/// \param Method The method that this class message is invoking, if
1906/// already known.
1907///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001908/// \param LBracLoc The location of the opening square bracket ']'.
1909///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001910/// \param RBrac The location of the closing square bracket ']'.
1911///
1912/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001913ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001914 QualType ReceiverType,
1915 SourceLocation SuperLoc,
1916 Selector Sel,
1917 ObjCMethodDecl *Method,
1918 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001919 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001920 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001921 MultiExprArg ArgsIn,
1922 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001923 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001924 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001925 if (LBracLoc.isInvalid()) {
1926 Diag(Loc, diag::err_missing_open_square_message_send)
1927 << FixItHint::CreateInsertion(Loc, "[");
1928 LBracLoc = Loc;
1929 }
1930
Douglas Gregor92e986e2010-04-22 16:44:27 +00001931 if (ReceiverType->isDependentType()) {
1932 // If the receiver type is dependent, we can't type-check anything
1933 // at this point. Build a dependent expression.
1934 unsigned NumArgs = ArgsIn.size();
1935 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1936 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001937 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1938 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001939 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001940 makeArrayRef(Args, NumArgs),RBracLoc,
1941 isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001942 }
Chris Lattner15faee12010-04-12 05:38:43 +00001943
Douglas Gregor2725ca82010-04-21 19:57:20 +00001944 // Find the class to which we are sending this message.
1945 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001946 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1947 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001948 Diag(Loc, diag::err_invalid_receiver_class_message)
1949 << ReceiverType;
1950 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001951 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001952 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001953 // objc++ diagnoses during typename annotation.
David Blaikie4e4d0842012-03-11 07:00:24 +00001954 if (!getLangOpts().CPlusPlus)
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001955 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001956 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001957 if (!Method) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001958 SourceRange TypeRange
1959 = SuperLoc.isValid()? SourceRange(SuperLoc)
1960 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
1961 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikie4e4d0842012-03-11 07:00:24 +00001962 (getLangOpts().ObjCAutoRefCount
Douglas Gregorb3029962011-11-14 22:10:01 +00001963 ? PDiag(diag::err_arc_receiver_forward_class)
1964 : PDiag(diag::warn_receiver_forward_class))
1965 << TypeRange)) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001966 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001967 Method = LookupFactoryMethodInGlobalPool(Sel,
1968 SourceRange(LBracLoc, RBracLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00001969 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001970 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1971 << Method->getDeclName();
1972 }
1973 if (!Method)
1974 Method = Class->lookupClassMethod(Sel);
1975
1976 // If we have an implementation in scope, check "private" methods.
1977 if (!Method)
1978 Method = LookupPrivateClassMethod(Sel, Class);
1979
1980 if (Method && DiagnoseUseOfDecl(Method, Loc))
1981 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001982 }
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Douglas Gregor2725ca82010-04-21 19:57:20 +00001984 // Check the argument types and determine the result type.
1985 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001986 ExprValueKind VK = VK_RValue;
1987
Douglas Gregor2725ca82010-04-21 19:57:20 +00001988 unsigned NumArgs = ArgsIn.size();
1989 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001990 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1991 SuperLoc.isValid(), LBracLoc, RBracLoc,
1992 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001993 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001994
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001995 if (Method && !Method->getResultType()->isVoidType() &&
1996 RequireCompleteType(LBracLoc, Method->getResultType(),
1997 diag::err_illegal_message_expr_incomplete_type))
1998 return ExprError();
1999
Douglas Gregor2725ca82010-04-21 19:57:20 +00002000 // Construct the appropriate ObjCMessageExpr.
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002001 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00002002 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00002003 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002004 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002005 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002006 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002007 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002008 else {
John McCallf89e55a2010-11-18 06:31:45 +00002009 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002010 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002011 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002012 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002013 if (!isImplicit)
2014 checkCocoaAPI(*this, Result);
2015 }
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002016 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00002017}
2018
Douglas Gregor2725ca82010-04-21 19:57:20 +00002019// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00002020// ArgExprs is optional - if it is present, the number of expressions
2021// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00002022ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00002023 ParsedType Receiver,
2024 Selector Sel,
2025 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002026 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor77328d12010-09-15 23:19:31 +00002027 SourceLocation RBracLoc,
2028 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002029 TypeSourceInfo *ReceiverTypeInfo;
2030 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2031 if (ReceiverType.isNull())
2032 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Mike Stump1eb44332009-09-09 15:08:12 +00002034
Douglas Gregor2725ca82010-04-21 19:57:20 +00002035 if (!ReceiverTypeInfo)
2036 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2037
2038 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00002039 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002040 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00002041}
2042
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002043ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2044 QualType ReceiverType,
2045 SourceLocation Loc,
2046 Selector Sel,
2047 ObjCMethodDecl *Method,
2048 MultiExprArg Args) {
2049 return BuildInstanceMessage(Receiver, ReceiverType,
2050 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2051 Sel, Method, Loc, Loc, Loc, Args,
2052 /*isImplicit=*/true);
2053}
2054
Douglas Gregor2725ca82010-04-21 19:57:20 +00002055/// \brief Build an Objective-C instance message expression.
2056///
2057/// This routine takes care of both normal instance messages and
2058/// instance messages to the superclass instance.
2059///
2060/// \param Receiver The expression that computes the object that will
2061/// receive this message. This may be empty, in which case we are
2062/// sending to the superclass instance and \p SuperLoc must be a valid
2063/// source location.
2064///
2065/// \param ReceiverType The (static) type of the object receiving the
2066/// message. When a \p Receiver expression is provided, this is the
2067/// same type as that expression. For a superclass instance send, this
2068/// is a pointer to the type of the superclass.
2069///
2070/// \param SuperLoc The location of the "super" keyword in a
2071/// superclass instance message.
2072///
2073/// \param Sel The selector to which the message is being sent.
2074///
Douglas Gregorf49bb082010-04-22 17:01:48 +00002075/// \param Method The method that this instance message is invoking, if
2076/// already known.
2077///
Douglas Gregor2725ca82010-04-21 19:57:20 +00002078/// \param LBracLoc The location of the opening square bracket ']'.
2079///
Douglas Gregor2725ca82010-04-21 19:57:20 +00002080/// \param RBrac The location of the closing square bracket ']'.
2081///
2082/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00002083ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002084 QualType ReceiverType,
2085 SourceLocation SuperLoc,
2086 Selector Sel,
2087 ObjCMethodDecl *Method,
2088 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002089 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002090 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002091 MultiExprArg ArgsIn,
2092 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00002093 // The location of the receiver.
2094 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2095
2096 if (LBracLoc.isInvalid()) {
2097 Diag(Loc, diag::err_missing_open_square_message_send)
2098 << FixItHint::CreateInsertion(Loc, "[");
2099 LBracLoc = Loc;
2100 }
2101
Douglas Gregor2725ca82010-04-21 19:57:20 +00002102 // If we have a receiver expression, perform appropriate promotions
2103 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00002104 if (Receiver) {
John McCall5acb0c92011-10-17 18:40:02 +00002105 if (Receiver->hasPlaceholderType()) {
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00002106 ExprResult Result;
2107 if (Receiver->getType() == Context.UnknownAnyTy)
2108 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2109 else
2110 Result = CheckPlaceholderExpr(Receiver);
2111 if (Result.isInvalid()) return ExprError();
2112 Receiver = Result.take();
John McCall5acb0c92011-10-17 18:40:02 +00002113 }
2114
Douglas Gregor92e986e2010-04-22 16:44:27 +00002115 if (Receiver->isTypeDependent()) {
2116 // If the receiver is type-dependent, we can't type-check anything
2117 // at this point. Build a dependent expression.
2118 unsigned NumArgs = ArgsIn.size();
2119 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2120 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2121 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00002122 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002123 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002124 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002125 RBracLoc, isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00002126 }
2127
Douglas Gregor2725ca82010-04-21 19:57:20 +00002128 // If necessary, apply function/array conversion to the receiver.
2129 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00002130 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2131 if (Result.isInvalid())
2132 return ExprError();
2133 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00002134 ReceiverType = Receiver->getType();
2135 }
2136
Douglas Gregorf49bb082010-04-22 17:01:48 +00002137 if (!Method) {
2138 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00002139 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002140 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00002141 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2142 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002143 SourceRange(LBracLoc, RBracLoc),
2144 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002145 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00002146 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002147 SourceRange(LBracLoc, RBracLoc),
2148 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002149 } else if (ReceiverType->isObjCClassType() ||
2150 ReceiverType->isObjCQualifiedClassType()) {
2151 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002152 // We allow sending a message to a qualified Class ("Class<foo>"), which
2153 // is ok as long as one of the protocols implements the selector (if not, warn).
2154 if (const ObjCObjectPointerType *QClassTy
2155 = ReceiverType->getAsObjCQualifiedClassType()) {
2156 // Search protocols for class methods.
2157 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2158 if (!Method) {
2159 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2160 // warn if instance method found for a Class message.
2161 if (Method) {
2162 Diag(Loc, diag::warn_instance_method_on_class_found)
2163 << Method->getSelector() << Sel;
Ted Kremenek3306ec12012-02-27 22:55:11 +00002164 Diag(Method->getLocation(), diag::note_method_declared_at)
2165 << Method->getDeclName();
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002166 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00002167 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002168 } else {
2169 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2170 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2171 // First check the public methods in the class interface.
2172 Method = ClassDecl->lookupClassMethod(Sel);
2173
2174 if (!Method)
2175 Method = LookupPrivateClassMethod(Sel, ClassDecl);
2176 }
2177 if (Method && DiagnoseUseOfDecl(Method, Loc))
2178 return ExprError();
2179 }
2180 if (!Method) {
2181 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00002182 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002183 Method = LookupFactoryMethodInGlobalPool(Sel,
2184 SourceRange(LBracLoc, RBracLoc),
2185 true);
2186 if (!Method) {
2187 // If no class (factory) method was found, check if an _instance_
2188 // method of the same name exists in the root class only.
2189 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002190 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002191 true);
2192 if (Method)
2193 if (const ObjCInterfaceDecl *ID =
2194 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2195 if (ID->getSuperClass())
2196 Diag(Loc, diag::warn_root_inst_method_not_found)
2197 << Sel << SourceRange(LBracLoc, RBracLoc);
2198 }
2199 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002200 }
2201 }
2202 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002203 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002204 ObjCInterfaceDecl* ClassDecl = 0;
2205
2206 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2207 // long as one of the protocols implements the selector (if not, warn).
2208 if (const ObjCObjectPointerType *QIdTy
2209 = ReceiverType->getAsObjCQualifiedIdType()) {
2210 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002211 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2212 if (!Method)
2213 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002214 } else if (const ObjCObjectPointerType *OCIType
2215 = ReceiverType->getAsObjCInterfacePointerType()) {
2216 // We allow sending a message to a pointer to an interface (an object).
2217 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00002218
Douglas Gregorb3029962011-11-14 22:10:01 +00002219 // Try to complete the type. Under ARC, this is a hard error from which
2220 // we don't try to recover.
2221 const ObjCInterfaceDecl *forwardClass = 0;
2222 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002223 getLangOpts().ObjCAutoRefCount
Douglas Gregorb3029962011-11-14 22:10:01 +00002224 ? PDiag(diag::err_arc_receiver_forward_instance)
2225 << (Receiver ? Receiver->getSourceRange()
2226 : SourceRange(SuperLoc))
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00002227 : PDiag(diag::warn_receiver_forward_instance)
2228 << (Receiver ? Receiver->getSourceRange()
2229 : SourceRange(SuperLoc)))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002230 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregorb3029962011-11-14 22:10:01 +00002231 return ExprError();
2232
2233 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00002234 Diag(Receiver ? Receiver->getLocStart()
2235 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00002236 Method = 0;
2237 } else {
2238 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCallf85e1932011-06-15 23:02:42 +00002239 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002240
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002241 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002242 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002243 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2244
Douglas Gregorf49bb082010-04-22 17:01:48 +00002245 if (!Method) {
2246 // If we have implementations in scope, check "private" methods.
2247 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
2248
David Blaikie4e4d0842012-03-11 07:00:24 +00002249 if (!Method && getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002250 Diag(Loc, diag::err_arc_may_not_respond)
2251 << OCIType->getPointeeType() << Sel;
2252 return ExprError();
2253 }
2254
Douglas Gregorc737acb2011-09-27 16:10:05 +00002255 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002256 // If we still haven't found a method, look in the global pool. This
2257 // behavior isn't very desirable, however we need it for GCC
2258 // compatibility. FIXME: should we deviate??
2259 if (OCIType->qual_empty()) {
2260 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002261 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002262 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002263 Diag(Loc, diag::warn_maynot_respond)
2264 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
2265 }
2266 }
2267 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002268 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00002269 return ExprError();
David Blaikie4e4d0842012-03-11 07:00:24 +00002270 } else if (!getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002271 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00002272 (ReceiverType->isPointerType() ||
2273 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002274 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00002275 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00002276 Diag(Loc, diag::warn_bad_receiver_type)
2277 << ReceiverType
2278 << Receiver->getSourceRange();
2279 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00002280 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002281 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00002282 else {
2283 // TODO: specialized warning on null receivers?
2284 bool IsNull = Receiver->isNullPointerConstant(Context,
2285 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00002286 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2287 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00002288 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002289 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00002290 } else {
John Wiegley429bb272011-04-08 18:41:53 +00002291 ExprResult ReceiverRes;
David Blaikie4e4d0842012-03-11 07:00:24 +00002292 if (getLangOpts().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00002293 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00002294 if (ReceiverRes.isUsable()) {
2295 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00002296 return BuildInstanceMessage(Receiver,
2297 ReceiverType,
2298 SuperLoc,
2299 Sel,
2300 Method,
2301 LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002302 SelectorLocs,
John Wiegley429bb272011-04-08 18:41:53 +00002303 RBracLoc,
2304 move(ArgsIn));
2305 } else {
2306 // Reject other random receiver types (e.g. structs).
2307 Diag(Loc, diag::err_bad_receiver_type)
2308 << ReceiverType << Receiver->getSourceRange();
2309 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00002310 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002311 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002312 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00002313 }
Mike Stump1eb44332009-09-09 15:08:12 +00002314
Douglas Gregor2725ca82010-04-21 19:57:20 +00002315 // Check the message arguments.
2316 unsigned NumArgs = ArgsIn.size();
2317 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2318 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00002319 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00002320 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2321 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00002322 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
2323 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00002324 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00002325 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00002326
Douglas Gregor483dd2f2011-01-11 03:23:19 +00002327 if (Method && !Method->getResultType()->isVoidType() &&
2328 RequireCompleteType(LBracLoc, Method->getResultType(),
2329 diag::err_illegal_message_expr_incomplete_type))
2330 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002331
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002332 SourceLocation SelLoc = SelectorLocs.front();
2333
John McCallf85e1932011-06-15 23:02:42 +00002334 // In ARC, forbid the user from sending messages to
2335 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002336 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002337 ObjCMethodFamily family =
2338 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2339 switch (family) {
2340 case OMF_init:
2341 if (Method)
2342 checkInitMethod(Method, ReceiverType);
2343
2344 case OMF_None:
2345 case OMF_alloc:
2346 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00002347 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00002348 case OMF_mutableCopy:
2349 case OMF_new:
2350 case OMF_self:
2351 break;
2352
2353 case OMF_dealloc:
2354 case OMF_retain:
2355 case OMF_release:
2356 case OMF_autorelease:
2357 case OMF_retainCount:
2358 Diag(Loc, diag::err_arc_illegal_explicit_message)
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002359 << Sel << SelLoc;
John McCallf85e1932011-06-15 23:02:42 +00002360 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002361
2362 case OMF_performSelector:
2363 if (Method && NumArgs >= 1) {
2364 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2365 Selector ArgSel = SelExp->getSelector();
2366 ObjCMethodDecl *SelMethod =
2367 LookupInstanceMethodInGlobalPool(ArgSel,
2368 SelExp->getSourceRange());
2369 if (!SelMethod)
2370 SelMethod =
2371 LookupFactoryMethodInGlobalPool(ArgSel,
2372 SelExp->getSourceRange());
2373 if (SelMethod) {
2374 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2375 switch (SelFamily) {
2376 case OMF_alloc:
2377 case OMF_copy:
2378 case OMF_mutableCopy:
2379 case OMF_new:
2380 case OMF_self:
2381 case OMF_init:
2382 // Issue error, unless ns_returns_not_retained.
2383 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2384 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002385 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002386 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002387 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2388 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002389 }
2390 break;
2391 default:
2392 // +0 call. OK. unless ns_returns_retained.
2393 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2394 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002395 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002396 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002397 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2398 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002399 }
2400 break;
2401 }
2402 }
2403 } else {
2404 // error (may leak).
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002405 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002406 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2407 }
2408 }
2409 break;
John McCallf85e1932011-06-15 23:02:42 +00002410 }
2411 }
2412
Douglas Gregor2725ca82010-04-21 19:57:20 +00002413 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00002414 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00002415 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00002416 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002417 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002418 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002419 makeArrayRef(Args, NumArgs), RBracLoc,
2420 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002421 else {
John McCallf89e55a2010-11-18 06:31:45 +00002422 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002423 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002424 makeArrayRef(Args, NumArgs), RBracLoc,
2425 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002426 if (!isImplicit)
2427 checkCocoaAPI(*this, Result);
2428 }
John McCallf85e1932011-06-15 23:02:42 +00002429
David Blaikie4e4d0842012-03-11 07:00:24 +00002430 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian98795562012-04-19 23:49:39 +00002431 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian878f8502012-04-04 20:05:25 +00002432
John McCallf85e1932011-06-15 23:02:42 +00002433 // In ARC, annotate delegate init calls.
2434 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00002435 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00002436 // Only consider init calls *directly* in init implementations,
2437 // not within blocks.
2438 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2439 if (method && method->getMethodFamily() == OMF_init) {
2440 // The implicit assignment to self means we also don't want to
2441 // consume the result.
2442 Result->setDelegateInitCall(true);
2443 return Owned(Result);
2444 }
2445 }
2446
2447 // In ARC, check for message sends which are likely to introduce
2448 // retain cycles.
2449 checkRetainCycles(Result);
2450 }
2451
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002452 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00002453}
2454
2455// ActOnInstanceMessage - used for both unary and keyword messages.
2456// ArgExprs is optional - if it is present, the number of expressions
2457// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00002458ExprResult Sema::ActOnInstanceMessage(Scope *S,
2459 Expr *Receiver,
2460 Selector Sel,
2461 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002462 ArrayRef<SourceLocation> SelectorLocs,
John McCall60d7b3a2010-08-24 06:29:42 +00002463 SourceLocation RBracLoc,
2464 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002465 if (!Receiver)
2466 return ExprError();
2467
John McCall9ae2f072010-08-23 23:25:46 +00002468 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00002469 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002470 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00002471}
Chris Lattnereca7be62008-04-07 05:30:13 +00002472
John McCallf85e1932011-06-15 23:02:42 +00002473enum ARCConversionTypeClass {
John McCall2cf031d2011-10-01 01:01:08 +00002474 /// int, void, struct A
John McCallf85e1932011-06-15 23:02:42 +00002475 ACTC_none,
John McCall2cf031d2011-10-01 01:01:08 +00002476
2477 /// id, void (^)()
John McCallf85e1932011-06-15 23:02:42 +00002478 ACTC_retainable,
John McCall2cf031d2011-10-01 01:01:08 +00002479
2480 /// id*, id***, void (^*)(),
2481 ACTC_indirectRetainable,
2482
2483 /// void* might be a normal C type, or it might a CF type.
2484 ACTC_voidPtr,
2485
2486 /// struct A*
2487 ACTC_coreFoundation
John McCallf85e1932011-06-15 23:02:42 +00002488};
John McCall2cf031d2011-10-01 01:01:08 +00002489static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2490 return (ACTC == ACTC_retainable ||
2491 ACTC == ACTC_coreFoundation ||
2492 ACTC == ACTC_voidPtr);
2493}
2494static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2495 return ACTC == ACTC_none ||
2496 ACTC == ACTC_voidPtr ||
2497 ACTC == ACTC_coreFoundation;
2498}
2499
John McCallf85e1932011-06-15 23:02:42 +00002500static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCall2cf031d2011-10-01 01:01:08 +00002501 bool isIndirect = false;
John McCallf85e1932011-06-15 23:02:42 +00002502
2503 // Ignore an outermost reference type.
John McCall2cf031d2011-10-01 01:01:08 +00002504 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCallf85e1932011-06-15 23:02:42 +00002505 type = ref->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002506 isIndirect = true;
2507 }
John McCallf85e1932011-06-15 23:02:42 +00002508
2509 // Drill through pointers and arrays recursively.
2510 while (true) {
2511 if (const PointerType *ptr = type->getAs<PointerType>()) {
2512 type = ptr->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002513
2514 // The first level of pointer may be the innermost pointer on a CF type.
2515 if (!isIndirect) {
2516 if (type->isVoidType()) return ACTC_voidPtr;
2517 if (type->isRecordType()) return ACTC_coreFoundation;
2518 }
John McCallf85e1932011-06-15 23:02:42 +00002519 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2520 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2521 } else {
2522 break;
2523 }
John McCall2cf031d2011-10-01 01:01:08 +00002524 isIndirect = true;
John McCallf85e1932011-06-15 23:02:42 +00002525 }
2526
John McCall2cf031d2011-10-01 01:01:08 +00002527 if (isIndirect) {
2528 if (type->isObjCARCBridgableType())
2529 return ACTC_indirectRetainable;
2530 return ACTC_none;
2531 }
2532
2533 if (type->isObjCARCBridgableType())
2534 return ACTC_retainable;
2535
2536 return ACTC_none;
John McCallf85e1932011-06-15 23:02:42 +00002537}
2538
2539namespace {
John McCall2cf031d2011-10-01 01:01:08 +00002540 /// A result from the cast checker.
2541 enum ACCResult {
2542 /// Cannot be casted.
2543 ACC_invalid,
2544
2545 /// Can be safely retained or not retained.
2546 ACC_bottom,
2547
2548 /// Can be casted at +0.
2549 ACC_plusZero,
2550
2551 /// Can be casted at +1.
2552 ACC_plusOne
2553 };
2554 ACCResult merge(ACCResult left, ACCResult right) {
2555 if (left == right) return left;
2556 if (left == ACC_bottom) return right;
2557 if (right == ACC_bottom) return left;
2558 return ACC_invalid;
2559 }
2560
2561 /// A checker which white-lists certain expressions whose conversion
2562 /// to or from retainable type would otherwise be forbidden in ARC.
2563 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2564 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2565
John McCallf85e1932011-06-15 23:02:42 +00002566 ASTContext &Context;
John McCall2cf031d2011-10-01 01:01:08 +00002567 ARCConversionTypeClass SourceClass;
2568 ARCConversionTypeClass TargetClass;
2569
2570 static bool isCFType(QualType type) {
2571 // Someday this can use ns_bridged. For now, it has to do this.
2572 return type->isCARCBridgableType();
John McCallf85e1932011-06-15 23:02:42 +00002573 }
John McCall2cf031d2011-10-01 01:01:08 +00002574
2575 public:
2576 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2577 ARCConversionTypeClass target)
2578 : Context(Context), SourceClass(source), TargetClass(target) {}
2579
2580 using super::Visit;
2581 ACCResult Visit(Expr *e) {
2582 return super::Visit(e->IgnoreParens());
2583 }
2584
2585 ACCResult VisitStmt(Stmt *s) {
2586 return ACC_invalid;
2587 }
2588
2589 /// Null pointer constants can be casted however you please.
2590 ACCResult VisitExpr(Expr *e) {
2591 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2592 return ACC_bottom;
2593 return ACC_invalid;
2594 }
2595
2596 /// Objective-C string literals can be safely casted.
2597 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2598 // If we're casting to any retainable type, go ahead. Global
2599 // strings are immune to retains, so this is bottom.
2600 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2601
2602 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002603 }
2604
John McCall2cf031d2011-10-01 01:01:08 +00002605 /// Look through certain implicit and explicit casts.
2606 ACCResult VisitCastExpr(CastExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002607 switch (e->getCastKind()) {
2608 case CK_NullToPointer:
John McCall2cf031d2011-10-01 01:01:08 +00002609 return ACC_bottom;
2610
John McCallf85e1932011-06-15 23:02:42 +00002611 case CK_NoOp:
2612 case CK_LValueToRValue:
2613 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002614 case CK_CPointerToObjCPointerCast:
2615 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002616 case CK_AnyPointerToBlockPointerCast:
2617 return Visit(e->getSubExpr());
John McCall2cf031d2011-10-01 01:01:08 +00002618
John McCallf85e1932011-06-15 23:02:42 +00002619 default:
John McCall2cf031d2011-10-01 01:01:08 +00002620 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002621 }
2622 }
John McCall2cf031d2011-10-01 01:01:08 +00002623
2624 /// Look through unary extension.
2625 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002626 return Visit(e->getSubExpr());
2627 }
John McCall2cf031d2011-10-01 01:01:08 +00002628
2629 /// Ignore the LHS of a comma operator.
2630 ACCResult VisitBinComma(BinaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002631 return Visit(e->getRHS());
2632 }
John McCall2cf031d2011-10-01 01:01:08 +00002633
2634 /// Conditional operators are okay if both sides are okay.
2635 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2636 ACCResult left = Visit(e->getTrueExpr());
2637 if (left == ACC_invalid) return ACC_invalid;
2638 return merge(left, Visit(e->getFalseExpr()));
John McCallf85e1932011-06-15 23:02:42 +00002639 }
John McCall2cf031d2011-10-01 01:01:08 +00002640
John McCall4b9c2d22011-11-06 09:01:30 +00002641 /// Look through pseudo-objects.
2642 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2643 // If we're getting here, we should always have a result.
2644 return Visit(e->getResultExpr());
2645 }
2646
John McCall2cf031d2011-10-01 01:01:08 +00002647 /// Statement expressions are okay if their result expression is okay.
2648 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002649 return Visit(e->getSubStmt()->body_back());
2650 }
John McCallf85e1932011-06-15 23:02:42 +00002651
John McCall2cf031d2011-10-01 01:01:08 +00002652 /// Some declaration references are okay.
2653 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2654 // References to global constants from system headers are okay.
2655 // These are things like 'kCFStringTransformToLatin'. They are
2656 // can also be assumed to be immune to retains.
2657 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2658 if (isAnyRetainable(TargetClass) &&
2659 isAnyRetainable(SourceClass) &&
2660 var &&
2661 var->getStorageClass() == SC_Extern &&
2662 var->getType().isConstQualified() &&
2663 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2664 return ACC_bottom;
2665 }
2666
2667 // Nothing else.
2668 return ACC_invalid;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00002669 }
John McCall2cf031d2011-10-01 01:01:08 +00002670
2671 /// Some calls are okay.
2672 ACCResult VisitCallExpr(CallExpr *e) {
2673 if (FunctionDecl *fn = e->getDirectCallee())
2674 if (ACCResult result = checkCallToFunction(fn))
2675 return result;
2676
2677 return super::VisitCallExpr(e);
2678 }
2679
2680 ACCResult checkCallToFunction(FunctionDecl *fn) {
2681 // Require a CF*Ref return type.
2682 if (!isCFType(fn->getResultType()))
2683 return ACC_invalid;
2684
2685 if (!isAnyRetainable(TargetClass))
2686 return ACC_invalid;
2687
2688 // Honor an explicit 'not retained' attribute.
2689 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2690 return ACC_plusZero;
2691
2692 // Honor an explicit 'retained' attribute, except that for
2693 // now we're not going to permit implicit handling of +1 results,
2694 // because it's a bit frightening.
2695 if (fn->hasAttr<CFReturnsRetainedAttr>())
2696 return ACC_invalid; // ACC_plusOne if we start accepting this
2697
2698 // Recognize this specific builtin function, which is used by CFSTR.
2699 unsigned builtinID = fn->getBuiltinID();
2700 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2701 return ACC_bottom;
2702
2703 // Otherwise, don't do anything implicit with an unaudited function.
2704 if (!fn->hasAttr<CFAuditedTransferAttr>())
2705 return ACC_invalid;
2706
2707 // Otherwise, it's +0 unless it follows the create convention.
2708 if (ento::coreFoundation::followsCreateRule(fn))
2709 return ACC_invalid; // ACC_plusOne if we start accepting this
2710
2711 return ACC_plusZero;
2712 }
2713
2714 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2715 return checkCallToMethod(e->getMethodDecl());
2716 }
2717
2718 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2719 ObjCMethodDecl *method;
2720 if (e->isExplicitProperty())
2721 method = e->getExplicitProperty()->getGetterMethodDecl();
2722 else
2723 method = e->getImplicitPropertyGetter();
2724 return checkCallToMethod(method);
2725 }
2726
2727 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2728 if (!method) return ACC_invalid;
2729
2730 // Check for message sends to functions returning CF types. We
2731 // just obey the Cocoa conventions with these, even though the
2732 // return type is CF.
2733 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2734 return ACC_invalid;
2735
2736 // If the method is explicitly marked not-retained, it's +0.
2737 if (method->hasAttr<CFReturnsNotRetainedAttr>())
2738 return ACC_plusZero;
2739
2740 // If the method is explicitly marked as returning retained, or its
2741 // selector follows a +1 Cocoa convention, treat it as +1.
2742 if (method->hasAttr<CFReturnsRetainedAttr>())
2743 return ACC_plusOne;
2744
2745 switch (method->getSelector().getMethodFamily()) {
2746 case OMF_alloc:
2747 case OMF_copy:
2748 case OMF_mutableCopy:
2749 case OMF_new:
2750 return ACC_plusOne;
2751
2752 default:
2753 // Otherwise, treat it as +0.
2754 return ACC_plusZero;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00002755 }
2756 }
John McCall2cf031d2011-10-01 01:01:08 +00002757 };
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00002758}
2759
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002760static bool
2761KnownName(Sema &S, const char *name) {
2762 LookupResult R(S, &S.Context.Idents.get(name), SourceLocation(),
2763 Sema::LookupOrdinaryName);
2764 return S.LookupName(R, S.TUScope, false);
2765}
2766
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002767static void addFixitForObjCARCConversion(Sema &S,
2768 DiagnosticBuilder &DiagB,
2769 Sema::CheckedConversionKind CCK,
2770 SourceLocation afterLParen,
2771 QualType castType,
2772 Expr *castExpr,
2773 const char *bridgeKeyword,
2774 const char *CFBridgeName) {
2775 // We handle C-style and implicit casts here.
2776 switch (CCK) {
2777 case Sema::CCK_ImplicitConversion:
2778 case Sema::CCK_CStyleCast:
2779 break;
2780 case Sema::CCK_FunctionalCast:
2781 case Sema::CCK_OtherCast:
2782 return;
2783 }
2784
2785 if (CFBridgeName) {
2786 Expr *castedE = castExpr;
2787 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2788 castedE = CCE->getSubExpr();
2789 castedE = castedE->IgnoreImpCasts();
2790 SourceRange range = castedE->getSourceRange();
2791 if (isa<ParenExpr>(castedE)) {
2792 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2793 CFBridgeName));
2794 } else {
2795 std::string namePlusParen = CFBridgeName;
2796 namePlusParen += "(";
2797 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2798 namePlusParen));
2799 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2800 S.PP.getLocForEndOfToken(range.getEnd()),
2801 ")"));
2802 }
2803 return;
2804 }
2805
2806 if (CCK == Sema::CCK_CStyleCast) {
2807 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
2808 } else {
2809 std::string castCode = "(";
2810 castCode += bridgeKeyword;
2811 castCode += castType.getAsString();
2812 castCode += ")";
2813 Expr *castedE = castExpr->IgnoreImpCasts();
2814 SourceRange range = castedE->getSourceRange();
2815 if (isa<ParenExpr>(castedE)) {
2816 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2817 castCode));
2818 } else {
2819 castCode += "(";
2820 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2821 castCode));
2822 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2823 S.PP.getLocForEndOfToken(range.getEnd()),
2824 ")"));
2825 }
2826 }
2827}
2828
John McCall5acb0c92011-10-17 18:40:02 +00002829static void
2830diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
2831 QualType castType, ARCConversionTypeClass castACTC,
2832 Expr *castExpr, ARCConversionTypeClass exprACTC,
2833 Sema::CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00002834 SourceLocation loc =
John McCall2cf031d2011-10-01 01:01:08 +00002835 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00002836
John McCall5acb0c92011-10-17 18:40:02 +00002837 if (S.makeUnavailableInSystemHeader(loc,
John McCall2cf031d2011-10-01 01:01:08 +00002838 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCallf85e1932011-06-15 23:02:42 +00002839 return;
John McCall5acb0c92011-10-17 18:40:02 +00002840
2841 QualType castExprType = castExpr->getType();
John McCallf85e1932011-06-15 23:02:42 +00002842
John McCall71c482c2011-06-17 06:50:50 +00002843 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00002844 switch (exprACTC) {
John McCall2cf031d2011-10-01 01:01:08 +00002845 case ACTC_none:
2846 case ACTC_coreFoundation:
2847 case ACTC_voidPtr:
2848 srcKind = (castExprType->isPointerType() ? 1 : 0);
2849 break;
2850 case ACTC_retainable:
2851 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
2852 break;
2853 case ACTC_indirectRetainable:
2854 srcKind = 4;
2855 break;
John McCallf85e1932011-06-15 23:02:42 +00002856 }
2857
John McCall5acb0c92011-10-17 18:40:02 +00002858 // Check whether this could be fixed with a bridge cast.
2859 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
2860 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCallf85e1932011-06-15 23:02:42 +00002861
John McCall5acb0c92011-10-17 18:40:02 +00002862 // Bridge from an ARC type to a CF type.
2863 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002864
John McCall5acb0c92011-10-17 18:40:02 +00002865 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2866 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2867 << 2 // of C pointer type
2868 << castExprType
2869 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
2870 << castType
2871 << castRange
2872 << castExpr->getSourceRange();
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002873 bool br = KnownName(S, "CFBridgingRelease");
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002874 {
2875 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2876 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2877 castType, castExpr, "__bridge ", 0);
2878 }
2879 {
2880 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_transfer)
2881 << castExprType << br;
2882 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2883 castType, castExpr, "__bridge_transfer ",
2884 br ? "CFBridgingRelease" : 0);
2885 }
John McCall5acb0c92011-10-17 18:40:02 +00002886
2887 return;
2888 }
2889
2890 // Bridge from a CF type to an ARC type.
2891 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002892 bool br = KnownName(S, "CFBridgingRetain");
John McCall5acb0c92011-10-17 18:40:02 +00002893 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2894 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2895 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
2896 << castExprType
2897 << 2 // to C pointer type
2898 << castType
2899 << castRange
2900 << castExpr->getSourceRange();
2901
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002902 {
2903 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2904 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2905 castType, castExpr, "__bridge ", 0);
2906 }
2907 {
2908 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_retained)
2909 << castType << br;
2910 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2911 castType, castExpr, "__bridge_retained ",
2912 br ? "CFBridgingRetain" : 0);
2913 }
John McCall5acb0c92011-10-17 18:40:02 +00002914
2915 return;
John McCallf85e1932011-06-15 23:02:42 +00002916 }
2917
John McCall5acb0c92011-10-17 18:40:02 +00002918 S.Diag(loc, diag::err_arc_mismatched_cast)
2919 << (CCK != Sema::CCK_ImplicitConversion)
2920 << srcKind << castExprType << castType
John McCallf85e1932011-06-15 23:02:42 +00002921 << castRange << castExpr->getSourceRange();
2922}
2923
John McCall5acb0c92011-10-17 18:40:02 +00002924Sema::ARCConversionResult
2925Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
2926 Expr *&castExpr, CheckedConversionKind CCK) {
2927 QualType castExprType = castExpr->getType();
2928
2929 // For the purposes of the classification, we assume reference types
2930 // will bind to temporaries.
2931 QualType effCastType = castType;
2932 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
2933 effCastType = ref->getPointeeType();
2934
2935 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
2936 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002937 if (exprACTC == castACTC) {
2938 // check for viablity and report error if casting an rvalue to a
2939 // life-time qualifier.
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002940 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002941 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002942 (castType != castExprType)) {
2943 const Type *DT = castType.getTypePtr();
2944 QualType QDT = castType;
2945 // We desugar some types but not others. We ignore those
2946 // that cannot happen in a cast; i.e. auto, and those which
2947 // should not be de-sugared; i.e typedef.
2948 if (const ParenType *PT = dyn_cast<ParenType>(DT))
2949 QDT = PT->desugar();
2950 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
2951 QDT = TP->desugar();
2952 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
2953 QDT = AT->desugar();
2954 if (QDT != castType &&
2955 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
2956 SourceLocation loc =
2957 (castRange.isValid() ? castRange.getBegin()
2958 : castExpr->getExprLoc());
2959 Diag(loc, diag::err_arc_nolifetime_behavior);
2960 }
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002961 }
2962 return ACR_okay;
2963 }
2964
John McCall5acb0c92011-10-17 18:40:02 +00002965 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
2966
2967 // Allow all of these types to be cast to integer types (but not
2968 // vice-versa).
2969 if (castACTC == ACTC_none && castType->isIntegralType(Context))
2970 return ACR_okay;
2971
2972 // Allow casts between pointers to lifetime types (e.g., __strong id*)
2973 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
2974 // must be explicit.
2975 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
2976 return ACR_okay;
2977 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
2978 CCK != CCK_ImplicitConversion)
2979 return ACR_okay;
2980
2981 switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
2982 // For invalid casts, fall through.
2983 case ACC_invalid:
2984 break;
2985
2986 // Do nothing for both bottom and +0.
2987 case ACC_bottom:
2988 case ACC_plusZero:
2989 return ACR_okay;
2990
2991 // If the result is +1, consume it here.
2992 case ACC_plusOne:
2993 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
2994 CK_ARCConsumeObject, castExpr,
2995 0, VK_RValue);
2996 ExprNeedsCleanups = true;
2997 return ACR_okay;
2998 }
2999
3000 // If this is a non-implicit cast from id or block type to a
3001 // CoreFoundation type, delay complaining in case the cast is used
3002 // in an acceptable context.
3003 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3004 CCK != CCK_ImplicitConversion)
3005 return ACR_unbridged;
3006
3007 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3008 castExpr, exprACTC, CCK);
3009 return ACR_okay;
3010}
3011
3012/// Given that we saw an expression with the ARCUnbridgedCastTy
3013/// placeholder type, complain bitterly.
3014void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3015 // We expect the spurious ImplicitCastExpr to already have been stripped.
3016 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3017 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3018
3019 SourceRange castRange;
3020 QualType castType;
3021 CheckedConversionKind CCK;
3022
3023 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3024 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3025 castType = cast->getTypeAsWritten();
3026 CCK = CCK_CStyleCast;
3027 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3028 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3029 castType = cast->getTypeAsWritten();
3030 CCK = CCK_OtherCast;
3031 } else {
3032 castType = cast->getType();
3033 CCK = CCK_ImplicitConversion;
3034 }
3035
3036 ARCConversionTypeClass castACTC =
3037 classifyTypeForARCConversion(castType.getNonReferenceType());
3038
3039 Expr *castExpr = realCast->getSubExpr();
3040 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3041
3042 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3043 castExpr, ACTC_retainable, CCK);
3044}
3045
3046/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3047/// type, remove the placeholder cast.
3048Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3049 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3050
3051 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3052 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3053 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3054 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3055 assert(uo->getOpcode() == UO_Extension);
3056 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3057 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3058 sub->getValueKind(), sub->getObjectKind(),
3059 uo->getOperatorLoc());
3060 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3061 assert(!gse->isResultDependent());
3062
3063 unsigned n = gse->getNumAssocs();
3064 SmallVector<Expr*, 4> subExprs(n);
3065 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3066 for (unsigned i = 0; i != n; ++i) {
3067 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3068 Expr *sub = gse->getAssocExpr(i);
3069 if (i == gse->getResultIndex())
3070 sub = stripARCUnbridgedCast(sub);
3071 subExprs[i] = sub;
3072 }
3073
3074 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3075 gse->getControllingExpr(),
3076 subTypes.data(), subExprs.data(),
3077 n, gse->getDefaultLoc(),
3078 gse->getRParenLoc(),
3079 gse->containsUnexpandedParameterPack(),
3080 gse->getResultIndex());
3081 } else {
3082 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3083 return cast<ImplicitCastExpr>(e)->getSubExpr();
3084 }
3085}
3086
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00003087bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3088 QualType exprType) {
3089 QualType canCastType =
3090 Context.getCanonicalType(castType).getUnqualifiedType();
3091 QualType canExprType =
3092 Context.getCanonicalType(exprType).getUnqualifiedType();
3093 if (isa<ObjCObjectPointerType>(canCastType) &&
3094 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3095 canExprType->isObjCObjectPointerType()) {
3096 if (const ObjCObjectPointerType *ObjT =
3097 canExprType->getAs<ObjCObjectPointerType>())
3098 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
3099 return false;
3100 }
3101 return true;
3102}
3103
John McCall7e5e5f42011-07-07 06:58:02 +00003104/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3105static Expr *maybeUndoReclaimObject(Expr *e) {
3106 // For now, we just undo operands that are *immediately* reclaim
3107 // expressions, which prevents the vast majority of potential
3108 // problems here. To catch them all, we'd need to rebuild arbitrary
3109 // value-propagating subexpressions --- we can't reliably rebuild
3110 // in-place because of expression sharing.
3111 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00003112 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00003113 return ice->getSubExpr();
3114
3115 return e;
3116}
3117
John McCallf85e1932011-06-15 23:02:42 +00003118ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3119 ObjCBridgeCastKind Kind,
3120 SourceLocation BridgeKeywordLoc,
3121 TypeSourceInfo *TSInfo,
3122 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00003123 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3124 if (SubResult.isInvalid()) return ExprError();
3125 SubExpr = SubResult.take();
3126
John McCallf85e1932011-06-15 23:02:42 +00003127 QualType T = TSInfo->getType();
3128 QualType FromType = SubExpr->getType();
3129
John McCall1d9b3b22011-09-09 05:25:32 +00003130 CastKind CK;
3131
John McCallf85e1932011-06-15 23:02:42 +00003132 bool MustConsume = false;
3133 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3134 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00003135 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00003136 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3137 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00003138 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3139 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00003140 switch (Kind) {
3141 case OBC_Bridge:
3142 break;
3143
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003144 case OBC_BridgeRetained: {
3145 bool br = KnownName(*this, "CFBridgingRelease");
John McCallf85e1932011-06-15 23:02:42 +00003146 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3147 << 2
3148 << FromType
3149 << (T->isBlockPointerType()? 1 : 0)
3150 << T
3151 << SubExpr->getSourceRange()
3152 << Kind;
3153 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3154 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3155 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003156 << FromType << br
John McCallf85e1932011-06-15 23:02:42 +00003157 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003158 br ? "CFBridgingRelease "
3159 : "__bridge_transfer ");
John McCallf85e1932011-06-15 23:02:42 +00003160
3161 Kind = OBC_Bridge;
3162 break;
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003163 }
John McCallf85e1932011-06-15 23:02:42 +00003164
3165 case OBC_BridgeTransfer:
3166 // We must consume the Objective-C object produced by the cast.
3167 MustConsume = true;
3168 break;
3169 }
3170 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3171 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00003172 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00003173 switch (Kind) {
3174 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00003175 // Reclaiming a value that's going to be __bridge-casted to CF
3176 // is very dangerous, so we don't do it.
3177 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00003178 break;
3179
3180 case OBC_BridgeRetained:
3181 // Produce the object before casting it.
3182 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00003183 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00003184 SubExpr, 0, VK_RValue);
3185 break;
3186
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003187 case OBC_BridgeTransfer: {
3188 bool br = KnownName(*this, "CFBridgingRetain");
John McCallf85e1932011-06-15 23:02:42 +00003189 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3190 << (FromType->isBlockPointerType()? 1 : 0)
3191 << FromType
3192 << 2
3193 << T
3194 << SubExpr->getSourceRange()
3195 << Kind;
3196
3197 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3198 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3199 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003200 << T << br
3201 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3202 br ? "CFBridgingRetain " : "__bridge_retained");
John McCallf85e1932011-06-15 23:02:42 +00003203
3204 Kind = OBC_Bridge;
3205 break;
3206 }
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003207 }
John McCallf85e1932011-06-15 23:02:42 +00003208 } else {
3209 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3210 << FromType << T << Kind
3211 << SubExpr->getSourceRange()
3212 << TSInfo->getTypeLoc().getSourceRange();
3213 return ExprError();
3214 }
3215
John McCall1d9b3b22011-09-09 05:25:32 +00003216 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00003217 BridgeKeywordLoc,
3218 TSInfo, SubExpr);
3219
3220 if (MustConsume) {
3221 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00003222 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00003223 0, VK_RValue);
3224 }
3225
3226 return Result;
3227}
3228
3229ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3230 SourceLocation LParenLoc,
3231 ObjCBridgeCastKind Kind,
3232 SourceLocation BridgeKeywordLoc,
3233 ParsedType Type,
3234 SourceLocation RParenLoc,
3235 Expr *SubExpr) {
3236 TypeSourceInfo *TSInfo = 0;
3237 QualType T = GetTypeFromParser(Type, &TSInfo);
3238 if (!TSInfo)
3239 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3240 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3241 SubExpr);
3242}