blob: ed71eb128c693db28090300ffae0e9dbcd075644 [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,
Douglas Gregord10099e2012-05-04 16:32:21 +0000913 diag::err_incomplete_type_objc_at_encode,
914 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000915 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 Gregord10099e2012-05-04 16:32:21 +00001179 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001180 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +00001181
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001182 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall5acb0c92011-10-17 18:40:02 +00001183 param);
John McCall3fa5cae2010-10-26 07:05:15 +00001184 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001185 if (ArgE.isInvalid())
1186 IsError = true;
1187 else
1188 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +00001189 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001190
1191 // Promote additional arguments to variadic methods.
1192 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001193 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
1194 if (Args[i]->isTypeDependent())
1195 continue;
1196
John Wiegley429bb272011-04-08 18:41:53 +00001197 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
1198 IsError |= Arg.isInvalid();
1199 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +00001200 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001201 } else {
1202 // Check for extra arguments to non-variadic methods.
1203 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001204 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001205 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001206 << 2 /*method*/ << NumNamedArgs << NumArgs
1207 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001208 << SourceRange(Args[NumNamedArgs]->getLocStart(),
1209 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001210 }
1211 }
1212
Douglas Gregor2725ca82010-04-21 19:57:20 +00001213 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001214
1215 // Do additional checkings on method.
1216 IsError |= CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
1217
Chris Lattner312531a2009-04-12 08:11:20 +00001218 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +00001219}
1220
Douglas Gregorc737acb2011-09-27 16:10:05 +00001221bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +00001222 // 'self' is objc 'self' in an objc method only.
John McCall4b9c2d22011-11-06 09:01:30 +00001223 ObjCMethodDecl *method =
1224 dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1225 if (!method) return false;
1226
John McCallf85e1932011-06-15 23:02:42 +00001227 receiver = receiver->IgnoreParenLValueCasts();
1228 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCall4b9c2d22011-11-06 09:01:30 +00001229 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregorc737acb2011-09-27 16:10:05 +00001230 return true;
1231 return false;
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001232}
1233
Steve Narofff1afaf62009-02-26 15:55:06 +00001234// Helper method for ActOnClassMethod/ActOnInstanceMethod.
1235// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +00001236// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +00001237// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +00001238ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +00001239 ObjCInterfaceDecl *ClassDecl) {
1240 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +00001241 // lookup in class and all superclasses
1242 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001243 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001244 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001245
Steve Naroff5609ec02009-03-08 18:56:13 +00001246 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001247 if (!Method)
1248 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Steve Naroff5609ec02009-03-08 18:56:13 +00001250 // Before we give up, check if the selector is an instance method.
1251 // But only in the root. This matches gcc's behaviour and what the
1252 // runtime expects.
1253 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001254 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001255 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +00001256 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +00001257 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +00001258 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1259 }
Mike Stump1eb44332009-09-09 15:08:12 +00001260
Steve Naroff5609ec02009-03-08 18:56:13 +00001261 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +00001262 }
Steve Naroff5609ec02009-03-08 18:56:13 +00001263 return Method;
1264}
1265
1266ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
1267 ObjCInterfaceDecl *ClassDecl) {
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00001268 if (!ClassDecl->hasDefinition())
1269 return 0;
1270
Steve Naroff5609ec02009-03-08 18:56:13 +00001271 ObjCMethodDecl *Method = 0;
1272 while (ClassDecl && !Method) {
1273 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001274 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001275 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001276
Steve Naroff5609ec02009-03-08 18:56:13 +00001277 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001278 if (!Method)
1279 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +00001280 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +00001281 }
Steve Narofff1afaf62009-02-26 15:55:06 +00001282 return Method;
1283}
1284
John McCall3c3b7f92011-10-25 17:37:35 +00001285/// LookupMethodInType - Look up a method in an ObjCObjectType.
1286ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1287 bool isInstance) {
1288 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1289 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1290 // Look it up in the main interface (and categories, etc.)
1291 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1292 return method;
1293
1294 // Okay, look for "private" methods declared in any
1295 // @implementations we've seen.
1296 if (isInstance) {
1297 if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
1298 return method;
1299 } else {
1300 if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
1301 return method;
1302 }
1303 }
1304
1305 // Check qualifiers.
1306 for (ObjCObjectType::qual_iterator
1307 i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
1308 if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
1309 return method;
1310
1311 return 0;
1312}
1313
Fariborz Jahanian61478062011-03-09 20:18:06 +00001314/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1315/// list of a qualified objective pointer type.
1316ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1317 const ObjCObjectPointerType *OPT,
1318 bool Instance)
1319{
1320 ObjCMethodDecl *MD = 0;
1321 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1322 E = OPT->qual_end(); I != E; ++I) {
1323 ObjCProtocolDecl *PROTO = (*I);
1324 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1325 return MD;
1326 }
1327 }
1328 return 0;
1329}
1330
Fariborz Jahanian98795562012-04-19 23:49:39 +00001331static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1332 if (!Receiver)
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001333 return;
1334
Fariborz Jahanian98795562012-04-19 23:49:39 +00001335 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1336 SourceLocation Loc = RExpr->getLocStart();
1337 QualType T = RExpr->getType();
1338 ObjCPropertyDecl *PDecl = 0;
1339 ObjCMethodDecl *GDecl = 0;
1340 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1341 RExpr = POE->getSyntacticForm();
1342 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1343 if (PRE->isImplicitProperty()) {
1344 GDecl = PRE->getImplicitPropertyGetter();
1345 if (GDecl) {
1346 T = GDecl->getResultType();
1347 }
1348 }
1349 else {
1350 PDecl = PRE->getExplicitProperty();
1351 if (PDecl) {
1352 T = PDecl->getType();
1353 }
1354 }
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001355 }
Fariborz Jahanian98795562012-04-19 23:49:39 +00001356 }
1357
1358 if (T.getObjCLifetime() == Qualifiers::OCL_Weak) {
1359 S.Diag(Loc, diag::warn_receiver_is_weak)
1360 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1361 if (PDecl)
1362 S.Diag(PDecl->getLocation(), diag::note_property_declare);
1363 else if (GDecl)
1364 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001365 return;
1366 }
1367
Fariborz Jahanian98795562012-04-19 23:49:39 +00001368 if (PDecl &&
1369 (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)) {
1370 S.Diag(Loc, diag::warn_receiver_is_weak) << 1;
1371 S.Diag(PDecl->getLocation(), diag::note_property_declare);
1372 }
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001373}
1374
Chris Lattner7f816522010-04-11 07:45:24 +00001375/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1376/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001377ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +00001378HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001379 Expr *BaseExpr, SourceLocation OpLoc,
1380 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001381 SourceLocation MemberLoc,
1382 SourceLocation SuperLoc, QualType SuperType,
1383 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +00001384 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1385 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +00001386
1387 if (MemberName.getNameKind() != DeclarationName::Identifier) {
1388 Diag(MemberLoc, diag::err_invalid_property_name)
1389 << MemberName << QualType(OPT, 0);
1390 return ExprError();
1391 }
1392
Chris Lattner7f816522010-04-11 07:45:24 +00001393 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregorb3029962011-11-14 22:10:01 +00001394 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1395 : BaseExpr->getSourceRange();
1396 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00001397 diag::err_property_not_found_forward_class,
1398 MemberName, BaseRange))
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +00001399 return ExprError();
Douglas Gregorb3029962011-11-14 22:10:01 +00001400
Chris Lattner7f816522010-04-11 07:45:24 +00001401 // Search for a declared property first.
1402 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1403 // Check whether we can reference this property.
1404 if (DiagnoseUseOfDecl(PD, MemberLoc))
1405 return ExprError();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001406 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001407 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001408 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001409 MemberLoc,
1410 SuperLoc, SuperType));
1411 else
John McCall3c3b7f92011-10-25 17:37:35 +00001412 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001413 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001414 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001415 }
1416 // Check protocols on qualified interfaces.
1417 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1418 E = OPT->qual_end(); I != E; ++I)
1419 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1420 // Check whether we can reference this property.
1421 if (DiagnoseUseOfDecl(PD, MemberLoc))
1422 return ExprError();
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001423
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001424 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001425 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1426 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001427 VK_LValue,
1428 OK_ObjCProperty,
1429 MemberLoc,
1430 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001431 else
John McCall3c3b7f92011-10-25 17:37:35 +00001432 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1433 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001434 VK_LValue,
1435 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001436 MemberLoc,
1437 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001438 }
1439 // If that failed, look for an "implicit" property by seeing if the nullary
1440 // selector is implemented.
1441
1442 // FIXME: The logic for looking up nullary and unary selectors should be
1443 // shared with the code in ActOnInstanceMessage.
1444
1445 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1446 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001447
1448 // May be founf in property's qualified list.
1449 if (!Getter)
1450 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +00001451
1452 // If this reference is in an @implementation, check for 'private' methods.
1453 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001454 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +00001455
1456 // Look through local category implementations associated with the class.
1457 if (!Getter)
1458 Getter = IFace->getCategoryInstanceMethod(Sel);
1459 if (Getter) {
1460 // Check if we can reference this property.
1461 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1462 return ExprError();
1463 }
1464 // If we found a getter then this may be a valid dot-reference, we
1465 // will look for the matching setter, in case it is needed.
1466 Selector SetterSel =
1467 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1468 PP.getSelectorTable(), Member);
1469 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001470
1471 // May be founf in property's qualified list.
1472 if (!Setter)
1473 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1474
Chris Lattner7f816522010-04-11 07:45:24 +00001475 if (!Setter) {
1476 // If this reference is in an @implementation, also check for 'private'
1477 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001478 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +00001479 }
1480 // Look through local category implementations associated with the class.
1481 if (!Setter)
1482 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001483
Chris Lattner7f816522010-04-11 07:45:24 +00001484 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1485 return ExprError();
1486
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001487 if (Getter || Setter) {
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001488 if (Super)
John McCall12f78a62010-12-02 01:19:52 +00001489 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001490 Context.PseudoObjectTy,
1491 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001492 MemberLoc,
1493 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001494 else
John McCall12f78a62010-12-02 01:19:52 +00001495 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001496 Context.PseudoObjectTy,
1497 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001498 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001499
Chris Lattner7f816522010-04-11 07:45:24 +00001500 }
1501
1502 // Attempt to correct for typos in property names.
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001503 DeclFilterCCC<ObjCPropertyDecl> Validator;
1504 if (TypoCorrection Corrected = CorrectTypo(
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001505 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001506 NULL, Validator, IFace, false, OPT)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001507 ObjCPropertyDecl *Property =
1508 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001509 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +00001510 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001511 << MemberName << QualType(OPT, 0) << TypoResult
1512 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +00001513 Diag(Property->getLocation(), diag::note_previous_decl)
1514 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001515 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1516 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001517 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +00001518 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001519 ObjCInterfaceDecl *ClassDeclared;
1520 if (ObjCIvarDecl *Ivar =
1521 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1522 QualType T = Ivar->getType();
1523 if (const ObjCObjectPointerType * OBJPT =
1524 T->getAsObjCInterfacePointerType()) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001525 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00001526 diag::err_property_not_as_forward_class,
1527 MemberName, BaseExpr))
Douglas Gregorb3029962011-11-14 22:10:01 +00001528 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001529 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001530 Diag(MemberLoc,
1531 diag::err_ivar_access_using_property_syntax_suggest)
1532 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1533 << FixItHint::CreateReplacement(OpLoc, "->");
1534 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001535 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001536
Chris Lattner7f816522010-04-11 07:45:24 +00001537 Diag(MemberLoc, diag::err_property_not_found)
1538 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001539 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +00001540 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001541 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +00001542 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +00001543}
1544
1545
1546
John McCall60d7b3a2010-08-24 06:29:42 +00001547ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +00001548ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1549 IdentifierInfo &propertyName,
1550 SourceLocation receiverNameLoc,
1551 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001552
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001553 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +00001554 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1555 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +00001556
1557 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +00001558 if (IFace == 0) {
1559 // If the "receiver" is 'super' in a method, handle it as an expression-like
1560 // property reference.
John McCall26743b22011-02-03 09:00:02 +00001561 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001562 IsSuper = true;
1563
Eli Friedmanb942cb22012-02-03 22:47:37 +00001564 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnereb483eb2010-04-11 08:28:14 +00001565 if (CurMethod->isInstanceMethod()) {
1566 QualType T =
1567 Context.getObjCInterfaceType(CurMethod->getClassInterface());
1568 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001569
1570 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001571 /*BaseExpr*/0,
1572 SourceLocation()/*OpLoc*/,
1573 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001574 propertyNameLoc,
1575 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001576 }
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Chris Lattnereb483eb2010-04-11 08:28:14 +00001578 // Otherwise, if this is a class method, try dispatching to our
1579 // superclass.
1580 IFace = CurMethod->getClassInterface()->getSuperClass();
1581 }
John McCall26743b22011-02-03 09:00:02 +00001582 }
Chris Lattnereb483eb2010-04-11 08:28:14 +00001583
1584 if (IFace == 0) {
1585 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1586 return ExprError();
1587 }
1588 }
1589
1590 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +00001591 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001592 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001593
1594 // If this reference is in an @implementation, check for 'private' methods.
1595 if (!Getter)
1596 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1597 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001598 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001599 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001600
1601 if (Getter) {
1602 // FIXME: refactor/share with ActOnMemberReference().
1603 // Check if we can reference this property.
1604 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1605 return ExprError();
1606 }
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Steve Naroff61f72cb2009-03-09 21:12:44 +00001608 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00001609 Selector SetterSel =
1610 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +00001611 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001613 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001614 if (!Setter) {
1615 // If this reference is in an @implementation, also check for 'private'
1616 // methods.
1617 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1618 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001619 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001620 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001621 }
1622 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001623 if (!Setter)
1624 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001625
1626 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1627 return ExprError();
1628
1629 if (Getter || Setter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001630 if (IsSuper)
1631 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001632 Context.PseudoObjectTy,
1633 VK_LValue, OK_ObjCProperty,
Douglas Gregor926df6c2011-06-11 01:09:30 +00001634 propertyNameLoc,
1635 receiverNameLoc,
1636 Context.getObjCInterfaceType(IFace)));
1637
John McCall12f78a62010-12-02 01:19:52 +00001638 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001639 Context.PseudoObjectTy,
1640 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001641 propertyNameLoc,
1642 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +00001643 }
1644 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1645 << &propertyName << Context.getObjCInterfaceType(IFace));
1646}
1647
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001648namespace {
1649
1650class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1651 public:
1652 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1653 // Determine whether "super" is acceptable in the current context.
1654 if (Method && Method->getClassInterface())
1655 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1656 }
1657
1658 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1659 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1660 candidate.isKeyword("super");
1661 }
1662};
1663
1664}
1665
Douglas Gregor47bd5432010-04-14 02:46:37 +00001666Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +00001667 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +00001668 SourceLocation NameLoc,
1669 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +00001670 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +00001671 ParsedType &ReceiverType) {
1672 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +00001673
Douglas Gregor47bd5432010-04-14 02:46:37 +00001674 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +00001675 // messaging super. If the identifier is "super" and there is a
1676 // trailing dot, it's an instance message.
1677 if (IsSuper && S->isInObjcMethodScope())
1678 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001679
1680 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1681 LookupName(Result, S);
1682
1683 switch (Result.getResultKind()) {
1684 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +00001685 // Normal name lookup didn't find anything. If we're in an
1686 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +00001687 // FIXME: This is a hack. Ivar lookup should be part of normal
1688 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +00001689 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidisccc9e762011-11-09 00:22:48 +00001690 if (!Method->getClassInterface()) {
1691 // Fall back: let the parser try to parse it as an instance message.
1692 return ObjCInstanceMessage;
1693 }
1694
Douglas Gregored464422010-04-19 20:09:36 +00001695 ObjCInterfaceDecl *ClassDeclared;
1696 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1697 ClassDeclared))
1698 return ObjCInstanceMessage;
1699 }
Douglas Gregor95f42922010-10-14 22:11:03 +00001700
Douglas Gregor47bd5432010-04-14 02:46:37 +00001701 // Break out; we'll perform typo correction below.
1702 break;
1703
1704 case LookupResult::NotFoundInCurrentInstantiation:
1705 case LookupResult::FoundOverloaded:
1706 case LookupResult::FoundUnresolvedValue:
1707 case LookupResult::Ambiguous:
1708 Result.suppressDiagnostics();
1709 return ObjCInstanceMessage;
1710
1711 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +00001712 // If the identifier is a class or not, and there is a trailing dot,
1713 // it's an instance message.
1714 if (HasTrailingDot)
1715 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001716 // We found something. If it's a type, then we have a class
1717 // message. Otherwise, it's an instance message.
1718 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +00001719 QualType T;
1720 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1721 T = Context.getObjCInterfaceType(Class);
1722 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
1723 T = Context.getTypeDeclType(Type);
1724 else
1725 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001726
Douglas Gregor1569f952010-04-21 20:38:13 +00001727 // We have a class message, and T is the type we're
1728 // messaging. Build source-location information for it.
1729 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +00001730 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +00001731 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001732 }
1733 }
1734
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001735 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001736 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1737 Result.getLookupKind(), S, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001738 Validator)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001739 if (Corrected.isKeyword()) {
1740 // If we've found the keyword "super" (the only keyword that would be
1741 // returned by CorrectTypo), this is a send to super.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001742 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001743 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +00001744 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +00001745 return ObjCSuperMessage;
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001746 } else if (ObjCInterfaceDecl *Class =
1747 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1748 // If we found a declaration, correct when it refers to an Objective-C
1749 // class.
1750 Diag(NameLoc, diag::err_unknown_receiver_suggest)
1751 << Name << Corrected.getCorrection()
1752 << FixItHint::CreateReplacement(SourceRange(NameLoc),
1753 Class->getNameAsString());
1754 Diag(Class->getLocation(), diag::note_previous_decl)
1755 << Corrected.getCorrection();
1756
1757 QualType T = Context.getObjCInterfaceType(Class);
1758 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1759 ReceiverType = CreateParsedType(T, TSInfo);
1760 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001761 }
1762 }
1763
1764 // Fall back: let the parser try to parse it as an instance message.
1765 return ObjCInstanceMessage;
1766}
Steve Naroff61f72cb2009-03-09 21:12:44 +00001767
John McCall60d7b3a2010-08-24 06:29:42 +00001768ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001769 SourceLocation SuperLoc,
1770 Selector Sel,
1771 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001772 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001773 SourceLocation RBracLoc,
1774 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001775 // Determine whether we are inside a method or not.
Eli Friedmanb942cb22012-02-03 22:47:37 +00001776 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregorf95861a2010-04-21 20:01:04 +00001777 if (!Method) {
1778 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1779 return ExprError();
1780 }
Chris Lattner85a932e2008-01-04 22:32:30 +00001781
Douglas Gregorf95861a2010-04-21 20:01:04 +00001782 ObjCInterfaceDecl *Class = Method->getClassInterface();
1783 if (!Class) {
1784 Diag(SuperLoc, diag::error_no_super_class_message)
1785 << Method->getDeclName();
1786 return ExprError();
1787 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001788
Douglas Gregorf95861a2010-04-21 20:01:04 +00001789 ObjCInterfaceDecl *Super = Class->getSuperClass();
1790 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001791 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +00001792 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1793 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001794 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +00001795 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001796
Douglas Gregorf95861a2010-04-21 20:01:04 +00001797 // We are in a method whose class has a superclass, so 'super'
1798 // is acting as a keyword.
1799 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +00001800 if (Sel.getMethodFamily() == OMF_dealloc)
1801 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00001802 if (Sel.getMethodFamily() == OMF_finalize)
1803 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +00001804
Douglas Gregorf95861a2010-04-21 20:01:04 +00001805 // Since we are in an instance method, this is an instance
1806 // message to the superclass instance.
1807 QualType SuperTy = Context.getObjCInterfaceType(Super);
1808 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +00001809 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001810 Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001811 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001812 }
Douglas Gregorf95861a2010-04-21 20:01:04 +00001813
1814 // Since we are in a class method, this is a class message to
1815 // the superclass.
1816 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1817 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001818 SuperLoc, Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001819 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001820}
1821
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001822
1823ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1824 bool isSuperReceiver,
1825 SourceLocation Loc,
1826 Selector Sel,
1827 ObjCMethodDecl *Method,
1828 MultiExprArg Args) {
1829 TypeSourceInfo *receiverTypeInfo = 0;
1830 if (!ReceiverType.isNull())
1831 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1832
1833 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1834 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1835 Sel, Method, Loc, Loc, Loc, Args,
1836 /*isImplicit=*/true);
1837
1838}
1839
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001840static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1841 unsigned DiagID,
1842 bool (*refactor)(const ObjCMessageExpr *,
1843 const NSAPI &, edit::Commit &)) {
1844 SourceLocation MsgLoc = Msg->getExprLoc();
1845 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
1846 return;
1847
1848 SourceManager &SM = S.SourceMgr;
1849 edit::Commit ECommit(SM, S.LangOpts);
1850 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1851 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1852 << Msg->getSelector() << Msg->getSourceRange();
1853 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1854 if (!ECommit.isCommitable())
1855 return;
1856 for (edit::Commit::edit_iterator
1857 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1858 const edit::Commit::Edit &Edit = *I;
1859 switch (Edit.Kind) {
1860 case edit::Commit::Act_Insert:
1861 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1862 Edit.Text,
1863 Edit.BeforePrev));
1864 break;
1865 case edit::Commit::Act_InsertFromRange:
1866 Builder.AddFixItHint(
1867 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1868 Edit.getInsertFromRange(SM),
1869 Edit.BeforePrev));
1870 break;
1871 case edit::Commit::Act_Remove:
1872 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1873 break;
1874 }
1875 }
1876 }
1877}
1878
1879static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1880 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1881 edit::rewriteObjCRedundantCallWithLiteral);
1882}
1883
Douglas Gregor2725ca82010-04-21 19:57:20 +00001884/// \brief Build an Objective-C class message expression.
1885///
1886/// This routine takes care of both normal class messages and
1887/// class messages to the superclass.
1888///
1889/// \param ReceiverTypeInfo Type source information that describes the
1890/// receiver of this message. This may be NULL, in which case we are
1891/// sending to the superclass and \p SuperLoc must be a valid source
1892/// location.
1893
1894/// \param ReceiverType The type of the object receiving the
1895/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1896/// type as that refers to. For a superclass send, this is the type of
1897/// the superclass.
1898///
1899/// \param SuperLoc The location of the "super" keyword in a
1900/// superclass message.
1901///
1902/// \param Sel The selector to which the message is being sent.
1903///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001904/// \param Method The method that this class message is invoking, if
1905/// already known.
1906///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001907/// \param LBracLoc The location of the opening square bracket ']'.
1908///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001909/// \param RBrac The location of the closing square bracket ']'.
1910///
1911/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001912ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001913 QualType ReceiverType,
1914 SourceLocation SuperLoc,
1915 Selector Sel,
1916 ObjCMethodDecl *Method,
1917 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001918 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001919 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001920 MultiExprArg ArgsIn,
1921 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001922 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001923 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001924 if (LBracLoc.isInvalid()) {
1925 Diag(Loc, diag::err_missing_open_square_message_send)
1926 << FixItHint::CreateInsertion(Loc, "[");
1927 LBracLoc = Loc;
1928 }
1929
Douglas Gregor92e986e2010-04-22 16:44:27 +00001930 if (ReceiverType->isDependentType()) {
1931 // If the receiver type is dependent, we can't type-check anything
1932 // at this point. Build a dependent expression.
1933 unsigned NumArgs = ArgsIn.size();
1934 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1935 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001936 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1937 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001938 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001939 makeArrayRef(Args, NumArgs),RBracLoc,
1940 isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001941 }
Chris Lattner15faee12010-04-12 05:38:43 +00001942
Douglas Gregor2725ca82010-04-21 19:57:20 +00001943 // Find the class to which we are sending this message.
1944 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001945 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1946 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001947 Diag(Loc, diag::err_invalid_receiver_class_message)
1948 << ReceiverType;
1949 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001950 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001951 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001952 // objc++ diagnoses during typename annotation.
David Blaikie4e4d0842012-03-11 07:00:24 +00001953 if (!getLangOpts().CPlusPlus)
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001954 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001955 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001956 if (!Method) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001957 SourceRange TypeRange
1958 = SuperLoc.isValid()? SourceRange(SuperLoc)
1959 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00001960 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikie4e4d0842012-03-11 07:00:24 +00001961 (getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001962 ? diag::err_arc_receiver_forward_class
1963 : diag::warn_receiver_forward_class),
1964 TypeRange)) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001965 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001966 Method = LookupFactoryMethodInGlobalPool(Sel,
1967 SourceRange(LBracLoc, RBracLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00001968 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001969 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1970 << Method->getDeclName();
1971 }
1972 if (!Method)
1973 Method = Class->lookupClassMethod(Sel);
1974
1975 // If we have an implementation in scope, check "private" methods.
1976 if (!Method)
1977 Method = LookupPrivateClassMethod(Sel, Class);
1978
1979 if (Method && DiagnoseUseOfDecl(Method, Loc))
1980 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001981 }
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Douglas Gregor2725ca82010-04-21 19:57:20 +00001983 // Check the argument types and determine the result type.
1984 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001985 ExprValueKind VK = VK_RValue;
1986
Douglas Gregor2725ca82010-04-21 19:57:20 +00001987 unsigned NumArgs = ArgsIn.size();
1988 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001989 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1990 SuperLoc.isValid(), LBracLoc, RBracLoc,
1991 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001992 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001993
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001994 if (Method && !Method->getResultType()->isVoidType() &&
1995 RequireCompleteType(LBracLoc, Method->getResultType(),
1996 diag::err_illegal_message_expr_incomplete_type))
1997 return ExprError();
1998
Douglas Gregor2725ca82010-04-21 19:57:20 +00001999 // Construct the appropriate ObjCMessageExpr.
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002000 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00002001 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00002002 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002003 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002004 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002005 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002006 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002007 else {
John McCallf89e55a2010-11-18 06:31:45 +00002008 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002009 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002010 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002011 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002012 if (!isImplicit)
2013 checkCocoaAPI(*this, Result);
2014 }
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002015 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00002016}
2017
Douglas Gregor2725ca82010-04-21 19:57:20 +00002018// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00002019// ArgExprs is optional - if it is present, the number of expressions
2020// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00002021ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00002022 ParsedType Receiver,
2023 Selector Sel,
2024 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002025 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor77328d12010-09-15 23:19:31 +00002026 SourceLocation RBracLoc,
2027 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002028 TypeSourceInfo *ReceiverTypeInfo;
2029 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2030 if (ReceiverType.isNull())
2031 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002032
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Douglas Gregor2725ca82010-04-21 19:57:20 +00002034 if (!ReceiverTypeInfo)
2035 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2036
2037 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00002038 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002039 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00002040}
2041
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002042ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2043 QualType ReceiverType,
2044 SourceLocation Loc,
2045 Selector Sel,
2046 ObjCMethodDecl *Method,
2047 MultiExprArg Args) {
2048 return BuildInstanceMessage(Receiver, ReceiverType,
2049 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2050 Sel, Method, Loc, Loc, Loc, Args,
2051 /*isImplicit=*/true);
2052}
2053
Douglas Gregor2725ca82010-04-21 19:57:20 +00002054/// \brief Build an Objective-C instance message expression.
2055///
2056/// This routine takes care of both normal instance messages and
2057/// instance messages to the superclass instance.
2058///
2059/// \param Receiver The expression that computes the object that will
2060/// receive this message. This may be empty, in which case we are
2061/// sending to the superclass instance and \p SuperLoc must be a valid
2062/// source location.
2063///
2064/// \param ReceiverType The (static) type of the object receiving the
2065/// message. When a \p Receiver expression is provided, this is the
2066/// same type as that expression. For a superclass instance send, this
2067/// is a pointer to the type of the superclass.
2068///
2069/// \param SuperLoc The location of the "super" keyword in a
2070/// superclass instance message.
2071///
2072/// \param Sel The selector to which the message is being sent.
2073///
Douglas Gregorf49bb082010-04-22 17:01:48 +00002074/// \param Method The method that this instance message is invoking, if
2075/// already known.
2076///
Douglas Gregor2725ca82010-04-21 19:57:20 +00002077/// \param LBracLoc The location of the opening square bracket ']'.
2078///
Douglas Gregor2725ca82010-04-21 19:57:20 +00002079/// \param RBrac The location of the closing square bracket ']'.
2080///
2081/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00002082ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002083 QualType ReceiverType,
2084 SourceLocation SuperLoc,
2085 Selector Sel,
2086 ObjCMethodDecl *Method,
2087 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002088 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002089 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002090 MultiExprArg ArgsIn,
2091 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00002092 // The location of the receiver.
2093 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2094
2095 if (LBracLoc.isInvalid()) {
2096 Diag(Loc, diag::err_missing_open_square_message_send)
2097 << FixItHint::CreateInsertion(Loc, "[");
2098 LBracLoc = Loc;
2099 }
2100
Douglas Gregor2725ca82010-04-21 19:57:20 +00002101 // If we have a receiver expression, perform appropriate promotions
2102 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00002103 if (Receiver) {
John McCall5acb0c92011-10-17 18:40:02 +00002104 if (Receiver->hasPlaceholderType()) {
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00002105 ExprResult Result;
2106 if (Receiver->getType() == Context.UnknownAnyTy)
2107 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2108 else
2109 Result = CheckPlaceholderExpr(Receiver);
2110 if (Result.isInvalid()) return ExprError();
2111 Receiver = Result.take();
John McCall5acb0c92011-10-17 18:40:02 +00002112 }
2113
Douglas Gregor92e986e2010-04-22 16:44:27 +00002114 if (Receiver->isTypeDependent()) {
2115 // If the receiver is type-dependent, we can't type-check anything
2116 // at this point. Build a dependent expression.
2117 unsigned NumArgs = ArgsIn.size();
2118 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2119 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2120 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00002121 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002122 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002123 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002124 RBracLoc, isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00002125 }
2126
Douglas Gregor2725ca82010-04-21 19:57:20 +00002127 // If necessary, apply function/array conversion to the receiver.
2128 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00002129 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2130 if (Result.isInvalid())
2131 return ExprError();
2132 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00002133 ReceiverType = Receiver->getType();
2134 }
2135
Douglas Gregorf49bb082010-04-22 17:01:48 +00002136 if (!Method) {
2137 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00002138 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002139 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00002140 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2141 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002142 SourceRange(LBracLoc, RBracLoc),
2143 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002144 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00002145 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002146 SourceRange(LBracLoc, RBracLoc),
2147 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002148 } else if (ReceiverType->isObjCClassType() ||
2149 ReceiverType->isObjCQualifiedClassType()) {
2150 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002151 // We allow sending a message to a qualified Class ("Class<foo>"), which
2152 // is ok as long as one of the protocols implements the selector (if not, warn).
2153 if (const ObjCObjectPointerType *QClassTy
2154 = ReceiverType->getAsObjCQualifiedClassType()) {
2155 // Search protocols for class methods.
2156 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2157 if (!Method) {
2158 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2159 // warn if instance method found for a Class message.
2160 if (Method) {
2161 Diag(Loc, diag::warn_instance_method_on_class_found)
2162 << Method->getSelector() << Sel;
Ted Kremenek3306ec12012-02-27 22:55:11 +00002163 Diag(Method->getLocation(), diag::note_method_declared_at)
2164 << Method->getDeclName();
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002165 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00002166 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002167 } else {
2168 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2169 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2170 // First check the public methods in the class interface.
2171 Method = ClassDecl->lookupClassMethod(Sel);
2172
2173 if (!Method)
2174 Method = LookupPrivateClassMethod(Sel, ClassDecl);
2175 }
2176 if (Method && DiagnoseUseOfDecl(Method, Loc))
2177 return ExprError();
2178 }
2179 if (!Method) {
2180 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00002181 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002182 Method = LookupFactoryMethodInGlobalPool(Sel,
2183 SourceRange(LBracLoc, RBracLoc),
2184 true);
2185 if (!Method) {
2186 // If no class (factory) method was found, check if an _instance_
2187 // method of the same name exists in the root class only.
2188 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002189 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002190 true);
2191 if (Method)
2192 if (const ObjCInterfaceDecl *ID =
2193 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2194 if (ID->getSuperClass())
2195 Diag(Loc, diag::warn_root_inst_method_not_found)
2196 << Sel << SourceRange(LBracLoc, RBracLoc);
2197 }
2198 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002199 }
2200 }
2201 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002202 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002203 ObjCInterfaceDecl* ClassDecl = 0;
2204
2205 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2206 // long as one of the protocols implements the selector (if not, warn).
2207 if (const ObjCObjectPointerType *QIdTy
2208 = ReceiverType->getAsObjCQualifiedIdType()) {
2209 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002210 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2211 if (!Method)
2212 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002213 } else if (const ObjCObjectPointerType *OCIType
2214 = ReceiverType->getAsObjCInterfacePointerType()) {
2215 // We allow sending a message to a pointer to an interface (an object).
2216 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00002217
Douglas Gregorb3029962011-11-14 22:10:01 +00002218 // Try to complete the type. Under ARC, this is a hard error from which
2219 // we don't try to recover.
2220 const ObjCInterfaceDecl *forwardClass = 0;
2221 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002222 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00002223 ? diag::err_arc_receiver_forward_instance
2224 : diag::warn_receiver_forward_instance,
2225 Receiver? Receiver->getSourceRange()
2226 : SourceRange(SuperLoc))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002227 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregorb3029962011-11-14 22:10:01 +00002228 return ExprError();
2229
2230 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00002231 Diag(Receiver ? Receiver->getLocStart()
2232 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00002233 Method = 0;
2234 } else {
2235 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCallf85e1932011-06-15 23:02:42 +00002236 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002237
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002238 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002239 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002240 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2241
Douglas Gregorf49bb082010-04-22 17:01:48 +00002242 if (!Method) {
2243 // If we have implementations in scope, check "private" methods.
2244 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
2245
David Blaikie4e4d0842012-03-11 07:00:24 +00002246 if (!Method && getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002247 Diag(Loc, diag::err_arc_may_not_respond)
2248 << OCIType->getPointeeType() << Sel;
2249 return ExprError();
2250 }
2251
Douglas Gregorc737acb2011-09-27 16:10:05 +00002252 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002253 // If we still haven't found a method, look in the global pool. This
2254 // behavior isn't very desirable, however we need it for GCC
2255 // compatibility. FIXME: should we deviate??
2256 if (OCIType->qual_empty()) {
2257 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002258 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002259 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002260 Diag(Loc, diag::warn_maynot_respond)
2261 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
2262 }
2263 }
2264 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002265 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00002266 return ExprError();
David Blaikie4e4d0842012-03-11 07:00:24 +00002267 } else if (!getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002268 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00002269 (ReceiverType->isPointerType() ||
2270 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002271 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00002272 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00002273 Diag(Loc, diag::warn_bad_receiver_type)
2274 << ReceiverType
2275 << Receiver->getSourceRange();
2276 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00002277 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002278 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00002279 else {
2280 // TODO: specialized warning on null receivers?
2281 bool IsNull = Receiver->isNullPointerConstant(Context,
2282 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00002283 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2284 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00002285 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002286 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00002287 } else {
John Wiegley429bb272011-04-08 18:41:53 +00002288 ExprResult ReceiverRes;
David Blaikie4e4d0842012-03-11 07:00:24 +00002289 if (getLangOpts().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00002290 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00002291 if (ReceiverRes.isUsable()) {
2292 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00002293 return BuildInstanceMessage(Receiver,
2294 ReceiverType,
2295 SuperLoc,
2296 Sel,
2297 Method,
2298 LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002299 SelectorLocs,
John Wiegley429bb272011-04-08 18:41:53 +00002300 RBracLoc,
2301 move(ArgsIn));
2302 } else {
2303 // Reject other random receiver types (e.g. structs).
2304 Diag(Loc, diag::err_bad_receiver_type)
2305 << ReceiverType << Receiver->getSourceRange();
2306 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00002307 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002308 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002309 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00002310 }
Mike Stump1eb44332009-09-09 15:08:12 +00002311
Douglas Gregor2725ca82010-04-21 19:57:20 +00002312 // Check the message arguments.
2313 unsigned NumArgs = ArgsIn.size();
2314 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2315 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00002316 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00002317 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2318 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00002319 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
2320 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00002321 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00002322 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00002323
Douglas Gregor483dd2f2011-01-11 03:23:19 +00002324 if (Method && !Method->getResultType()->isVoidType() &&
2325 RequireCompleteType(LBracLoc, Method->getResultType(),
2326 diag::err_illegal_message_expr_incomplete_type))
2327 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002328
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002329 SourceLocation SelLoc = SelectorLocs.front();
2330
John McCallf85e1932011-06-15 23:02:42 +00002331 // In ARC, forbid the user from sending messages to
2332 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002333 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002334 ObjCMethodFamily family =
2335 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2336 switch (family) {
2337 case OMF_init:
2338 if (Method)
2339 checkInitMethod(Method, ReceiverType);
2340
2341 case OMF_None:
2342 case OMF_alloc:
2343 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00002344 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00002345 case OMF_mutableCopy:
2346 case OMF_new:
2347 case OMF_self:
2348 break;
2349
2350 case OMF_dealloc:
2351 case OMF_retain:
2352 case OMF_release:
2353 case OMF_autorelease:
2354 case OMF_retainCount:
2355 Diag(Loc, diag::err_arc_illegal_explicit_message)
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002356 << Sel << SelLoc;
John McCallf85e1932011-06-15 23:02:42 +00002357 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002358
2359 case OMF_performSelector:
2360 if (Method && NumArgs >= 1) {
2361 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2362 Selector ArgSel = SelExp->getSelector();
2363 ObjCMethodDecl *SelMethod =
2364 LookupInstanceMethodInGlobalPool(ArgSel,
2365 SelExp->getSourceRange());
2366 if (!SelMethod)
2367 SelMethod =
2368 LookupFactoryMethodInGlobalPool(ArgSel,
2369 SelExp->getSourceRange());
2370 if (SelMethod) {
2371 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2372 switch (SelFamily) {
2373 case OMF_alloc:
2374 case OMF_copy:
2375 case OMF_mutableCopy:
2376 case OMF_new:
2377 case OMF_self:
2378 case OMF_init:
2379 // Issue error, unless ns_returns_not_retained.
2380 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2381 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002382 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002383 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002384 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2385 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002386 }
2387 break;
2388 default:
2389 // +0 call. OK. unless ns_returns_retained.
2390 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2391 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002392 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002393 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002394 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2395 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002396 }
2397 break;
2398 }
2399 }
2400 } else {
2401 // error (may leak).
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002402 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002403 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2404 }
2405 }
2406 break;
John McCallf85e1932011-06-15 23:02:42 +00002407 }
2408 }
2409
Douglas Gregor2725ca82010-04-21 19:57:20 +00002410 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00002411 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00002412 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00002413 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002414 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002415 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002416 makeArrayRef(Args, NumArgs), RBracLoc,
2417 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002418 else {
John McCallf89e55a2010-11-18 06:31:45 +00002419 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002420 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002421 makeArrayRef(Args, NumArgs), RBracLoc,
2422 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002423 if (!isImplicit)
2424 checkCocoaAPI(*this, Result);
2425 }
John McCallf85e1932011-06-15 23:02:42 +00002426
David Blaikie4e4d0842012-03-11 07:00:24 +00002427 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian98795562012-04-19 23:49:39 +00002428 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian878f8502012-04-04 20:05:25 +00002429
John McCallf85e1932011-06-15 23:02:42 +00002430 // In ARC, annotate delegate init calls.
2431 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00002432 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00002433 // Only consider init calls *directly* in init implementations,
2434 // not within blocks.
2435 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2436 if (method && method->getMethodFamily() == OMF_init) {
2437 // The implicit assignment to self means we also don't want to
2438 // consume the result.
2439 Result->setDelegateInitCall(true);
2440 return Owned(Result);
2441 }
2442 }
2443
2444 // In ARC, check for message sends which are likely to introduce
2445 // retain cycles.
2446 checkRetainCycles(Result);
2447 }
2448
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002449 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00002450}
2451
2452// ActOnInstanceMessage - used for both unary and keyword messages.
2453// ArgExprs is optional - if it is present, the number of expressions
2454// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00002455ExprResult Sema::ActOnInstanceMessage(Scope *S,
2456 Expr *Receiver,
2457 Selector Sel,
2458 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002459 ArrayRef<SourceLocation> SelectorLocs,
John McCall60d7b3a2010-08-24 06:29:42 +00002460 SourceLocation RBracLoc,
2461 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002462 if (!Receiver)
2463 return ExprError();
2464
John McCall9ae2f072010-08-23 23:25:46 +00002465 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00002466 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002467 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00002468}
Chris Lattnereca7be62008-04-07 05:30:13 +00002469
John McCallf85e1932011-06-15 23:02:42 +00002470enum ARCConversionTypeClass {
John McCall2cf031d2011-10-01 01:01:08 +00002471 /// int, void, struct A
John McCallf85e1932011-06-15 23:02:42 +00002472 ACTC_none,
John McCall2cf031d2011-10-01 01:01:08 +00002473
2474 /// id, void (^)()
John McCallf85e1932011-06-15 23:02:42 +00002475 ACTC_retainable,
John McCall2cf031d2011-10-01 01:01:08 +00002476
2477 /// id*, id***, void (^*)(),
2478 ACTC_indirectRetainable,
2479
2480 /// void* might be a normal C type, or it might a CF type.
2481 ACTC_voidPtr,
2482
2483 /// struct A*
2484 ACTC_coreFoundation
John McCallf85e1932011-06-15 23:02:42 +00002485};
John McCall2cf031d2011-10-01 01:01:08 +00002486static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2487 return (ACTC == ACTC_retainable ||
2488 ACTC == ACTC_coreFoundation ||
2489 ACTC == ACTC_voidPtr);
2490}
2491static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2492 return ACTC == ACTC_none ||
2493 ACTC == ACTC_voidPtr ||
2494 ACTC == ACTC_coreFoundation;
2495}
2496
John McCallf85e1932011-06-15 23:02:42 +00002497static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCall2cf031d2011-10-01 01:01:08 +00002498 bool isIndirect = false;
John McCallf85e1932011-06-15 23:02:42 +00002499
2500 // Ignore an outermost reference type.
John McCall2cf031d2011-10-01 01:01:08 +00002501 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCallf85e1932011-06-15 23:02:42 +00002502 type = ref->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002503 isIndirect = true;
2504 }
John McCallf85e1932011-06-15 23:02:42 +00002505
2506 // Drill through pointers and arrays recursively.
2507 while (true) {
2508 if (const PointerType *ptr = type->getAs<PointerType>()) {
2509 type = ptr->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002510
2511 // The first level of pointer may be the innermost pointer on a CF type.
2512 if (!isIndirect) {
2513 if (type->isVoidType()) return ACTC_voidPtr;
2514 if (type->isRecordType()) return ACTC_coreFoundation;
2515 }
John McCallf85e1932011-06-15 23:02:42 +00002516 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2517 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2518 } else {
2519 break;
2520 }
John McCall2cf031d2011-10-01 01:01:08 +00002521 isIndirect = true;
John McCallf85e1932011-06-15 23:02:42 +00002522 }
2523
John McCall2cf031d2011-10-01 01:01:08 +00002524 if (isIndirect) {
2525 if (type->isObjCARCBridgableType())
2526 return ACTC_indirectRetainable;
2527 return ACTC_none;
2528 }
2529
2530 if (type->isObjCARCBridgableType())
2531 return ACTC_retainable;
2532
2533 return ACTC_none;
John McCallf85e1932011-06-15 23:02:42 +00002534}
2535
2536namespace {
John McCall2cf031d2011-10-01 01:01:08 +00002537 /// A result from the cast checker.
2538 enum ACCResult {
2539 /// Cannot be casted.
2540 ACC_invalid,
2541
2542 /// Can be safely retained or not retained.
2543 ACC_bottom,
2544
2545 /// Can be casted at +0.
2546 ACC_plusZero,
2547
2548 /// Can be casted at +1.
2549 ACC_plusOne
2550 };
2551 ACCResult merge(ACCResult left, ACCResult right) {
2552 if (left == right) return left;
2553 if (left == ACC_bottom) return right;
2554 if (right == ACC_bottom) return left;
2555 return ACC_invalid;
2556 }
2557
2558 /// A checker which white-lists certain expressions whose conversion
2559 /// to or from retainable type would otherwise be forbidden in ARC.
2560 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2561 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2562
John McCallf85e1932011-06-15 23:02:42 +00002563 ASTContext &Context;
John McCall2cf031d2011-10-01 01:01:08 +00002564 ARCConversionTypeClass SourceClass;
2565 ARCConversionTypeClass TargetClass;
2566
2567 static bool isCFType(QualType type) {
2568 // Someday this can use ns_bridged. For now, it has to do this.
2569 return type->isCARCBridgableType();
John McCallf85e1932011-06-15 23:02:42 +00002570 }
John McCall2cf031d2011-10-01 01:01:08 +00002571
2572 public:
2573 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2574 ARCConversionTypeClass target)
2575 : Context(Context), SourceClass(source), TargetClass(target) {}
2576
2577 using super::Visit;
2578 ACCResult Visit(Expr *e) {
2579 return super::Visit(e->IgnoreParens());
2580 }
2581
2582 ACCResult VisitStmt(Stmt *s) {
2583 return ACC_invalid;
2584 }
2585
2586 /// Null pointer constants can be casted however you please.
2587 ACCResult VisitExpr(Expr *e) {
2588 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2589 return ACC_bottom;
2590 return ACC_invalid;
2591 }
2592
2593 /// Objective-C string literals can be safely casted.
2594 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2595 // If we're casting to any retainable type, go ahead. Global
2596 // strings are immune to retains, so this is bottom.
2597 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2598
2599 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002600 }
2601
John McCall2cf031d2011-10-01 01:01:08 +00002602 /// Look through certain implicit and explicit casts.
2603 ACCResult VisitCastExpr(CastExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002604 switch (e->getCastKind()) {
2605 case CK_NullToPointer:
John McCall2cf031d2011-10-01 01:01:08 +00002606 return ACC_bottom;
2607
John McCallf85e1932011-06-15 23:02:42 +00002608 case CK_NoOp:
2609 case CK_LValueToRValue:
2610 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002611 case CK_CPointerToObjCPointerCast:
2612 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002613 case CK_AnyPointerToBlockPointerCast:
2614 return Visit(e->getSubExpr());
John McCall2cf031d2011-10-01 01:01:08 +00002615
John McCallf85e1932011-06-15 23:02:42 +00002616 default:
John McCall2cf031d2011-10-01 01:01:08 +00002617 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002618 }
2619 }
John McCall2cf031d2011-10-01 01:01:08 +00002620
2621 /// Look through unary extension.
2622 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002623 return Visit(e->getSubExpr());
2624 }
John McCall2cf031d2011-10-01 01:01:08 +00002625
2626 /// Ignore the LHS of a comma operator.
2627 ACCResult VisitBinComma(BinaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002628 return Visit(e->getRHS());
2629 }
John McCall2cf031d2011-10-01 01:01:08 +00002630
2631 /// Conditional operators are okay if both sides are okay.
2632 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2633 ACCResult left = Visit(e->getTrueExpr());
2634 if (left == ACC_invalid) return ACC_invalid;
2635 return merge(left, Visit(e->getFalseExpr()));
John McCallf85e1932011-06-15 23:02:42 +00002636 }
John McCall2cf031d2011-10-01 01:01:08 +00002637
John McCall4b9c2d22011-11-06 09:01:30 +00002638 /// Look through pseudo-objects.
2639 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2640 // If we're getting here, we should always have a result.
2641 return Visit(e->getResultExpr());
2642 }
2643
John McCall2cf031d2011-10-01 01:01:08 +00002644 /// Statement expressions are okay if their result expression is okay.
2645 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002646 return Visit(e->getSubStmt()->body_back());
2647 }
John McCallf85e1932011-06-15 23:02:42 +00002648
John McCall2cf031d2011-10-01 01:01:08 +00002649 /// Some declaration references are okay.
2650 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2651 // References to global constants from system headers are okay.
2652 // These are things like 'kCFStringTransformToLatin'. They are
2653 // can also be assumed to be immune to retains.
2654 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2655 if (isAnyRetainable(TargetClass) &&
2656 isAnyRetainable(SourceClass) &&
2657 var &&
2658 var->getStorageClass() == SC_Extern &&
2659 var->getType().isConstQualified() &&
2660 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2661 return ACC_bottom;
2662 }
2663
2664 // Nothing else.
2665 return ACC_invalid;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00002666 }
John McCall2cf031d2011-10-01 01:01:08 +00002667
2668 /// Some calls are okay.
2669 ACCResult VisitCallExpr(CallExpr *e) {
2670 if (FunctionDecl *fn = e->getDirectCallee())
2671 if (ACCResult result = checkCallToFunction(fn))
2672 return result;
2673
2674 return super::VisitCallExpr(e);
2675 }
2676
2677 ACCResult checkCallToFunction(FunctionDecl *fn) {
2678 // Require a CF*Ref return type.
2679 if (!isCFType(fn->getResultType()))
2680 return ACC_invalid;
2681
2682 if (!isAnyRetainable(TargetClass))
2683 return ACC_invalid;
2684
2685 // Honor an explicit 'not retained' attribute.
2686 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2687 return ACC_plusZero;
2688
2689 // Honor an explicit 'retained' attribute, except that for
2690 // now we're not going to permit implicit handling of +1 results,
2691 // because it's a bit frightening.
2692 if (fn->hasAttr<CFReturnsRetainedAttr>())
2693 return ACC_invalid; // ACC_plusOne if we start accepting this
2694
2695 // Recognize this specific builtin function, which is used by CFSTR.
2696 unsigned builtinID = fn->getBuiltinID();
2697 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2698 return ACC_bottom;
2699
2700 // Otherwise, don't do anything implicit with an unaudited function.
2701 if (!fn->hasAttr<CFAuditedTransferAttr>())
2702 return ACC_invalid;
2703
2704 // Otherwise, it's +0 unless it follows the create convention.
2705 if (ento::coreFoundation::followsCreateRule(fn))
2706 return ACC_invalid; // ACC_plusOne if we start accepting this
2707
2708 return ACC_plusZero;
2709 }
2710
2711 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2712 return checkCallToMethod(e->getMethodDecl());
2713 }
2714
2715 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2716 ObjCMethodDecl *method;
2717 if (e->isExplicitProperty())
2718 method = e->getExplicitProperty()->getGetterMethodDecl();
2719 else
2720 method = e->getImplicitPropertyGetter();
2721 return checkCallToMethod(method);
2722 }
2723
2724 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2725 if (!method) return ACC_invalid;
2726
2727 // Check for message sends to functions returning CF types. We
2728 // just obey the Cocoa conventions with these, even though the
2729 // return type is CF.
2730 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2731 return ACC_invalid;
2732
2733 // If the method is explicitly marked not-retained, it's +0.
2734 if (method->hasAttr<CFReturnsNotRetainedAttr>())
2735 return ACC_plusZero;
2736
2737 // If the method is explicitly marked as returning retained, or its
2738 // selector follows a +1 Cocoa convention, treat it as +1.
2739 if (method->hasAttr<CFReturnsRetainedAttr>())
2740 return ACC_plusOne;
2741
2742 switch (method->getSelector().getMethodFamily()) {
2743 case OMF_alloc:
2744 case OMF_copy:
2745 case OMF_mutableCopy:
2746 case OMF_new:
2747 return ACC_plusOne;
2748
2749 default:
2750 // Otherwise, treat it as +0.
2751 return ACC_plusZero;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00002752 }
2753 }
John McCall2cf031d2011-10-01 01:01:08 +00002754 };
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00002755}
2756
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002757static bool
2758KnownName(Sema &S, const char *name) {
2759 LookupResult R(S, &S.Context.Idents.get(name), SourceLocation(),
2760 Sema::LookupOrdinaryName);
2761 return S.LookupName(R, S.TUScope, false);
2762}
2763
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002764static void addFixitForObjCARCConversion(Sema &S,
2765 DiagnosticBuilder &DiagB,
2766 Sema::CheckedConversionKind CCK,
2767 SourceLocation afterLParen,
2768 QualType castType,
2769 Expr *castExpr,
2770 const char *bridgeKeyword,
2771 const char *CFBridgeName) {
2772 // We handle C-style and implicit casts here.
2773 switch (CCK) {
2774 case Sema::CCK_ImplicitConversion:
2775 case Sema::CCK_CStyleCast:
2776 break;
2777 case Sema::CCK_FunctionalCast:
2778 case Sema::CCK_OtherCast:
2779 return;
2780 }
2781
2782 if (CFBridgeName) {
2783 Expr *castedE = castExpr;
2784 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2785 castedE = CCE->getSubExpr();
2786 castedE = castedE->IgnoreImpCasts();
2787 SourceRange range = castedE->getSourceRange();
2788 if (isa<ParenExpr>(castedE)) {
2789 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2790 CFBridgeName));
2791 } else {
2792 std::string namePlusParen = CFBridgeName;
2793 namePlusParen += "(";
2794 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2795 namePlusParen));
2796 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2797 S.PP.getLocForEndOfToken(range.getEnd()),
2798 ")"));
2799 }
2800 return;
2801 }
2802
2803 if (CCK == Sema::CCK_CStyleCast) {
2804 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
2805 } else {
2806 std::string castCode = "(";
2807 castCode += bridgeKeyword;
2808 castCode += castType.getAsString();
2809 castCode += ")";
2810 Expr *castedE = castExpr->IgnoreImpCasts();
2811 SourceRange range = castedE->getSourceRange();
2812 if (isa<ParenExpr>(castedE)) {
2813 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2814 castCode));
2815 } else {
2816 castCode += "(";
2817 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2818 castCode));
2819 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2820 S.PP.getLocForEndOfToken(range.getEnd()),
2821 ")"));
2822 }
2823 }
2824}
2825
John McCall5acb0c92011-10-17 18:40:02 +00002826static void
2827diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
2828 QualType castType, ARCConversionTypeClass castACTC,
2829 Expr *castExpr, ARCConversionTypeClass exprACTC,
2830 Sema::CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00002831 SourceLocation loc =
John McCall2cf031d2011-10-01 01:01:08 +00002832 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00002833
John McCall5acb0c92011-10-17 18:40:02 +00002834 if (S.makeUnavailableInSystemHeader(loc,
John McCall2cf031d2011-10-01 01:01:08 +00002835 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCallf85e1932011-06-15 23:02:42 +00002836 return;
John McCall5acb0c92011-10-17 18:40:02 +00002837
2838 QualType castExprType = castExpr->getType();
John McCallf85e1932011-06-15 23:02:42 +00002839
John McCall71c482c2011-06-17 06:50:50 +00002840 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00002841 switch (exprACTC) {
John McCall2cf031d2011-10-01 01:01:08 +00002842 case ACTC_none:
2843 case ACTC_coreFoundation:
2844 case ACTC_voidPtr:
2845 srcKind = (castExprType->isPointerType() ? 1 : 0);
2846 break;
2847 case ACTC_retainable:
2848 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
2849 break;
2850 case ACTC_indirectRetainable:
2851 srcKind = 4;
2852 break;
John McCallf85e1932011-06-15 23:02:42 +00002853 }
2854
John McCall5acb0c92011-10-17 18:40:02 +00002855 // Check whether this could be fixed with a bridge cast.
2856 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
2857 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCallf85e1932011-06-15 23:02:42 +00002858
John McCall5acb0c92011-10-17 18:40:02 +00002859 // Bridge from an ARC type to a CF type.
2860 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002861
John McCall5acb0c92011-10-17 18:40:02 +00002862 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2863 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2864 << 2 // of C pointer type
2865 << castExprType
2866 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
2867 << castType
2868 << castRange
2869 << castExpr->getSourceRange();
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002870 bool br = KnownName(S, "CFBridgingRelease");
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002871 {
2872 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2873 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2874 castType, castExpr, "__bridge ", 0);
2875 }
2876 {
2877 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_transfer)
2878 << castExprType << br;
2879 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2880 castType, castExpr, "__bridge_transfer ",
2881 br ? "CFBridgingRelease" : 0);
2882 }
John McCall5acb0c92011-10-17 18:40:02 +00002883
2884 return;
2885 }
2886
2887 // Bridge from a CF type to an ARC type.
2888 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002889 bool br = KnownName(S, "CFBridgingRetain");
John McCall5acb0c92011-10-17 18:40:02 +00002890 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2891 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2892 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
2893 << castExprType
2894 << 2 // to C pointer type
2895 << castType
2896 << castRange
2897 << castExpr->getSourceRange();
2898
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002899 {
2900 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2901 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2902 castType, castExpr, "__bridge ", 0);
2903 }
2904 {
2905 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_retained)
2906 << castType << br;
2907 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2908 castType, castExpr, "__bridge_retained ",
2909 br ? "CFBridgingRetain" : 0);
2910 }
John McCall5acb0c92011-10-17 18:40:02 +00002911
2912 return;
John McCallf85e1932011-06-15 23:02:42 +00002913 }
2914
John McCall5acb0c92011-10-17 18:40:02 +00002915 S.Diag(loc, diag::err_arc_mismatched_cast)
2916 << (CCK != Sema::CCK_ImplicitConversion)
2917 << srcKind << castExprType << castType
John McCallf85e1932011-06-15 23:02:42 +00002918 << castRange << castExpr->getSourceRange();
2919}
2920
John McCall5acb0c92011-10-17 18:40:02 +00002921Sema::ARCConversionResult
2922Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
2923 Expr *&castExpr, CheckedConversionKind CCK) {
2924 QualType castExprType = castExpr->getType();
2925
2926 // For the purposes of the classification, we assume reference types
2927 // will bind to temporaries.
2928 QualType effCastType = castType;
2929 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
2930 effCastType = ref->getPointeeType();
2931
2932 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
2933 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002934 if (exprACTC == castACTC) {
2935 // check for viablity and report error if casting an rvalue to a
2936 // life-time qualifier.
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002937 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002938 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002939 (castType != castExprType)) {
2940 const Type *DT = castType.getTypePtr();
2941 QualType QDT = castType;
2942 // We desugar some types but not others. We ignore those
2943 // that cannot happen in a cast; i.e. auto, and those which
2944 // should not be de-sugared; i.e typedef.
2945 if (const ParenType *PT = dyn_cast<ParenType>(DT))
2946 QDT = PT->desugar();
2947 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
2948 QDT = TP->desugar();
2949 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
2950 QDT = AT->desugar();
2951 if (QDT != castType &&
2952 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
2953 SourceLocation loc =
2954 (castRange.isValid() ? castRange.getBegin()
2955 : castExpr->getExprLoc());
2956 Diag(loc, diag::err_arc_nolifetime_behavior);
2957 }
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002958 }
2959 return ACR_okay;
2960 }
2961
John McCall5acb0c92011-10-17 18:40:02 +00002962 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
2963
2964 // Allow all of these types to be cast to integer types (but not
2965 // vice-versa).
2966 if (castACTC == ACTC_none && castType->isIntegralType(Context))
2967 return ACR_okay;
2968
2969 // Allow casts between pointers to lifetime types (e.g., __strong id*)
2970 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
2971 // must be explicit.
2972 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
2973 return ACR_okay;
2974 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
2975 CCK != CCK_ImplicitConversion)
2976 return ACR_okay;
2977
2978 switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
2979 // For invalid casts, fall through.
2980 case ACC_invalid:
2981 break;
2982
2983 // Do nothing for both bottom and +0.
2984 case ACC_bottom:
2985 case ACC_plusZero:
2986 return ACR_okay;
2987
2988 // If the result is +1, consume it here.
2989 case ACC_plusOne:
2990 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
2991 CK_ARCConsumeObject, castExpr,
2992 0, VK_RValue);
2993 ExprNeedsCleanups = true;
2994 return ACR_okay;
2995 }
2996
2997 // If this is a non-implicit cast from id or block type to a
2998 // CoreFoundation type, delay complaining in case the cast is used
2999 // in an acceptable context.
3000 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
3001 CCK != CCK_ImplicitConversion)
3002 return ACR_unbridged;
3003
3004 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3005 castExpr, exprACTC, CCK);
3006 return ACR_okay;
3007}
3008
3009/// Given that we saw an expression with the ARCUnbridgedCastTy
3010/// placeholder type, complain bitterly.
3011void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3012 // We expect the spurious ImplicitCastExpr to already have been stripped.
3013 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3014 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3015
3016 SourceRange castRange;
3017 QualType castType;
3018 CheckedConversionKind CCK;
3019
3020 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3021 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3022 castType = cast->getTypeAsWritten();
3023 CCK = CCK_CStyleCast;
3024 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3025 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3026 castType = cast->getTypeAsWritten();
3027 CCK = CCK_OtherCast;
3028 } else {
3029 castType = cast->getType();
3030 CCK = CCK_ImplicitConversion;
3031 }
3032
3033 ARCConversionTypeClass castACTC =
3034 classifyTypeForARCConversion(castType.getNonReferenceType());
3035
3036 Expr *castExpr = realCast->getSubExpr();
3037 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3038
3039 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3040 castExpr, ACTC_retainable, CCK);
3041}
3042
3043/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3044/// type, remove the placeholder cast.
3045Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3046 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3047
3048 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3049 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3050 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3051 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3052 assert(uo->getOpcode() == UO_Extension);
3053 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3054 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3055 sub->getValueKind(), sub->getObjectKind(),
3056 uo->getOperatorLoc());
3057 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3058 assert(!gse->isResultDependent());
3059
3060 unsigned n = gse->getNumAssocs();
3061 SmallVector<Expr*, 4> subExprs(n);
3062 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3063 for (unsigned i = 0; i != n; ++i) {
3064 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3065 Expr *sub = gse->getAssocExpr(i);
3066 if (i == gse->getResultIndex())
3067 sub = stripARCUnbridgedCast(sub);
3068 subExprs[i] = sub;
3069 }
3070
3071 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3072 gse->getControllingExpr(),
3073 subTypes.data(), subExprs.data(),
3074 n, gse->getDefaultLoc(),
3075 gse->getRParenLoc(),
3076 gse->containsUnexpandedParameterPack(),
3077 gse->getResultIndex());
3078 } else {
3079 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3080 return cast<ImplicitCastExpr>(e)->getSubExpr();
3081 }
3082}
3083
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00003084bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3085 QualType exprType) {
3086 QualType canCastType =
3087 Context.getCanonicalType(castType).getUnqualifiedType();
3088 QualType canExprType =
3089 Context.getCanonicalType(exprType).getUnqualifiedType();
3090 if (isa<ObjCObjectPointerType>(canCastType) &&
3091 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3092 canExprType->isObjCObjectPointerType()) {
3093 if (const ObjCObjectPointerType *ObjT =
3094 canExprType->getAs<ObjCObjectPointerType>())
3095 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
3096 return false;
3097 }
3098 return true;
3099}
3100
John McCall7e5e5f42011-07-07 06:58:02 +00003101/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3102static Expr *maybeUndoReclaimObject(Expr *e) {
3103 // For now, we just undo operands that are *immediately* reclaim
3104 // expressions, which prevents the vast majority of potential
3105 // problems here. To catch them all, we'd need to rebuild arbitrary
3106 // value-propagating subexpressions --- we can't reliably rebuild
3107 // in-place because of expression sharing.
3108 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00003109 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00003110 return ice->getSubExpr();
3111
3112 return e;
3113}
3114
John McCallf85e1932011-06-15 23:02:42 +00003115ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3116 ObjCBridgeCastKind Kind,
3117 SourceLocation BridgeKeywordLoc,
3118 TypeSourceInfo *TSInfo,
3119 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00003120 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3121 if (SubResult.isInvalid()) return ExprError();
3122 SubExpr = SubResult.take();
3123
John McCallf85e1932011-06-15 23:02:42 +00003124 QualType T = TSInfo->getType();
3125 QualType FromType = SubExpr->getType();
3126
John McCall1d9b3b22011-09-09 05:25:32 +00003127 CastKind CK;
3128
John McCallf85e1932011-06-15 23:02:42 +00003129 bool MustConsume = false;
3130 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3131 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00003132 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00003133 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3134 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00003135 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3136 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00003137 switch (Kind) {
3138 case OBC_Bridge:
3139 break;
3140
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003141 case OBC_BridgeRetained: {
3142 bool br = KnownName(*this, "CFBridgingRelease");
John McCallf85e1932011-06-15 23:02:42 +00003143 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3144 << 2
3145 << FromType
3146 << (T->isBlockPointerType()? 1 : 0)
3147 << T
3148 << SubExpr->getSourceRange()
3149 << Kind;
3150 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3151 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3152 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003153 << FromType << br
John McCallf85e1932011-06-15 23:02:42 +00003154 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003155 br ? "CFBridgingRelease "
3156 : "__bridge_transfer ");
John McCallf85e1932011-06-15 23:02:42 +00003157
3158 Kind = OBC_Bridge;
3159 break;
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003160 }
John McCallf85e1932011-06-15 23:02:42 +00003161
3162 case OBC_BridgeTransfer:
3163 // We must consume the Objective-C object produced by the cast.
3164 MustConsume = true;
3165 break;
3166 }
3167 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3168 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00003169 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00003170 switch (Kind) {
3171 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00003172 // Reclaiming a value that's going to be __bridge-casted to CF
3173 // is very dangerous, so we don't do it.
3174 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00003175 break;
3176
3177 case OBC_BridgeRetained:
3178 // Produce the object before casting it.
3179 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00003180 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00003181 SubExpr, 0, VK_RValue);
3182 break;
3183
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003184 case OBC_BridgeTransfer: {
3185 bool br = KnownName(*this, "CFBridgingRetain");
John McCallf85e1932011-06-15 23:02:42 +00003186 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3187 << (FromType->isBlockPointerType()? 1 : 0)
3188 << FromType
3189 << 2
3190 << T
3191 << SubExpr->getSourceRange()
3192 << Kind;
3193
3194 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3195 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3196 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003197 << T << br
3198 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3199 br ? "CFBridgingRetain " : "__bridge_retained");
John McCallf85e1932011-06-15 23:02:42 +00003200
3201 Kind = OBC_Bridge;
3202 break;
3203 }
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003204 }
John McCallf85e1932011-06-15 23:02:42 +00003205 } else {
3206 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3207 << FromType << T << Kind
3208 << SubExpr->getSourceRange()
3209 << TSInfo->getTypeLoc().getSourceRange();
3210 return ExprError();
3211 }
3212
John McCall1d9b3b22011-09-09 05:25:32 +00003213 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00003214 BridgeKeywordLoc,
3215 TSInfo, SubExpr);
3216
3217 if (MustConsume) {
3218 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00003219 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00003220 0, VK_RValue);
3221 }
3222
3223 return Result;
3224}
3225
3226ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3227 SourceLocation LParenLoc,
3228 ObjCBridgeCastKind Kind,
3229 SourceLocation BridgeKeywordLoc,
3230 ParsedType Type,
3231 SourceLocation RParenLoc,
3232 Expr *SubExpr) {
3233 TypeSourceInfo *TSInfo = 0;
3234 QualType T = GetTypeFromParser(Type, &TSInfo);
3235 if (!TSInfo)
3236 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3237 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3238 SubExpr);
3239}