blob: f6c49fa2f9d9aa90f0c47911f4e33382f534075e [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
Jordy Rosec8521fa2012-05-12 17:32:44 +0000143/// \brief Emits an error if the given method does not exist, or if the return
144/// type is not an Objective-C object.
145static bool validateBoxingMethod(Sema &S, SourceLocation Loc,
146 const ObjCInterfaceDecl *Class,
147 Selector Sel, const ObjCMethodDecl *Method) {
148 if (!Method) {
149 // FIXME: Is there a better way to avoid quotes than using getName()?
150 S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName();
151 return false;
152 }
153
154 // Make sure the return type is reasonable.
155 QualType ReturnType = Method->getResultType();
156 if (!ReturnType->isObjCObjectPointerType()) {
157 S.Diag(Loc, diag::err_objc_literal_method_sig)
158 << Sel;
159 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
160 << ReturnType;
161 return false;
162 }
163
164 return true;
165}
166
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000167/// \brief Retrieve the NSNumber factory method that should be used to create
168/// an Objective-C literal for the given type.
169static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beardeb382ec2012-04-19 00:25:12 +0000170 QualType NumberType,
171 bool isLiteral = false,
172 SourceRange R = SourceRange()) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000173 llvm::Optional<NSAPI::NSNumberLiteralMethodKind> Kind
Patrick Beardeb382ec2012-04-19 00:25:12 +0000174 = S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000175
176 if (!Kind) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000177 if (isLiteral) {
178 S.Diag(Loc, diag::err_invalid_nsnumber_type)
179 << NumberType << R;
180 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000181 return 0;
182 }
Patrick Beardeb382ec2012-04-19 00:25:12 +0000183
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000184 // If we already looked up this method, we're done.
185 if (S.NSNumberLiteralMethods[*Kind])
186 return S.NSNumberLiteralMethods[*Kind];
187
188 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
189 /*Instance=*/false);
190
Patrick Beardeb382ec2012-04-19 00:25:12 +0000191 ASTContext &CX = S.Context;
192
193 // Look up the NSNumber class, if we haven't done so already. It's cached
194 // in the Sema instance.
195 if (!S.NSNumberDecl) {
196 IdentifierInfo *NSNumberId = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
197 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
198 Loc, Sema::LookupOrdinaryName);
199 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
200 if (!S.NSNumberDecl) {
201 if (S.getLangOpts().DebuggerObjCLiteral) {
202 // Create a stub definition of NSNumber.
203 S.NSNumberDecl = ObjCInterfaceDecl::Create (CX,
204 CX.getTranslationUnitDecl(),
205 SourceLocation(), NSNumberId,
206 0, SourceLocation());
207 } else {
208 // Otherwise, require a declaration of NSNumber.
209 S.Diag(Loc, diag::err_undeclared_nsnumber);
210 return 0;
211 }
212 } else if (!S.NSNumberDecl->hasDefinition()) {
213 S.Diag(Loc, diag::err_undeclared_nsnumber);
214 return 0;
215 }
216
217 // generate the pointer to NSNumber type.
218 S.NSNumberPointer = CX.getObjCObjectPointerType(CX.getObjCInterfaceType(S.NSNumberDecl));
219 }
220
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000221 // Look for the appropriate method within NSNumber.
222 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);;
David Blaikie4e4d0842012-03-11 07:00:24 +0000223 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000224 // create a stub definition this NSNumber factory method.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000225 TypeSourceInfo *ResultTInfo = 0;
Patrick Beardeb382ec2012-04-19 00:25:12 +0000226 Method = ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
227 S.NSNumberPointer, ResultTInfo, S.NSNumberDecl,
228 /*isInstance=*/false, /*isVariadic=*/false,
229 /*isSynthesized=*/false,
230 /*isImplicitlyDeclared=*/true,
231 /*isDefined=*/false, ObjCMethodDecl::Required,
232 /*HasRelatedResultType=*/false);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000233 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
234 SourceLocation(), SourceLocation(),
Patrick Beardeb382ec2012-04-19 00:25:12 +0000235 &CX.Idents.get("value"),
236 NumberType, /*TInfo=*/0, SC_None, SC_None, 0);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000237 Method->setMethodParams(S.Context, value, ArrayRef<SourceLocation>());
238 }
239
Jordy Rosec8521fa2012-05-12 17:32:44 +0000240 if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method))
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000241 return 0;
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000242
243 // Note: if the parameter type is out-of-line, we'll catch it later in the
244 // implicit conversion.
245
246 S.NSNumberLiteralMethods[*Kind] = Method;
247 return Method;
248}
249
Patrick Beardeb382ec2012-04-19 00:25:12 +0000250/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
251/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000252ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000253 // Determine the type of the literal.
254 QualType NumberType = Number->getType();
255 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
256 // In C, character literals have type 'int'. That's not the type we want
257 // to use to determine the Objective-c literal kind.
258 switch (Char->getKind()) {
259 case CharacterLiteral::Ascii:
260 NumberType = Context.CharTy;
261 break;
262
263 case CharacterLiteral::Wide:
264 NumberType = Context.getWCharType();
265 break;
266
267 case CharacterLiteral::UTF16:
268 NumberType = Context.Char16Ty;
269 break;
270
271 case CharacterLiteral::UTF32:
272 NumberType = Context.Char32Ty;
273 break;
274 }
275 }
276
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000277 // Look for the appropriate method within NSNumber.
278 // Construct the literal.
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000279 SourceRange NR(Number->getSourceRange());
Patrick Beardeb382ec2012-04-19 00:25:12 +0000280 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000281 true, NR);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000282 if (!Method)
283 return ExprError();
284
285 // Convert the number to the type that the parameter expects.
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000286 ParmVarDecl *ParamDecl = Method->param_begin()[0];
287 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
288 ParamDecl);
289 ExprResult ConvertedNumber = PerformCopyInitialization(Entity,
290 SourceLocation(),
291 Owned(Number));
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000292 if (ConvertedNumber.isInvalid())
293 return ExprError();
294 Number = ConvertedNumber.get();
295
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000296 // Use the effective source range of the literal, including the leading '@'.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000297 return MaybeBindToTemporary(
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000298 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method,
299 SourceRange(AtLoc, NR.getEnd())));
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000300}
301
302ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
303 SourceLocation ValueLoc,
304 bool Value) {
305 ExprResult Inner;
David Blaikie4e4d0842012-03-11 07:00:24 +0000306 if (getLangOpts().CPlusPlus) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000307 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
308 } else {
309 // C doesn't actually have a way to represent literal values of type
310 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
311 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
312 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
313 CK_IntegralToBoolean);
314 }
315
316 return BuildObjCNumericLiteral(AtLoc, Inner.get());
317}
318
319/// \brief Check that the given expression is a valid element of an Objective-C
320/// collection literal.
321static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
322 QualType T) {
323 // If the expression is type-dependent, there's nothing for us to do.
324 if (Element->isTypeDependent())
325 return Element;
326
327 ExprResult Result = S.CheckPlaceholderExpr(Element);
328 if (Result.isInvalid())
329 return ExprError();
330 Element = Result.get();
331
332 // In C++, check for an implicit conversion to an Objective-C object pointer
333 // type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000334 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000335 InitializedEntity Entity
336 = InitializedEntity::InitializeParameter(S.Context, T, /*Consumed=*/false);
337 InitializationKind Kind
338 = InitializationKind::CreateCopy(Element->getLocStart(), SourceLocation());
339 InitializationSequence Seq(S, Entity, Kind, &Element, 1);
340 if (!Seq.Failed())
341 return Seq.Perform(S, Entity, Kind, MultiExprArg(S, &Element, 1));
342 }
343
344 Expr *OrigElement = Element;
345
346 // Perform lvalue-to-rvalue conversion.
347 Result = S.DefaultLvalueConversion(Element);
348 if (Result.isInvalid())
349 return ExprError();
350 Element = Result.get();
351
352 // Make sure that we have an Objective-C pointer type or block.
353 if (!Element->getType()->isObjCObjectPointerType() &&
354 !Element->getType()->isBlockPointerType()) {
355 bool Recovered = false;
356
357 // If this is potentially an Objective-C numeric literal, add the '@'.
358 if (isa<IntegerLiteral>(OrigElement) ||
359 isa<CharacterLiteral>(OrigElement) ||
360 isa<FloatingLiteral>(OrigElement) ||
361 isa<ObjCBoolLiteralExpr>(OrigElement) ||
362 isa<CXXBoolLiteralExpr>(OrigElement)) {
363 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
364 int Which = isa<CharacterLiteral>(OrigElement) ? 1
365 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
366 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
367 : 3;
368
369 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
370 << Which << OrigElement->getSourceRange()
371 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
372
373 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
374 OrigElement);
375 if (Result.isInvalid())
376 return ExprError();
377
378 Element = Result.get();
379 Recovered = true;
380 }
381 }
382 // If this is potentially an Objective-C string literal, add the '@'.
383 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
384 if (String->isAscii()) {
385 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
386 << 0 << OrigElement->getSourceRange()
387 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
388
389 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
390 if (Result.isInvalid())
391 return ExprError();
392
393 Element = Result.get();
394 Recovered = true;
395 }
396 }
397
398 if (!Recovered) {
399 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
400 << Element->getType();
401 return ExprError();
402 }
403 }
404
405 // Make sure that the element has the type that the container factory
406 // function expects.
407 return S.PerformCopyInitialization(
408 InitializedEntity::InitializeParameter(S.Context, T,
409 /*Consumed=*/false),
410 Element->getLocStart(), Element);
411}
412
Patrick Beardeb382ec2012-04-19 00:25:12 +0000413ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
414 if (ValueExpr->isTypeDependent()) {
415 ObjCBoxedExpr *BoxedExpr =
416 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR);
417 return Owned(BoxedExpr);
418 }
419 ObjCMethodDecl *BoxingMethod = NULL;
420 QualType BoxedType;
421 // Convert the expression to an RValue, so we can check for pointer types...
422 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
423 if (RValue.isInvalid()) {
424 return ExprError();
425 }
426 ValueExpr = RValue.get();
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000427 QualType ValueType(ValueExpr->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +0000428 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
429 QualType PointeeType = PT->getPointeeType();
430 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
431
432 if (!NSStringDecl) {
433 IdentifierInfo *NSStringId =
434 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
435 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
436 SR.getBegin(), LookupOrdinaryName);
437 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
438 if (!NSStringDecl) {
439 if (getLangOpts().DebuggerObjCLiteral) {
440 // Support boxed expressions in the debugger w/o NSString declaration.
441 NSStringDecl = ObjCInterfaceDecl::Create(Context,
442 Context.getTranslationUnitDecl(),
443 SourceLocation(), NSStringId,
444 0, SourceLocation());
445 } else {
446 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
447 return ExprError();
448 }
449 } else if (!NSStringDecl->hasDefinition()) {
450 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
451 return ExprError();
452 }
453 assert(NSStringDecl && "NSStringDecl should not be NULL");
454 NSStringPointer =
455 Context.getObjCObjectPointerType(Context.getObjCInterfaceType(NSStringDecl));
456 }
457
458 if (!StringWithUTF8StringMethod) {
459 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
460 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
461
462 // Look for the appropriate method within NSString.
Jordy Rosec8521fa2012-05-12 17:32:44 +0000463 BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
464 if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000465 // Debugger needs to work even if NSString hasn't been defined.
466 TypeSourceInfo *ResultTInfo = 0;
467 ObjCMethodDecl *M =
468 ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(),
469 stringWithUTF8String, NSStringPointer,
470 ResultTInfo, NSStringDecl,
471 /*isInstance=*/false, /*isVariadic=*/false,
472 /*isSynthesized=*/false,
473 /*isImplicitlyDeclared=*/true,
474 /*isDefined=*/false,
475 ObjCMethodDecl::Required,
476 /*HasRelatedResultType=*/false);
477 ParmVarDecl *value =
478 ParmVarDecl::Create(Context, M,
479 SourceLocation(), SourceLocation(),
480 &Context.Idents.get("value"),
481 Context.getPointerType(Context.CharTy.withConst()),
482 /*TInfo=*/0,
483 SC_None, SC_None, 0);
484 M->setMethodParams(Context, value, ArrayRef<SourceLocation>());
Jordy Rosec8521fa2012-05-12 17:32:44 +0000485 BoxingMethod = M;
Patrick Beardeb382ec2012-04-19 00:25:12 +0000486 }
Jordy Rose99446d92012-05-12 15:53:41 +0000487
Jordy Rosec8521fa2012-05-12 17:32:44 +0000488 if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl,
489 stringWithUTF8String, BoxingMethod))
490 return ExprError();
491
492 StringWithUTF8StringMethod = BoxingMethod;
Patrick Beardeb382ec2012-04-19 00:25:12 +0000493 }
494
495 BoxingMethod = StringWithUTF8StringMethod;
496 BoxedType = NSStringPointer;
497 }
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000498 } else if (ValueType->isBuiltinType()) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000499 // The other types we support are numeric, char and BOOL/bool. We could also
500 // provide limited support for structure types, such as NSRange, NSRect, and
501 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
502 // for more details.
503
504 // Check for a top-level character literal.
505 if (const CharacterLiteral *Char =
506 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
507 // In C, character literals have type 'int'. That's not the type we want
508 // to use to determine the Objective-c literal kind.
509 switch (Char->getKind()) {
510 case CharacterLiteral::Ascii:
511 ValueType = Context.CharTy;
512 break;
513
514 case CharacterLiteral::Wide:
515 ValueType = Context.getWCharType();
516 break;
517
518 case CharacterLiteral::UTF16:
519 ValueType = Context.Char16Ty;
520 break;
521
522 case CharacterLiteral::UTF32:
523 ValueType = Context.Char32Ty;
524 break;
525 }
526 }
527
528 // FIXME: Do I need to do anything special with BoolTy expressions?
529
530 // Look for the appropriate method within NSNumber.
531 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
532 BoxedType = NSNumberPointer;
533 }
534
535 if (!BoxingMethod) {
536 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
537 << ValueType << ValueExpr->getSourceRange();
538 return ExprError();
539 }
540
541 // Convert the expression to the type that the parameter requires.
Patrick Bearde0fdadf2012-05-01 21:47:19 +0000542 ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0];
543 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
544 ParamDecl);
545 ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity,
546 SourceLocation(),
547 Owned(ValueExpr));
Patrick Beardeb382ec2012-04-19 00:25:12 +0000548 if (ConvertedValueExpr.isInvalid())
549 return ExprError();
550 ValueExpr = ConvertedValueExpr.get();
551
552 ObjCBoxedExpr *BoxedExpr =
553 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
554 BoxingMethod, SR);
555 return MaybeBindToTemporary(BoxedExpr);
556}
557
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000558ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
559 Expr *IndexExpr,
560 ObjCMethodDecl *getterMethod,
561 ObjCMethodDecl *setterMethod) {
562 // Feature support is for modern abi.
563 if (!LangOpts.ObjCNonFragileABI)
564 return ExprError();
565 // If the expression is type-dependent, there's nothing for us to do.
566 assert ((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
567 "base or index cannot have dependent type here");
568 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
569 if (Result.isInvalid())
570 return ExprError();
571 IndexExpr = Result.get();
572
573 // Perform lvalue-to-rvalue conversion.
574 Result = DefaultLvalueConversion(BaseExpr);
575 if (Result.isInvalid())
576 return ExprError();
577 BaseExpr = Result.get();
578 return Owned(ObjCSubscriptRefExpr::Create(Context,
579 BaseExpr,
580 IndexExpr,
581 Context.PseudoObjectTy,
582 getterMethod,
583 setterMethod, RB));
584
585}
586
587ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
588 // Look up the NSArray class, if we haven't done so already.
589 if (!NSArrayDecl) {
590 NamedDecl *IF = LookupSingleName(TUScope,
591 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
592 SR.getBegin(),
593 LookupOrdinaryName);
594 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikie4e4d0842012-03-11 07:00:24 +0000595 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000596 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
597 Context.getTranslationUnitDecl(),
598 SourceLocation(),
599 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
600 0, SourceLocation());
601
602 if (!NSArrayDecl) {
603 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
604 return ExprError();
605 }
606 }
607
608 // Find the arrayWithObjects:count: method, if we haven't done so already.
609 QualType IdT = Context.getObjCIdType();
610 if (!ArrayWithObjectsMethod) {
611 Selector
612 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
Jordy Rosec8521fa2012-05-12 17:32:44 +0000613 ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel);
614 if (!Method && getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000615 TypeSourceInfo *ResultTInfo = 0;
Jordy Rosec8521fa2012-05-12 17:32:44 +0000616 Method = ObjCMethodDecl::Create(Context,
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000617 SourceLocation(), SourceLocation(), Sel,
618 IdT,
619 ResultTInfo,
620 Context.getTranslationUnitDecl(),
621 false /*Instance*/, false/*isVariadic*/,
622 /*isSynthesized=*/false,
623 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
624 ObjCMethodDecl::Required,
625 false);
626 SmallVector<ParmVarDecl *, 2> Params;
Jordy Rosec8521fa2012-05-12 17:32:44 +0000627 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000628 SourceLocation(), SourceLocation(),
629 &Context.Idents.get("objects"),
630 Context.getPointerType(IdT),
631 /*TInfo=*/0,
632 SC_None,
633 SC_None,
634 0);
635 Params.push_back(objects);
Jordy Rosec8521fa2012-05-12 17:32:44 +0000636 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000637 SourceLocation(), SourceLocation(),
638 &Context.Idents.get("cnt"),
639 Context.UnsignedLongTy,
640 /*TInfo=*/0,
641 SC_None,
642 SC_None,
643 0);
644 Params.push_back(cnt);
Jordy Rosec8521fa2012-05-12 17:32:44 +0000645 Method->setMethodParams(Context, Params, ArrayRef<SourceLocation>());
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000646
647
648 }
649
Jordy Rosec8521fa2012-05-12 17:32:44 +0000650 if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method))
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000651 return ExprError();
Jordy Rosec8521fa2012-05-12 17:32:44 +0000652
653 ArrayWithObjectsMethod = Method;
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000654 }
655
656 // Dig out the type that all elements should be converted to.
657 QualType T = ArrayWithObjectsMethod->param_begin()[0]->getType();
658 const PointerType *PtrT = T->getAs<PointerType>();
659 if (!PtrT ||
660 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
661 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
662 << ArrayWithObjectsMethod->getSelector();
663 Diag(ArrayWithObjectsMethod->param_begin()[0]->getLocation(),
664 diag::note_objc_literal_method_param)
665 << 0 << T
666 << Context.getPointerType(IdT.withConst());
667 return ExprError();
668 }
669 T = PtrT->getPointeeType();
670
671 // Check that the 'count' parameter is integral.
672 if (!ArrayWithObjectsMethod->param_begin()[1]->getType()->isIntegerType()) {
673 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
674 << ArrayWithObjectsMethod->getSelector();
675 Diag(ArrayWithObjectsMethod->param_begin()[1]->getLocation(),
676 diag::note_objc_literal_method_param)
677 << 1
678 << ArrayWithObjectsMethod->param_begin()[1]->getType()
679 << "integral";
680 return ExprError();
681 }
682
683 // Check that each of the elements provided is valid in a collection literal,
684 // performing conversions as necessary.
685 Expr **ElementsBuffer = Elements.get();
686 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
687 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
688 ElementsBuffer[I],
689 T);
690 if (Converted.isInvalid())
691 return ExprError();
692
693 ElementsBuffer[I] = Converted.get();
694 }
695
696 QualType Ty
697 = Context.getObjCObjectPointerType(
698 Context.getObjCInterfaceType(NSArrayDecl));
699
700 return MaybeBindToTemporary(
701 ObjCArrayLiteral::Create(Context,
702 llvm::makeArrayRef(Elements.get(),
703 Elements.size()),
704 Ty, ArrayWithObjectsMethod, SR));
705}
706
707ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
708 ObjCDictionaryElement *Elements,
709 unsigned NumElements) {
710 // Look up the NSDictionary class, if we haven't done so already.
711 if (!NSDictionaryDecl) {
712 NamedDecl *IF = LookupSingleName(TUScope,
713 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
714 SR.getBegin(), LookupOrdinaryName);
715 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikie4e4d0842012-03-11 07:00:24 +0000716 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000717 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
718 Context.getTranslationUnitDecl(),
719 SourceLocation(),
720 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
721 0, SourceLocation());
722
723 if (!NSDictionaryDecl) {
724 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
725 return ExprError();
726 }
727 }
728
729 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
730 // so already.
731 QualType IdT = Context.getObjCIdType();
732 if (!DictionaryWithObjectsMethod) {
733 Selector Sel = NSAPIObj->getNSDictionarySelector(
734 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
Jordy Rosec8521fa2012-05-12 17:32:44 +0000735 ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel);
736 if (!Method && getLangOpts().DebuggerObjCLiteral) {
737 Method = ObjCMethodDecl::Create(Context,
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000738 SourceLocation(), SourceLocation(), Sel,
739 IdT,
740 0 /*TypeSourceInfo */,
741 Context.getTranslationUnitDecl(),
742 false /*Instance*/, false/*isVariadic*/,
743 /*isSynthesized=*/false,
744 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
745 ObjCMethodDecl::Required,
746 false);
747 SmallVector<ParmVarDecl *, 3> Params;
Jordy Rosec8521fa2012-05-12 17:32:44 +0000748 ParmVarDecl *objects = ParmVarDecl::Create(Context, Method,
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000749 SourceLocation(), SourceLocation(),
750 &Context.Idents.get("objects"),
751 Context.getPointerType(IdT),
752 /*TInfo=*/0,
753 SC_None,
754 SC_None,
755 0);
756 Params.push_back(objects);
Jordy Rosec8521fa2012-05-12 17:32:44 +0000757 ParmVarDecl *keys = ParmVarDecl::Create(Context, Method,
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000758 SourceLocation(), SourceLocation(),
759 &Context.Idents.get("keys"),
760 Context.getPointerType(IdT),
761 /*TInfo=*/0,
762 SC_None,
763 SC_None,
764 0);
765 Params.push_back(keys);
Jordy Rosec8521fa2012-05-12 17:32:44 +0000766 ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method,
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000767 SourceLocation(), SourceLocation(),
768 &Context.Idents.get("cnt"),
769 Context.UnsignedLongTy,
770 /*TInfo=*/0,
771 SC_None,
772 SC_None,
773 0);
774 Params.push_back(cnt);
Jordy Rosec8521fa2012-05-12 17:32:44 +0000775 Method->setMethodParams(Context, Params, ArrayRef<SourceLocation>());
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000776 }
777
Jordy Rosec8521fa2012-05-12 17:32:44 +0000778 if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel,
779 Method))
780 return ExprError();
781
782 DictionaryWithObjectsMethod = Method;
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000783 }
784
785 // Dig out the type that all values should be converted to.
786 QualType ValueT = DictionaryWithObjectsMethod->param_begin()[0]->getType();
787 const PointerType *PtrValue = ValueT->getAs<PointerType>();
788 if (!PtrValue ||
789 !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) {
790 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
791 << DictionaryWithObjectsMethod->getSelector();
792 Diag(DictionaryWithObjectsMethod->param_begin()[0]->getLocation(),
793 diag::note_objc_literal_method_param)
794 << 0 << ValueT
795 << Context.getPointerType(IdT.withConst());
796 return ExprError();
797 }
798 ValueT = PtrValue->getPointeeType();
799
800 // Dig out the type that all keys should be converted to.
801 QualType KeyT = DictionaryWithObjectsMethod->param_begin()[1]->getType();
802 const PointerType *PtrKey = KeyT->getAs<PointerType>();
803 if (!PtrKey ||
804 !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
805 IdT)) {
806 bool err = true;
807 if (PtrKey) {
808 if (QIDNSCopying.isNull()) {
809 // key argument of selector is id<NSCopying>?
810 if (ObjCProtocolDecl *NSCopyingPDecl =
811 LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) {
812 ObjCProtocolDecl *PQ[] = {NSCopyingPDecl};
813 QIDNSCopying =
814 Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
815 (ObjCProtocolDecl**) PQ,1);
816 QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying);
817 }
818 }
819 if (!QIDNSCopying.isNull())
820 err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(),
821 QIDNSCopying);
822 }
823
824 if (err) {
825 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
826 << DictionaryWithObjectsMethod->getSelector();
827 Diag(DictionaryWithObjectsMethod->param_begin()[1]->getLocation(),
828 diag::note_objc_literal_method_param)
829 << 1 << KeyT
830 << Context.getPointerType(IdT.withConst());
831 return ExprError();
832 }
833 }
834 KeyT = PtrKey->getPointeeType();
835
836 // Check that the 'count' parameter is integral.
837 if (!DictionaryWithObjectsMethod->param_begin()[2]->getType()
838 ->isIntegerType()) {
839 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
840 << DictionaryWithObjectsMethod->getSelector();
841 Diag(DictionaryWithObjectsMethod->param_begin()[2]->getLocation(),
842 diag::note_objc_literal_method_param)
843 << 2
844 << DictionaryWithObjectsMethod->param_begin()[2]->getType()
845 << "integral";
846 return ExprError();
847 }
848
849 // Check that each of the keys and values provided is valid in a collection
850 // literal, performing conversions as necessary.
851 bool HasPackExpansions = false;
852 for (unsigned I = 0, N = NumElements; I != N; ++I) {
853 // Check the key.
854 ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key,
855 KeyT);
856 if (Key.isInvalid())
857 return ExprError();
858
859 // Check the value.
860 ExprResult Value
861 = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT);
862 if (Value.isInvalid())
863 return ExprError();
864
865 Elements[I].Key = Key.get();
866 Elements[I].Value = Value.get();
867
868 if (Elements[I].EllipsisLoc.isInvalid())
869 continue;
870
871 if (!Elements[I].Key->containsUnexpandedParameterPack() &&
872 !Elements[I].Value->containsUnexpandedParameterPack()) {
873 Diag(Elements[I].EllipsisLoc,
874 diag::err_pack_expansion_without_parameter_packs)
875 << SourceRange(Elements[I].Key->getLocStart(),
876 Elements[I].Value->getLocEnd());
877 return ExprError();
878 }
879
880 HasPackExpansions = true;
881 }
882
883
884 QualType Ty
885 = Context.getObjCObjectPointerType(
886 Context.getObjCInterfaceType(NSDictionaryDecl));
887 return MaybeBindToTemporary(
888 ObjCDictionaryLiteral::Create(Context,
889 llvm::makeArrayRef(Elements,
890 NumElements),
891 HasPackExpansions,
892 Ty,
893 DictionaryWithObjectsMethod, SR));
Chris Lattner85a932e2008-01-04 22:32:30 +0000894}
895
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000896ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000897 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000898 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000899 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000900 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000901 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000902 StrTy = Context.DependentTy;
903 else {
Fariborz Jahanian6c916152011-06-16 22:34:44 +0000904 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
905 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000906 if (RequireCompleteType(AtLoc, EncodedType,
Douglas Gregord10099e2012-05-04 16:32:21 +0000907 diag::err_incomplete_type_objc_at_encode,
908 EncodedTypeInfo->getTypeLoc()))
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000909 return ExprError();
910
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000911 std::string Str;
912 Context.getObjCEncodingForType(EncodedType, Str);
913
914 // The type of @encode is the same as the type of the corresponding string,
915 // which is an array type.
916 StrTy = Context.CharTy;
917 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikie4e4d0842012-03-11 07:00:24 +0000918 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000919 StrTy.addConst();
920 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
921 ArrayType::Normal, 0);
922 }
Mike Stump1eb44332009-09-09 15:08:12 +0000923
Douglas Gregor81d34662010-04-20 15:39:42 +0000924 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000925}
926
John McCallf312b1e2010-08-26 23:41:50 +0000927ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
928 SourceLocation EncodeLoc,
929 SourceLocation LParenLoc,
930 ParsedType ty,
931 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000932 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000933 TypeSourceInfo *TInfo;
934 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
935 if (!TInfo)
936 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
937 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000938
Douglas Gregor81d34662010-04-20 15:39:42 +0000939 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000940}
941
John McCallf312b1e2010-08-26 23:41:50 +0000942ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
943 SourceLocation AtLoc,
944 SourceLocation SelLoc,
945 SourceLocation LParenLoc,
946 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000947 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000948 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000949 if (!Method)
950 Method = LookupFactoryMethodInGlobalPool(Sel,
951 SourceRange(LParenLoc, RParenLoc));
952 if (!Method)
953 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian4c91d892011-07-13 19:05:43 +0000954
955 if (!Method ||
956 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
957 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
958 = ReferencedSelectors.find(Sel);
959 if (Pos == ReferencedSelectors.end())
960 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
961 }
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000962
John McCallf85e1932011-06-15 23:02:42 +0000963 // In ARC, forbid the user from using @selector for
964 // retain/release/autorelease/dealloc/retainCount.
David Blaikie4e4d0842012-03-11 07:00:24 +0000965 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +0000966 switch (Sel.getMethodFamily()) {
967 case OMF_retain:
968 case OMF_release:
969 case OMF_autorelease:
970 case OMF_retainCount:
971 case OMF_dealloc:
972 Diag(AtLoc, diag::err_arc_illegal_selector) <<
973 Sel << SourceRange(LParenLoc, RParenLoc);
974 break;
975
976 case OMF_None:
977 case OMF_alloc:
978 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +0000979 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +0000980 case OMF_init:
981 case OMF_mutableCopy:
982 case OMF_new:
983 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +0000984 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +0000985 break;
986 }
987 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000988 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000989 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000990}
991
John McCallf312b1e2010-08-26 23:41:50 +0000992ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
993 SourceLocation AtLoc,
994 SourceLocation ProtoLoc,
995 SourceLocation LParenLoc,
996 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000997 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000998 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000999 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +00001000 return true;
1001 }
Mike Stump1eb44332009-09-09 15:08:12 +00001002
Chris Lattnera0af1fe2009-02-18 06:06:56 +00001003 QualType Ty = Context.getObjCProtoType();
1004 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +00001005 return true;
Steve Naroff14108da2009-07-10 23:34:53 +00001006 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +00001007 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +00001008}
1009
John McCall26743b22011-02-03 09:00:02 +00001010/// Try to capture an implicit reference to 'self'.
Eli Friedmanb942cb22012-02-03 22:47:37 +00001011ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
1012 DeclContext *DC = getFunctionLevelDeclContext();
John McCall26743b22011-02-03 09:00:02 +00001013
1014 // If we're not in an ObjC method, error out. Note that, unlike the
1015 // C++ case, we don't require an instance method --- class methods
1016 // still have a 'self', and we really do still need to capture it!
1017 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
1018 if (!method)
1019 return 0;
1020
Douglas Gregor999713e2012-02-18 09:37:24 +00001021 tryCaptureVariable(method->getSelfDecl(), Loc);
John McCall26743b22011-02-03 09:00:02 +00001022
1023 return method;
1024}
1025
Douglas Gregor5c16d632011-09-09 20:05:21 +00001026static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
1027 if (T == Context.getObjCInstanceType())
1028 return Context.getObjCIdType();
1029
1030 return T;
1031}
1032
Douglas Gregor926df6c2011-06-11 01:09:30 +00001033QualType Sema::getMessageSendResultType(QualType ReceiverType,
1034 ObjCMethodDecl *Method,
1035 bool isClassMessage, bool isSuperMessage) {
1036 assert(Method && "Must have a method");
1037 if (!Method->hasRelatedResultType())
1038 return Method->getSendResultType();
1039
1040 // If a method has a related return type:
1041 // - if the method found is an instance method, but the message send
1042 // was a class message send, T is the declared return type of the method
1043 // found
1044 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor5c16d632011-09-09 20:05:21 +00001045 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001046
1047 // - if the receiver is super, T is a pointer to the class of the
1048 // enclosing method definition
1049 if (isSuperMessage) {
1050 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
1051 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
1052 return Context.getObjCObjectPointerType(
1053 Context.getObjCInterfaceType(Class));
1054 }
1055
1056 // - if the receiver is the name of a class U, T is a pointer to U
1057 if (ReceiverType->getAs<ObjCInterfaceType>() ||
1058 ReceiverType->isObjCQualifiedInterfaceType())
1059 return Context.getObjCObjectPointerType(ReceiverType);
1060 // - if the receiver is of type Class or qualified Class type,
1061 // T is the declared return type of the method.
1062 if (ReceiverType->isObjCClassType() ||
1063 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor5c16d632011-09-09 20:05:21 +00001064 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001065
1066 // - if the receiver is id, qualified id, Class, or qualified Class, T
1067 // is the receiver type, otherwise
1068 // - T is the type of the receiver expression.
1069 return ReceiverType;
1070}
John McCall26743b22011-02-03 09:00:02 +00001071
Douglas Gregor926df6c2011-06-11 01:09:30 +00001072void Sema::EmitRelatedResultTypeNote(const Expr *E) {
1073 E = E->IgnoreParenImpCasts();
1074 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
1075 if (!MsgSend)
1076 return;
1077
1078 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
1079 if (!Method)
1080 return;
1081
1082 if (!Method->hasRelatedResultType())
1083 return;
1084
1085 if (Context.hasSameUnqualifiedType(Method->getResultType()
1086 .getNonReferenceType(),
1087 MsgSend->getType()))
1088 return;
1089
Douglas Gregore97179c2011-09-08 01:46:34 +00001090 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
1091 Context.getObjCInstanceType()))
1092 return;
1093
Douglas Gregor926df6c2011-06-11 01:09:30 +00001094 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
1095 << Method->isInstanceMethod() << Method->getSelector()
1096 << MsgSend->getType();
1097}
1098
1099bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
1100 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00001101 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +00001102 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001103 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +00001104 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001105 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +00001106 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +00001107 for (unsigned i = 0; i != NumArgs; i++) {
1108 if (Args[i]->isTypeDependent())
1109 continue;
1110
John Wiegley429bb272011-04-08 18:41:53 +00001111 ExprResult Result = DefaultArgumentPromotion(Args[i]);
1112 if (Result.isInvalid())
1113 return true;
1114 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +00001115 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +00001116
John McCallf85e1932011-06-15 23:02:42 +00001117 unsigned DiagID;
David Blaikie4e4d0842012-03-11 07:00:24 +00001118 if (getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00001119 DiagID = diag::err_arc_method_not_found;
1120 else
1121 DiagID = isClassMessage ? diag::warn_class_method_not_found
1122 : diag::warn_inst_method_not_found;
David Blaikie4e4d0842012-03-11 07:00:24 +00001123 if (!getLangOpts().DebuggerSupport)
John McCall819e7452011-08-31 20:57:36 +00001124 Diag(lbrac, DiagID)
1125 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +00001126
1127 // In debuggers, we want to use __unknown_anytype for these
1128 // results so that clients can cast them.
David Blaikie4e4d0842012-03-11 07:00:24 +00001129 if (getLangOpts().DebuggerSupport) {
John McCall48218c62011-07-13 17:56:40 +00001130 ReturnType = Context.UnknownAnyTy;
1131 } else {
1132 ReturnType = Context.getObjCIdType();
1133 }
John McCallf89e55a2010-11-18 06:31:45 +00001134 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001135 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +00001136 }
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Douglas Gregor926df6c2011-06-11 01:09:30 +00001138 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
1139 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +00001140 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001142 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +00001143 // Method might have more arguments than selector indicates. This is due
1144 // to addition of c-style arguments in method.
1145 if (Method->param_size() > Sel.getNumArgs())
1146 NumNamedArgs = Method->param_size();
1147 // FIXME. This need be cleaned up.
1148 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +00001149 Diag(lbrac, diag::err_typecheck_call_too_few_args)
1150 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +00001151 return false;
1152 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001153
Chris Lattner312531a2009-04-12 08:11:20 +00001154 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001155 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001156 // We can't do any type-checking on a type-dependent argument.
1157 if (Args[i]->isTypeDependent())
1158 continue;
1159
Chris Lattner85a932e2008-01-04 22:32:30 +00001160 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +00001161
John McCall5acb0c92011-10-17 18:40:02 +00001162 ParmVarDecl *param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +00001163 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +00001164
John McCall5acb0c92011-10-17 18:40:02 +00001165 // Strip the unbridged-cast placeholder expression off unless it's
1166 // a consumed argument.
1167 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
1168 !param->hasAttr<CFConsumedAttr>())
1169 argExpr = stripARCUnbridgedCast(argExpr);
1170
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001171 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall5acb0c92011-10-17 18:40:02 +00001172 param->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00001173 diag::err_call_incomplete_argument, argExpr))
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001174 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +00001175
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001176 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall5acb0c92011-10-17 18:40:02 +00001177 param);
John McCall3fa5cae2010-10-26 07:05:15 +00001178 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001179 if (ArgE.isInvalid())
1180 IsError = true;
1181 else
1182 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +00001183 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001184
1185 // Promote additional arguments to variadic methods.
1186 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001187 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
1188 if (Args[i]->isTypeDependent())
1189 continue;
1190
John Wiegley429bb272011-04-08 18:41:53 +00001191 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
1192 IsError |= Arg.isInvalid();
1193 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +00001194 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001195 } else {
1196 // Check for extra arguments to non-variadic methods.
1197 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001198 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001199 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001200 << 2 /*method*/ << NumNamedArgs << NumArgs
1201 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001202 << SourceRange(Args[NumNamedArgs]->getLocStart(),
1203 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001204 }
1205 }
1206
Douglas Gregor2725ca82010-04-21 19:57:20 +00001207 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001208
1209 // Do additional checkings on method.
1210 IsError |= CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
1211
Chris Lattner312531a2009-04-12 08:11:20 +00001212 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +00001213}
1214
Douglas Gregorc737acb2011-09-27 16:10:05 +00001215bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +00001216 // 'self' is objc 'self' in an objc method only.
John McCall4b9c2d22011-11-06 09:01:30 +00001217 ObjCMethodDecl *method =
1218 dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1219 if (!method) return false;
1220
John McCallf85e1932011-06-15 23:02:42 +00001221 receiver = receiver->IgnoreParenLValueCasts();
1222 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCall4b9c2d22011-11-06 09:01:30 +00001223 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregorc737acb2011-09-27 16:10:05 +00001224 return true;
1225 return false;
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001226}
1227
Steve Narofff1afaf62009-02-26 15:55:06 +00001228// Helper method for ActOnClassMethod/ActOnInstanceMethod.
1229// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +00001230// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +00001231// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +00001232ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +00001233 ObjCInterfaceDecl *ClassDecl) {
1234 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +00001235 // lookup in class and all superclasses
1236 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001237 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001238 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001239
Steve Naroff5609ec02009-03-08 18:56:13 +00001240 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001241 if (!Method)
1242 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001243
Steve Naroff5609ec02009-03-08 18:56:13 +00001244 // Before we give up, check if the selector is an instance method.
1245 // But only in the root. This matches gcc's behaviour and what the
1246 // runtime expects.
1247 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001248 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001249 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +00001250 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +00001251 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +00001252 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1253 }
Mike Stump1eb44332009-09-09 15:08:12 +00001254
Steve Naroff5609ec02009-03-08 18:56:13 +00001255 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +00001256 }
Steve Naroff5609ec02009-03-08 18:56:13 +00001257 return Method;
1258}
1259
1260ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
1261 ObjCInterfaceDecl *ClassDecl) {
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00001262 if (!ClassDecl->hasDefinition())
1263 return 0;
1264
Steve Naroff5609ec02009-03-08 18:56:13 +00001265 ObjCMethodDecl *Method = 0;
1266 while (ClassDecl && !Method) {
1267 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001268 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001269 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001270
Steve Naroff5609ec02009-03-08 18:56:13 +00001271 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001272 if (!Method)
1273 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +00001274 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +00001275 }
Steve Narofff1afaf62009-02-26 15:55:06 +00001276 return Method;
1277}
1278
John McCall3c3b7f92011-10-25 17:37:35 +00001279/// LookupMethodInType - Look up a method in an ObjCObjectType.
1280ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1281 bool isInstance) {
1282 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1283 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1284 // Look it up in the main interface (and categories, etc.)
1285 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1286 return method;
1287
1288 // Okay, look for "private" methods declared in any
1289 // @implementations we've seen.
1290 if (isInstance) {
1291 if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
1292 return method;
1293 } else {
1294 if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
1295 return method;
1296 }
1297 }
1298
1299 // Check qualifiers.
1300 for (ObjCObjectType::qual_iterator
1301 i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
1302 if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
1303 return method;
1304
1305 return 0;
1306}
1307
Fariborz Jahanian61478062011-03-09 20:18:06 +00001308/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1309/// list of a qualified objective pointer type.
1310ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1311 const ObjCObjectPointerType *OPT,
1312 bool Instance)
1313{
1314 ObjCMethodDecl *MD = 0;
1315 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1316 E = OPT->qual_end(); I != E; ++I) {
1317 ObjCProtocolDecl *PROTO = (*I);
1318 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1319 return MD;
1320 }
1321 }
1322 return 0;
1323}
1324
Fariborz Jahanian98795562012-04-19 23:49:39 +00001325static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1326 if (!Receiver)
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001327 return;
1328
Fariborz Jahanian98795562012-04-19 23:49:39 +00001329 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1330 SourceLocation Loc = RExpr->getLocStart();
1331 QualType T = RExpr->getType();
1332 ObjCPropertyDecl *PDecl = 0;
1333 ObjCMethodDecl *GDecl = 0;
1334 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1335 RExpr = POE->getSyntacticForm();
1336 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1337 if (PRE->isImplicitProperty()) {
1338 GDecl = PRE->getImplicitPropertyGetter();
1339 if (GDecl) {
1340 T = GDecl->getResultType();
1341 }
1342 }
1343 else {
1344 PDecl = PRE->getExplicitProperty();
1345 if (PDecl) {
1346 T = PDecl->getType();
1347 }
1348 }
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001349 }
Fariborz Jahanian98795562012-04-19 23:49:39 +00001350 }
1351
1352 if (T.getObjCLifetime() == Qualifiers::OCL_Weak) {
1353 S.Diag(Loc, diag::warn_receiver_is_weak)
1354 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1355 if (PDecl)
1356 S.Diag(PDecl->getLocation(), diag::note_property_declare);
1357 else if (GDecl)
1358 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001359 return;
1360 }
1361
Fariborz Jahanian98795562012-04-19 23:49:39 +00001362 if (PDecl &&
1363 (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)) {
1364 S.Diag(Loc, diag::warn_receiver_is_weak) << 1;
1365 S.Diag(PDecl->getLocation(), diag::note_property_declare);
1366 }
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001367}
1368
Chris Lattner7f816522010-04-11 07:45:24 +00001369/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1370/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001371ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +00001372HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001373 Expr *BaseExpr, SourceLocation OpLoc,
1374 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001375 SourceLocation MemberLoc,
1376 SourceLocation SuperLoc, QualType SuperType,
1377 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +00001378 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1379 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +00001380
1381 if (MemberName.getNameKind() != DeclarationName::Identifier) {
1382 Diag(MemberLoc, diag::err_invalid_property_name)
1383 << MemberName << QualType(OPT, 0);
1384 return ExprError();
1385 }
1386
Chris Lattner7f816522010-04-11 07:45:24 +00001387 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregorb3029962011-11-14 22:10:01 +00001388 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1389 : BaseExpr->getSourceRange();
1390 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00001391 diag::err_property_not_found_forward_class,
1392 MemberName, BaseRange))
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +00001393 return ExprError();
Douglas Gregorb3029962011-11-14 22:10:01 +00001394
Chris Lattner7f816522010-04-11 07:45:24 +00001395 // Search for a declared property first.
1396 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1397 // Check whether we can reference this property.
1398 if (DiagnoseUseOfDecl(PD, MemberLoc))
1399 return ExprError();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001400 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001401 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001402 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001403 MemberLoc,
1404 SuperLoc, SuperType));
1405 else
John McCall3c3b7f92011-10-25 17:37:35 +00001406 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001407 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001408 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001409 }
1410 // Check protocols on qualified interfaces.
1411 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1412 E = OPT->qual_end(); I != E; ++I)
1413 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1414 // Check whether we can reference this property.
1415 if (DiagnoseUseOfDecl(PD, MemberLoc))
1416 return ExprError();
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001417
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001418 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001419 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1420 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001421 VK_LValue,
1422 OK_ObjCProperty,
1423 MemberLoc,
1424 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001425 else
John McCall3c3b7f92011-10-25 17:37:35 +00001426 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1427 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001428 VK_LValue,
1429 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001430 MemberLoc,
1431 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001432 }
1433 // If that failed, look for an "implicit" property by seeing if the nullary
1434 // selector is implemented.
1435
1436 // FIXME: The logic for looking up nullary and unary selectors should be
1437 // shared with the code in ActOnInstanceMessage.
1438
1439 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1440 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001441
1442 // May be founf in property's qualified list.
1443 if (!Getter)
1444 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +00001445
1446 // If this reference is in an @implementation, check for 'private' methods.
1447 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001448 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +00001449
1450 // Look through local category implementations associated with the class.
1451 if (!Getter)
1452 Getter = IFace->getCategoryInstanceMethod(Sel);
1453 if (Getter) {
1454 // Check if we can reference this property.
1455 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1456 return ExprError();
1457 }
1458 // If we found a getter then this may be a valid dot-reference, we
1459 // will look for the matching setter, in case it is needed.
1460 Selector SetterSel =
1461 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1462 PP.getSelectorTable(), Member);
1463 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001464
1465 // May be founf in property's qualified list.
1466 if (!Setter)
1467 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1468
Chris Lattner7f816522010-04-11 07:45:24 +00001469 if (!Setter) {
1470 // If this reference is in an @implementation, also check for 'private'
1471 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001472 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +00001473 }
1474 // Look through local category implementations associated with the class.
1475 if (!Setter)
1476 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001477
Chris Lattner7f816522010-04-11 07:45:24 +00001478 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1479 return ExprError();
1480
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001481 if (Getter || Setter) {
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001482 if (Super)
John McCall12f78a62010-12-02 01:19:52 +00001483 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001484 Context.PseudoObjectTy,
1485 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001486 MemberLoc,
1487 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001488 else
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, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001493
Chris Lattner7f816522010-04-11 07:45:24 +00001494 }
1495
1496 // Attempt to correct for typos in property names.
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001497 DeclFilterCCC<ObjCPropertyDecl> Validator;
1498 if (TypoCorrection Corrected = CorrectTypo(
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001499 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001500 NULL, Validator, IFace, false, OPT)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001501 ObjCPropertyDecl *Property =
1502 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001503 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +00001504 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001505 << MemberName << QualType(OPT, 0) << TypoResult
1506 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +00001507 Diag(Property->getLocation(), diag::note_previous_decl)
1508 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001509 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1510 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001511 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +00001512 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001513 ObjCInterfaceDecl *ClassDeclared;
1514 if (ObjCIvarDecl *Ivar =
1515 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1516 QualType T = Ivar->getType();
1517 if (const ObjCObjectPointerType * OBJPT =
1518 T->getAsObjCInterfacePointerType()) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001519 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
Douglas Gregord10099e2012-05-04 16:32:21 +00001520 diag::err_property_not_as_forward_class,
1521 MemberName, BaseExpr))
Douglas Gregorb3029962011-11-14 22:10:01 +00001522 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001523 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001524 Diag(MemberLoc,
1525 diag::err_ivar_access_using_property_syntax_suggest)
1526 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1527 << FixItHint::CreateReplacement(OpLoc, "->");
1528 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001529 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001530
Chris Lattner7f816522010-04-11 07:45:24 +00001531 Diag(MemberLoc, diag::err_property_not_found)
1532 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001533 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +00001534 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001535 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +00001536 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +00001537}
1538
1539
1540
John McCall60d7b3a2010-08-24 06:29:42 +00001541ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +00001542ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1543 IdentifierInfo &propertyName,
1544 SourceLocation receiverNameLoc,
1545 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001546
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001547 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +00001548 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1549 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +00001550
1551 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +00001552 if (IFace == 0) {
1553 // If the "receiver" is 'super' in a method, handle it as an expression-like
1554 // property reference.
John McCall26743b22011-02-03 09:00:02 +00001555 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001556 IsSuper = true;
1557
Eli Friedmanb942cb22012-02-03 22:47:37 +00001558 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnereb483eb2010-04-11 08:28:14 +00001559 if (CurMethod->isInstanceMethod()) {
1560 QualType T =
1561 Context.getObjCInterfaceType(CurMethod->getClassInterface());
1562 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001563
1564 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001565 /*BaseExpr*/0,
1566 SourceLocation()/*OpLoc*/,
1567 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001568 propertyNameLoc,
1569 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001570 }
Mike Stump1eb44332009-09-09 15:08:12 +00001571
Chris Lattnereb483eb2010-04-11 08:28:14 +00001572 // Otherwise, if this is a class method, try dispatching to our
1573 // superclass.
1574 IFace = CurMethod->getClassInterface()->getSuperClass();
1575 }
John McCall26743b22011-02-03 09:00:02 +00001576 }
Chris Lattnereb483eb2010-04-11 08:28:14 +00001577
1578 if (IFace == 0) {
1579 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1580 return ExprError();
1581 }
1582 }
1583
1584 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +00001585 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001586 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001587
1588 // If this reference is in an @implementation, check for 'private' methods.
1589 if (!Getter)
1590 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1591 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001592 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001593 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001594
1595 if (Getter) {
1596 // FIXME: refactor/share with ActOnMemberReference().
1597 // Check if we can reference this property.
1598 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1599 return ExprError();
1600 }
Mike Stump1eb44332009-09-09 15:08:12 +00001601
Steve Naroff61f72cb2009-03-09 21:12:44 +00001602 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00001603 Selector SetterSel =
1604 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +00001605 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001607 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001608 if (!Setter) {
1609 // If this reference is in an @implementation, also check for 'private'
1610 // methods.
1611 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1612 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001613 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001614 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001615 }
1616 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001617 if (!Setter)
1618 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001619
1620 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1621 return ExprError();
1622
1623 if (Getter || Setter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001624 if (IsSuper)
1625 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001626 Context.PseudoObjectTy,
1627 VK_LValue, OK_ObjCProperty,
Douglas Gregor926df6c2011-06-11 01:09:30 +00001628 propertyNameLoc,
1629 receiverNameLoc,
1630 Context.getObjCInterfaceType(IFace)));
1631
John McCall12f78a62010-12-02 01:19:52 +00001632 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001633 Context.PseudoObjectTy,
1634 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001635 propertyNameLoc,
1636 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +00001637 }
1638 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1639 << &propertyName << Context.getObjCInterfaceType(IFace));
1640}
1641
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001642namespace {
1643
1644class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1645 public:
1646 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1647 // Determine whether "super" is acceptable in the current context.
1648 if (Method && Method->getClassInterface())
1649 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1650 }
1651
1652 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1653 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1654 candidate.isKeyword("super");
1655 }
1656};
1657
1658}
1659
Douglas Gregor47bd5432010-04-14 02:46:37 +00001660Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +00001661 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +00001662 SourceLocation NameLoc,
1663 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +00001664 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +00001665 ParsedType &ReceiverType) {
1666 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +00001667
Douglas Gregor47bd5432010-04-14 02:46:37 +00001668 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +00001669 // messaging super. If the identifier is "super" and there is a
1670 // trailing dot, it's an instance message.
1671 if (IsSuper && S->isInObjcMethodScope())
1672 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001673
1674 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1675 LookupName(Result, S);
1676
1677 switch (Result.getResultKind()) {
1678 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +00001679 // Normal name lookup didn't find anything. If we're in an
1680 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +00001681 // FIXME: This is a hack. Ivar lookup should be part of normal
1682 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +00001683 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidisccc9e762011-11-09 00:22:48 +00001684 if (!Method->getClassInterface()) {
1685 // Fall back: let the parser try to parse it as an instance message.
1686 return ObjCInstanceMessage;
1687 }
1688
Douglas Gregored464422010-04-19 20:09:36 +00001689 ObjCInterfaceDecl *ClassDeclared;
1690 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1691 ClassDeclared))
1692 return ObjCInstanceMessage;
1693 }
Douglas Gregor95f42922010-10-14 22:11:03 +00001694
Douglas Gregor47bd5432010-04-14 02:46:37 +00001695 // Break out; we'll perform typo correction below.
1696 break;
1697
1698 case LookupResult::NotFoundInCurrentInstantiation:
1699 case LookupResult::FoundOverloaded:
1700 case LookupResult::FoundUnresolvedValue:
1701 case LookupResult::Ambiguous:
1702 Result.suppressDiagnostics();
1703 return ObjCInstanceMessage;
1704
1705 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +00001706 // If the identifier is a class or not, and there is a trailing dot,
1707 // it's an instance message.
1708 if (HasTrailingDot)
1709 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001710 // We found something. If it's a type, then we have a class
1711 // message. Otherwise, it's an instance message.
1712 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +00001713 QualType T;
1714 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1715 T = Context.getObjCInterfaceType(Class);
1716 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
1717 T = Context.getTypeDeclType(Type);
1718 else
1719 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001720
Douglas Gregor1569f952010-04-21 20:38:13 +00001721 // We have a class message, and T is the type we're
1722 // messaging. Build source-location information for it.
1723 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +00001724 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +00001725 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001726 }
1727 }
1728
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001729 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001730 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1731 Result.getLookupKind(), S, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001732 Validator)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001733 if (Corrected.isKeyword()) {
1734 // If we've found the keyword "super" (the only keyword that would be
1735 // returned by CorrectTypo), this is a send to super.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001736 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001737 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +00001738 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +00001739 return ObjCSuperMessage;
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001740 } else if (ObjCInterfaceDecl *Class =
1741 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1742 // If we found a declaration, correct when it refers to an Objective-C
1743 // class.
1744 Diag(NameLoc, diag::err_unknown_receiver_suggest)
1745 << Name << Corrected.getCorrection()
1746 << FixItHint::CreateReplacement(SourceRange(NameLoc),
1747 Class->getNameAsString());
1748 Diag(Class->getLocation(), diag::note_previous_decl)
1749 << Corrected.getCorrection();
1750
1751 QualType T = Context.getObjCInterfaceType(Class);
1752 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1753 ReceiverType = CreateParsedType(T, TSInfo);
1754 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001755 }
1756 }
1757
1758 // Fall back: let the parser try to parse it as an instance message.
1759 return ObjCInstanceMessage;
1760}
Steve Naroff61f72cb2009-03-09 21:12:44 +00001761
John McCall60d7b3a2010-08-24 06:29:42 +00001762ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001763 SourceLocation SuperLoc,
1764 Selector Sel,
1765 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001766 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001767 SourceLocation RBracLoc,
1768 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001769 // Determine whether we are inside a method or not.
Eli Friedmanb942cb22012-02-03 22:47:37 +00001770 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregorf95861a2010-04-21 20:01:04 +00001771 if (!Method) {
1772 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1773 return ExprError();
1774 }
Chris Lattner85a932e2008-01-04 22:32:30 +00001775
Douglas Gregorf95861a2010-04-21 20:01:04 +00001776 ObjCInterfaceDecl *Class = Method->getClassInterface();
1777 if (!Class) {
1778 Diag(SuperLoc, diag::error_no_super_class_message)
1779 << Method->getDeclName();
1780 return ExprError();
1781 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001782
Douglas Gregorf95861a2010-04-21 20:01:04 +00001783 ObjCInterfaceDecl *Super = Class->getSuperClass();
1784 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001785 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +00001786 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1787 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001788 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +00001789 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001790
Douglas Gregorf95861a2010-04-21 20:01:04 +00001791 // We are in a method whose class has a superclass, so 'super'
1792 // is acting as a keyword.
1793 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +00001794 if (Sel.getMethodFamily() == OMF_dealloc)
1795 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00001796 if (Sel.getMethodFamily() == OMF_finalize)
1797 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +00001798
Douglas Gregorf95861a2010-04-21 20:01:04 +00001799 // Since we are in an instance method, this is an instance
1800 // message to the superclass instance.
1801 QualType SuperTy = Context.getObjCInterfaceType(Super);
1802 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +00001803 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001804 Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001805 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001806 }
Douglas Gregorf95861a2010-04-21 20:01:04 +00001807
1808 // Since we are in a class method, this is a class message to
1809 // the superclass.
1810 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1811 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001812 SuperLoc, Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001813 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001814}
1815
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001816
1817ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1818 bool isSuperReceiver,
1819 SourceLocation Loc,
1820 Selector Sel,
1821 ObjCMethodDecl *Method,
1822 MultiExprArg Args) {
1823 TypeSourceInfo *receiverTypeInfo = 0;
1824 if (!ReceiverType.isNull())
1825 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1826
1827 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1828 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1829 Sel, Method, Loc, Loc, Loc, Args,
1830 /*isImplicit=*/true);
1831
1832}
1833
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001834static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1835 unsigned DiagID,
1836 bool (*refactor)(const ObjCMessageExpr *,
1837 const NSAPI &, edit::Commit &)) {
1838 SourceLocation MsgLoc = Msg->getExprLoc();
1839 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
1840 return;
1841
1842 SourceManager &SM = S.SourceMgr;
1843 edit::Commit ECommit(SM, S.LangOpts);
1844 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1845 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1846 << Msg->getSelector() << Msg->getSourceRange();
1847 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1848 if (!ECommit.isCommitable())
1849 return;
1850 for (edit::Commit::edit_iterator
1851 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1852 const edit::Commit::Edit &Edit = *I;
1853 switch (Edit.Kind) {
1854 case edit::Commit::Act_Insert:
1855 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1856 Edit.Text,
1857 Edit.BeforePrev));
1858 break;
1859 case edit::Commit::Act_InsertFromRange:
1860 Builder.AddFixItHint(
1861 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1862 Edit.getInsertFromRange(SM),
1863 Edit.BeforePrev));
1864 break;
1865 case edit::Commit::Act_Remove:
1866 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1867 break;
1868 }
1869 }
1870 }
1871}
1872
1873static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1874 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1875 edit::rewriteObjCRedundantCallWithLiteral);
1876}
1877
Douglas Gregor2725ca82010-04-21 19:57:20 +00001878/// \brief Build an Objective-C class message expression.
1879///
1880/// This routine takes care of both normal class messages and
1881/// class messages to the superclass.
1882///
1883/// \param ReceiverTypeInfo Type source information that describes the
1884/// receiver of this message. This may be NULL, in which case we are
1885/// sending to the superclass and \p SuperLoc must be a valid source
1886/// location.
1887
1888/// \param ReceiverType The type of the object receiving the
1889/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1890/// type as that refers to. For a superclass send, this is the type of
1891/// the superclass.
1892///
1893/// \param SuperLoc The location of the "super" keyword in a
1894/// superclass message.
1895///
1896/// \param Sel The selector to which the message is being sent.
1897///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001898/// \param Method The method that this class message is invoking, if
1899/// already known.
1900///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001901/// \param LBracLoc The location of the opening square bracket ']'.
1902///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001903/// \param RBrac The location of the closing square bracket ']'.
1904///
1905/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001906ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001907 QualType ReceiverType,
1908 SourceLocation SuperLoc,
1909 Selector Sel,
1910 ObjCMethodDecl *Method,
1911 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001912 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001913 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001914 MultiExprArg ArgsIn,
1915 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001916 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001917 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001918 if (LBracLoc.isInvalid()) {
1919 Diag(Loc, diag::err_missing_open_square_message_send)
1920 << FixItHint::CreateInsertion(Loc, "[");
1921 LBracLoc = Loc;
1922 }
1923
Douglas Gregor92e986e2010-04-22 16:44:27 +00001924 if (ReceiverType->isDependentType()) {
1925 // If the receiver type is dependent, we can't type-check anything
1926 // at this point. Build a dependent expression.
1927 unsigned NumArgs = ArgsIn.size();
1928 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1929 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001930 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1931 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001932 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001933 makeArrayRef(Args, NumArgs),RBracLoc,
1934 isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001935 }
Chris Lattner15faee12010-04-12 05:38:43 +00001936
Douglas Gregor2725ca82010-04-21 19:57:20 +00001937 // Find the class to which we are sending this message.
1938 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001939 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1940 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001941 Diag(Loc, diag::err_invalid_receiver_class_message)
1942 << ReceiverType;
1943 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001944 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001945 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001946 // objc++ diagnoses during typename annotation.
David Blaikie4e4d0842012-03-11 07:00:24 +00001947 if (!getLangOpts().CPlusPlus)
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001948 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001949 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001950 if (!Method) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001951 SourceRange TypeRange
1952 = SuperLoc.isValid()? SourceRange(SuperLoc)
1953 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00001954 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikie4e4d0842012-03-11 07:00:24 +00001955 (getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00001956 ? diag::err_arc_receiver_forward_class
1957 : diag::warn_receiver_forward_class),
1958 TypeRange)) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001959 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001960 Method = LookupFactoryMethodInGlobalPool(Sel,
1961 SourceRange(LBracLoc, RBracLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00001962 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001963 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1964 << Method->getDeclName();
1965 }
1966 if (!Method)
1967 Method = Class->lookupClassMethod(Sel);
1968
1969 // If we have an implementation in scope, check "private" methods.
1970 if (!Method)
1971 Method = LookupPrivateClassMethod(Sel, Class);
1972
1973 if (Method && DiagnoseUseOfDecl(Method, Loc))
1974 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001975 }
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Douglas Gregor2725ca82010-04-21 19:57:20 +00001977 // Check the argument types and determine the result type.
1978 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001979 ExprValueKind VK = VK_RValue;
1980
Douglas Gregor2725ca82010-04-21 19:57:20 +00001981 unsigned NumArgs = ArgsIn.size();
1982 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001983 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1984 SuperLoc.isValid(), LBracLoc, RBracLoc,
1985 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001986 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001987
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001988 if (Method && !Method->getResultType()->isVoidType() &&
1989 RequireCompleteType(LBracLoc, Method->getResultType(),
1990 diag::err_illegal_message_expr_incomplete_type))
1991 return ExprError();
1992
Douglas Gregor2725ca82010-04-21 19:57:20 +00001993 // Construct the appropriate ObjCMessageExpr.
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001994 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001995 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001996 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001997 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001998 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001999 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002000 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002001 else {
John McCallf89e55a2010-11-18 06:31:45 +00002002 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002003 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002004 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002005 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002006 if (!isImplicit)
2007 checkCocoaAPI(*this, Result);
2008 }
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002009 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00002010}
2011
Douglas Gregor2725ca82010-04-21 19:57:20 +00002012// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00002013// ArgExprs is optional - if it is present, the number of expressions
2014// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00002015ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00002016 ParsedType Receiver,
2017 Selector Sel,
2018 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002019 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor77328d12010-09-15 23:19:31 +00002020 SourceLocation RBracLoc,
2021 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002022 TypeSourceInfo *ReceiverTypeInfo;
2023 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2024 if (ReceiverType.isNull())
2025 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Douglas Gregor2725ca82010-04-21 19:57:20 +00002028 if (!ReceiverTypeInfo)
2029 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2030
2031 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00002032 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002033 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00002034}
2035
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002036ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2037 QualType ReceiverType,
2038 SourceLocation Loc,
2039 Selector Sel,
2040 ObjCMethodDecl *Method,
2041 MultiExprArg Args) {
2042 return BuildInstanceMessage(Receiver, ReceiverType,
2043 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2044 Sel, Method, Loc, Loc, Loc, Args,
2045 /*isImplicit=*/true);
2046}
2047
Douglas Gregor2725ca82010-04-21 19:57:20 +00002048/// \brief Build an Objective-C instance message expression.
2049///
2050/// This routine takes care of both normal instance messages and
2051/// instance messages to the superclass instance.
2052///
2053/// \param Receiver The expression that computes the object that will
2054/// receive this message. This may be empty, in which case we are
2055/// sending to the superclass instance and \p SuperLoc must be a valid
2056/// source location.
2057///
2058/// \param ReceiverType The (static) type of the object receiving the
2059/// message. When a \p Receiver expression is provided, this is the
2060/// same type as that expression. For a superclass instance send, this
2061/// is a pointer to the type of the superclass.
2062///
2063/// \param SuperLoc The location of the "super" keyword in a
2064/// superclass instance message.
2065///
2066/// \param Sel The selector to which the message is being sent.
2067///
Douglas Gregorf49bb082010-04-22 17:01:48 +00002068/// \param Method The method that this instance message is invoking, if
2069/// already known.
2070///
Douglas Gregor2725ca82010-04-21 19:57:20 +00002071/// \param LBracLoc The location of the opening square bracket ']'.
2072///
Douglas Gregor2725ca82010-04-21 19:57:20 +00002073/// \param RBrac The location of the closing square bracket ']'.
2074///
2075/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00002076ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002077 QualType ReceiverType,
2078 SourceLocation SuperLoc,
2079 Selector Sel,
2080 ObjCMethodDecl *Method,
2081 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002082 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002083 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002084 MultiExprArg ArgsIn,
2085 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00002086 // The location of the receiver.
2087 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2088
2089 if (LBracLoc.isInvalid()) {
2090 Diag(Loc, diag::err_missing_open_square_message_send)
2091 << FixItHint::CreateInsertion(Loc, "[");
2092 LBracLoc = Loc;
2093 }
2094
Douglas Gregor2725ca82010-04-21 19:57:20 +00002095 // If we have a receiver expression, perform appropriate promotions
2096 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00002097 if (Receiver) {
John McCall5acb0c92011-10-17 18:40:02 +00002098 if (Receiver->hasPlaceholderType()) {
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00002099 ExprResult Result;
2100 if (Receiver->getType() == Context.UnknownAnyTy)
2101 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2102 else
2103 Result = CheckPlaceholderExpr(Receiver);
2104 if (Result.isInvalid()) return ExprError();
2105 Receiver = Result.take();
John McCall5acb0c92011-10-17 18:40:02 +00002106 }
2107
Douglas Gregor92e986e2010-04-22 16:44:27 +00002108 if (Receiver->isTypeDependent()) {
2109 // If the receiver is type-dependent, we can't type-check anything
2110 // at this point. Build a dependent expression.
2111 unsigned NumArgs = ArgsIn.size();
2112 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2113 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2114 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00002115 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002116 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002117 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002118 RBracLoc, isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00002119 }
2120
Douglas Gregor2725ca82010-04-21 19:57:20 +00002121 // If necessary, apply function/array conversion to the receiver.
2122 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00002123 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2124 if (Result.isInvalid())
2125 return ExprError();
2126 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00002127 ReceiverType = Receiver->getType();
2128 }
2129
Douglas Gregorf49bb082010-04-22 17:01:48 +00002130 if (!Method) {
2131 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00002132 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002133 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00002134 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2135 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002136 SourceRange(LBracLoc, RBracLoc),
2137 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002138 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00002139 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002140 SourceRange(LBracLoc, RBracLoc),
2141 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002142 } else if (ReceiverType->isObjCClassType() ||
2143 ReceiverType->isObjCQualifiedClassType()) {
2144 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002145 // We allow sending a message to a qualified Class ("Class<foo>"), which
2146 // is ok as long as one of the protocols implements the selector (if not, warn).
2147 if (const ObjCObjectPointerType *QClassTy
2148 = ReceiverType->getAsObjCQualifiedClassType()) {
2149 // Search protocols for class methods.
2150 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2151 if (!Method) {
2152 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2153 // warn if instance method found for a Class message.
2154 if (Method) {
2155 Diag(Loc, diag::warn_instance_method_on_class_found)
2156 << Method->getSelector() << Sel;
Ted Kremenek3306ec12012-02-27 22:55:11 +00002157 Diag(Method->getLocation(), diag::note_method_declared_at)
2158 << Method->getDeclName();
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002159 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00002160 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002161 } else {
2162 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2163 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2164 // First check the public methods in the class interface.
2165 Method = ClassDecl->lookupClassMethod(Sel);
2166
2167 if (!Method)
2168 Method = LookupPrivateClassMethod(Sel, ClassDecl);
2169 }
2170 if (Method && DiagnoseUseOfDecl(Method, Loc))
2171 return ExprError();
2172 }
2173 if (!Method) {
2174 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00002175 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002176 Method = LookupFactoryMethodInGlobalPool(Sel,
2177 SourceRange(LBracLoc, RBracLoc),
2178 true);
2179 if (!Method) {
2180 // If no class (factory) method was found, check if an _instance_
2181 // method of the same name exists in the root class only.
2182 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002183 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002184 true);
2185 if (Method)
2186 if (const ObjCInterfaceDecl *ID =
2187 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2188 if (ID->getSuperClass())
2189 Diag(Loc, diag::warn_root_inst_method_not_found)
2190 << Sel << SourceRange(LBracLoc, RBracLoc);
2191 }
2192 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002193 }
2194 }
2195 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002196 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002197 ObjCInterfaceDecl* ClassDecl = 0;
2198
2199 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2200 // long as one of the protocols implements the selector (if not, warn).
2201 if (const ObjCObjectPointerType *QIdTy
2202 = ReceiverType->getAsObjCQualifiedIdType()) {
2203 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002204 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2205 if (!Method)
2206 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002207 } else if (const ObjCObjectPointerType *OCIType
2208 = ReceiverType->getAsObjCInterfacePointerType()) {
2209 // We allow sending a message to a pointer to an interface (an object).
2210 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00002211
Douglas Gregorb3029962011-11-14 22:10:01 +00002212 // Try to complete the type. Under ARC, this is a hard error from which
2213 // we don't try to recover.
2214 const ObjCInterfaceDecl *forwardClass = 0;
2215 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002216 getLangOpts().ObjCAutoRefCount
Douglas Gregord10099e2012-05-04 16:32:21 +00002217 ? diag::err_arc_receiver_forward_instance
2218 : diag::warn_receiver_forward_instance,
2219 Receiver? Receiver->getSourceRange()
2220 : SourceRange(SuperLoc))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002221 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregorb3029962011-11-14 22:10:01 +00002222 return ExprError();
2223
2224 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00002225 Diag(Receiver ? Receiver->getLocStart()
2226 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00002227 Method = 0;
2228 } else {
2229 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCallf85e1932011-06-15 23:02:42 +00002230 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002231
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002232 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002233 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002234 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2235
Douglas Gregorf49bb082010-04-22 17:01:48 +00002236 if (!Method) {
2237 // If we have implementations in scope, check "private" methods.
2238 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
2239
David Blaikie4e4d0842012-03-11 07:00:24 +00002240 if (!Method && getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002241 Diag(Loc, diag::err_arc_may_not_respond)
2242 << OCIType->getPointeeType() << Sel;
2243 return ExprError();
2244 }
2245
Douglas Gregorc737acb2011-09-27 16:10:05 +00002246 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002247 // If we still haven't found a method, look in the global pool. This
2248 // behavior isn't very desirable, however we need it for GCC
2249 // compatibility. FIXME: should we deviate??
2250 if (OCIType->qual_empty()) {
2251 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002252 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002253 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002254 Diag(Loc, diag::warn_maynot_respond)
2255 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
2256 }
2257 }
2258 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002259 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00002260 return ExprError();
David Blaikie4e4d0842012-03-11 07:00:24 +00002261 } else if (!getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002262 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00002263 (ReceiverType->isPointerType() ||
2264 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002265 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00002266 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00002267 Diag(Loc, diag::warn_bad_receiver_type)
2268 << ReceiverType
2269 << Receiver->getSourceRange();
2270 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00002271 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002272 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00002273 else {
2274 // TODO: specialized warning on null receivers?
2275 bool IsNull = Receiver->isNullPointerConstant(Context,
2276 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00002277 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2278 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00002279 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002280 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00002281 } else {
John Wiegley429bb272011-04-08 18:41:53 +00002282 ExprResult ReceiverRes;
David Blaikie4e4d0842012-03-11 07:00:24 +00002283 if (getLangOpts().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00002284 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00002285 if (ReceiverRes.isUsable()) {
2286 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00002287 return BuildInstanceMessage(Receiver,
2288 ReceiverType,
2289 SuperLoc,
2290 Sel,
2291 Method,
2292 LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002293 SelectorLocs,
John Wiegley429bb272011-04-08 18:41:53 +00002294 RBracLoc,
2295 move(ArgsIn));
2296 } else {
2297 // Reject other random receiver types (e.g. structs).
2298 Diag(Loc, diag::err_bad_receiver_type)
2299 << ReceiverType << Receiver->getSourceRange();
2300 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00002301 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002302 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002303 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00002304 }
Mike Stump1eb44332009-09-09 15:08:12 +00002305
Douglas Gregor2725ca82010-04-21 19:57:20 +00002306 // Check the message arguments.
2307 unsigned NumArgs = ArgsIn.size();
2308 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2309 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00002310 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00002311 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2312 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00002313 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
2314 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00002315 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00002316 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00002317
Douglas Gregor483dd2f2011-01-11 03:23:19 +00002318 if (Method && !Method->getResultType()->isVoidType() &&
2319 RequireCompleteType(LBracLoc, Method->getResultType(),
2320 diag::err_illegal_message_expr_incomplete_type))
2321 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002322
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002323 SourceLocation SelLoc = SelectorLocs.front();
2324
John McCallf85e1932011-06-15 23:02:42 +00002325 // In ARC, forbid the user from sending messages to
2326 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002327 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002328 ObjCMethodFamily family =
2329 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2330 switch (family) {
2331 case OMF_init:
2332 if (Method)
2333 checkInitMethod(Method, ReceiverType);
2334
2335 case OMF_None:
2336 case OMF_alloc:
2337 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00002338 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00002339 case OMF_mutableCopy:
2340 case OMF_new:
2341 case OMF_self:
2342 break;
2343
2344 case OMF_dealloc:
2345 case OMF_retain:
2346 case OMF_release:
2347 case OMF_autorelease:
2348 case OMF_retainCount:
2349 Diag(Loc, diag::err_arc_illegal_explicit_message)
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002350 << Sel << SelLoc;
John McCallf85e1932011-06-15 23:02:42 +00002351 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002352
2353 case OMF_performSelector:
2354 if (Method && NumArgs >= 1) {
2355 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2356 Selector ArgSel = SelExp->getSelector();
2357 ObjCMethodDecl *SelMethod =
2358 LookupInstanceMethodInGlobalPool(ArgSel,
2359 SelExp->getSourceRange());
2360 if (!SelMethod)
2361 SelMethod =
2362 LookupFactoryMethodInGlobalPool(ArgSel,
2363 SelExp->getSourceRange());
2364 if (SelMethod) {
2365 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2366 switch (SelFamily) {
2367 case OMF_alloc:
2368 case OMF_copy:
2369 case OMF_mutableCopy:
2370 case OMF_new:
2371 case OMF_self:
2372 case OMF_init:
2373 // Issue error, unless ns_returns_not_retained.
2374 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2375 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002376 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002377 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002378 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2379 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002380 }
2381 break;
2382 default:
2383 // +0 call. OK. unless ns_returns_retained.
2384 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2385 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002386 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002387 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002388 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2389 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002390 }
2391 break;
2392 }
2393 }
2394 } else {
2395 // error (may leak).
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002396 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002397 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2398 }
2399 }
2400 break;
John McCallf85e1932011-06-15 23:02:42 +00002401 }
2402 }
2403
Douglas Gregor2725ca82010-04-21 19:57:20 +00002404 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00002405 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00002406 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00002407 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002408 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002409 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002410 makeArrayRef(Args, NumArgs), RBracLoc,
2411 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002412 else {
John McCallf89e55a2010-11-18 06:31:45 +00002413 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002414 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002415 makeArrayRef(Args, NumArgs), RBracLoc,
2416 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002417 if (!isImplicit)
2418 checkCocoaAPI(*this, Result);
2419 }
John McCallf85e1932011-06-15 23:02:42 +00002420
David Blaikie4e4d0842012-03-11 07:00:24 +00002421 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian98795562012-04-19 23:49:39 +00002422 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian878f8502012-04-04 20:05:25 +00002423
John McCallf85e1932011-06-15 23:02:42 +00002424 // In ARC, annotate delegate init calls.
2425 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00002426 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00002427 // Only consider init calls *directly* in init implementations,
2428 // not within blocks.
2429 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2430 if (method && method->getMethodFamily() == OMF_init) {
2431 // The implicit assignment to self means we also don't want to
2432 // consume the result.
2433 Result->setDelegateInitCall(true);
2434 return Owned(Result);
2435 }
2436 }
2437
2438 // In ARC, check for message sends which are likely to introduce
2439 // retain cycles.
2440 checkRetainCycles(Result);
2441 }
2442
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002443 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00002444}
2445
2446// ActOnInstanceMessage - used for both unary and keyword messages.
2447// ArgExprs is optional - if it is present, the number of expressions
2448// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00002449ExprResult Sema::ActOnInstanceMessage(Scope *S,
2450 Expr *Receiver,
2451 Selector Sel,
2452 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002453 ArrayRef<SourceLocation> SelectorLocs,
John McCall60d7b3a2010-08-24 06:29:42 +00002454 SourceLocation RBracLoc,
2455 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002456 if (!Receiver)
2457 return ExprError();
2458
John McCall9ae2f072010-08-23 23:25:46 +00002459 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00002460 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002461 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00002462}
Chris Lattnereca7be62008-04-07 05:30:13 +00002463
John McCallf85e1932011-06-15 23:02:42 +00002464enum ARCConversionTypeClass {
John McCall2cf031d2011-10-01 01:01:08 +00002465 /// int, void, struct A
John McCallf85e1932011-06-15 23:02:42 +00002466 ACTC_none,
John McCall2cf031d2011-10-01 01:01:08 +00002467
2468 /// id, void (^)()
John McCallf85e1932011-06-15 23:02:42 +00002469 ACTC_retainable,
John McCall2cf031d2011-10-01 01:01:08 +00002470
2471 /// id*, id***, void (^*)(),
2472 ACTC_indirectRetainable,
2473
2474 /// void* might be a normal C type, or it might a CF type.
2475 ACTC_voidPtr,
2476
2477 /// struct A*
2478 ACTC_coreFoundation
John McCallf85e1932011-06-15 23:02:42 +00002479};
John McCall2cf031d2011-10-01 01:01:08 +00002480static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2481 return (ACTC == ACTC_retainable ||
2482 ACTC == ACTC_coreFoundation ||
2483 ACTC == ACTC_voidPtr);
2484}
2485static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2486 return ACTC == ACTC_none ||
2487 ACTC == ACTC_voidPtr ||
2488 ACTC == ACTC_coreFoundation;
2489}
2490
John McCallf85e1932011-06-15 23:02:42 +00002491static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCall2cf031d2011-10-01 01:01:08 +00002492 bool isIndirect = false;
John McCallf85e1932011-06-15 23:02:42 +00002493
2494 // Ignore an outermost reference type.
John McCall2cf031d2011-10-01 01:01:08 +00002495 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCallf85e1932011-06-15 23:02:42 +00002496 type = ref->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002497 isIndirect = true;
2498 }
John McCallf85e1932011-06-15 23:02:42 +00002499
2500 // Drill through pointers and arrays recursively.
2501 while (true) {
2502 if (const PointerType *ptr = type->getAs<PointerType>()) {
2503 type = ptr->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002504
2505 // The first level of pointer may be the innermost pointer on a CF type.
2506 if (!isIndirect) {
2507 if (type->isVoidType()) return ACTC_voidPtr;
2508 if (type->isRecordType()) return ACTC_coreFoundation;
2509 }
John McCallf85e1932011-06-15 23:02:42 +00002510 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2511 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2512 } else {
2513 break;
2514 }
John McCall2cf031d2011-10-01 01:01:08 +00002515 isIndirect = true;
John McCallf85e1932011-06-15 23:02:42 +00002516 }
2517
John McCall2cf031d2011-10-01 01:01:08 +00002518 if (isIndirect) {
2519 if (type->isObjCARCBridgableType())
2520 return ACTC_indirectRetainable;
2521 return ACTC_none;
2522 }
2523
2524 if (type->isObjCARCBridgableType())
2525 return ACTC_retainable;
2526
2527 return ACTC_none;
John McCallf85e1932011-06-15 23:02:42 +00002528}
2529
2530namespace {
John McCall2cf031d2011-10-01 01:01:08 +00002531 /// A result from the cast checker.
2532 enum ACCResult {
2533 /// Cannot be casted.
2534 ACC_invalid,
2535
2536 /// Can be safely retained or not retained.
2537 ACC_bottom,
2538
2539 /// Can be casted at +0.
2540 ACC_plusZero,
2541
2542 /// Can be casted at +1.
2543 ACC_plusOne
2544 };
2545 ACCResult merge(ACCResult left, ACCResult right) {
2546 if (left == right) return left;
2547 if (left == ACC_bottom) return right;
2548 if (right == ACC_bottom) return left;
2549 return ACC_invalid;
2550 }
2551
2552 /// A checker which white-lists certain expressions whose conversion
2553 /// to or from retainable type would otherwise be forbidden in ARC.
2554 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2555 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2556
John McCallf85e1932011-06-15 23:02:42 +00002557 ASTContext &Context;
John McCall2cf031d2011-10-01 01:01:08 +00002558 ARCConversionTypeClass SourceClass;
2559 ARCConversionTypeClass TargetClass;
2560
2561 static bool isCFType(QualType type) {
2562 // Someday this can use ns_bridged. For now, it has to do this.
2563 return type->isCARCBridgableType();
John McCallf85e1932011-06-15 23:02:42 +00002564 }
John McCall2cf031d2011-10-01 01:01:08 +00002565
2566 public:
2567 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2568 ARCConversionTypeClass target)
2569 : Context(Context), SourceClass(source), TargetClass(target) {}
2570
2571 using super::Visit;
2572 ACCResult Visit(Expr *e) {
2573 return super::Visit(e->IgnoreParens());
2574 }
2575
2576 ACCResult VisitStmt(Stmt *s) {
2577 return ACC_invalid;
2578 }
2579
2580 /// Null pointer constants can be casted however you please.
2581 ACCResult VisitExpr(Expr *e) {
2582 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2583 return ACC_bottom;
2584 return ACC_invalid;
2585 }
2586
2587 /// Objective-C string literals can be safely casted.
2588 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2589 // If we're casting to any retainable type, go ahead. Global
2590 // strings are immune to retains, so this is bottom.
2591 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2592
2593 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002594 }
2595
John McCall2cf031d2011-10-01 01:01:08 +00002596 /// Look through certain implicit and explicit casts.
2597 ACCResult VisitCastExpr(CastExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002598 switch (e->getCastKind()) {
2599 case CK_NullToPointer:
John McCall2cf031d2011-10-01 01:01:08 +00002600 return ACC_bottom;
2601
John McCallf85e1932011-06-15 23:02:42 +00002602 case CK_NoOp:
2603 case CK_LValueToRValue:
2604 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002605 case CK_CPointerToObjCPointerCast:
2606 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002607 case CK_AnyPointerToBlockPointerCast:
2608 return Visit(e->getSubExpr());
John McCall2cf031d2011-10-01 01:01:08 +00002609
John McCallf85e1932011-06-15 23:02:42 +00002610 default:
John McCall2cf031d2011-10-01 01:01:08 +00002611 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002612 }
2613 }
John McCall2cf031d2011-10-01 01:01:08 +00002614
2615 /// Look through unary extension.
2616 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002617 return Visit(e->getSubExpr());
2618 }
John McCall2cf031d2011-10-01 01:01:08 +00002619
2620 /// Ignore the LHS of a comma operator.
2621 ACCResult VisitBinComma(BinaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002622 return Visit(e->getRHS());
2623 }
John McCall2cf031d2011-10-01 01:01:08 +00002624
2625 /// Conditional operators are okay if both sides are okay.
2626 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2627 ACCResult left = Visit(e->getTrueExpr());
2628 if (left == ACC_invalid) return ACC_invalid;
2629 return merge(left, Visit(e->getFalseExpr()));
John McCallf85e1932011-06-15 23:02:42 +00002630 }
John McCall2cf031d2011-10-01 01:01:08 +00002631
John McCall4b9c2d22011-11-06 09:01:30 +00002632 /// Look through pseudo-objects.
2633 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2634 // If we're getting here, we should always have a result.
2635 return Visit(e->getResultExpr());
2636 }
2637
John McCall2cf031d2011-10-01 01:01:08 +00002638 /// Statement expressions are okay if their result expression is okay.
2639 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002640 return Visit(e->getSubStmt()->body_back());
2641 }
John McCallf85e1932011-06-15 23:02:42 +00002642
John McCall2cf031d2011-10-01 01:01:08 +00002643 /// Some declaration references are okay.
2644 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2645 // References to global constants from system headers are okay.
2646 // These are things like 'kCFStringTransformToLatin'. They are
2647 // can also be assumed to be immune to retains.
2648 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2649 if (isAnyRetainable(TargetClass) &&
2650 isAnyRetainable(SourceClass) &&
2651 var &&
2652 var->getStorageClass() == SC_Extern &&
2653 var->getType().isConstQualified() &&
2654 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2655 return ACC_bottom;
2656 }
2657
2658 // Nothing else.
2659 return ACC_invalid;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00002660 }
John McCall2cf031d2011-10-01 01:01:08 +00002661
2662 /// Some calls are okay.
2663 ACCResult VisitCallExpr(CallExpr *e) {
2664 if (FunctionDecl *fn = e->getDirectCallee())
2665 if (ACCResult result = checkCallToFunction(fn))
2666 return result;
2667
2668 return super::VisitCallExpr(e);
2669 }
2670
2671 ACCResult checkCallToFunction(FunctionDecl *fn) {
2672 // Require a CF*Ref return type.
2673 if (!isCFType(fn->getResultType()))
2674 return ACC_invalid;
2675
2676 if (!isAnyRetainable(TargetClass))
2677 return ACC_invalid;
2678
2679 // Honor an explicit 'not retained' attribute.
2680 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2681 return ACC_plusZero;
2682
2683 // Honor an explicit 'retained' attribute, except that for
2684 // now we're not going to permit implicit handling of +1 results,
2685 // because it's a bit frightening.
2686 if (fn->hasAttr<CFReturnsRetainedAttr>())
2687 return ACC_invalid; // ACC_plusOne if we start accepting this
2688
2689 // Recognize this specific builtin function, which is used by CFSTR.
2690 unsigned builtinID = fn->getBuiltinID();
2691 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2692 return ACC_bottom;
2693
2694 // Otherwise, don't do anything implicit with an unaudited function.
2695 if (!fn->hasAttr<CFAuditedTransferAttr>())
2696 return ACC_invalid;
2697
2698 // Otherwise, it's +0 unless it follows the create convention.
2699 if (ento::coreFoundation::followsCreateRule(fn))
2700 return ACC_invalid; // ACC_plusOne if we start accepting this
2701
2702 return ACC_plusZero;
2703 }
2704
2705 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2706 return checkCallToMethod(e->getMethodDecl());
2707 }
2708
2709 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2710 ObjCMethodDecl *method;
2711 if (e->isExplicitProperty())
2712 method = e->getExplicitProperty()->getGetterMethodDecl();
2713 else
2714 method = e->getImplicitPropertyGetter();
2715 return checkCallToMethod(method);
2716 }
2717
2718 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2719 if (!method) return ACC_invalid;
2720
2721 // Check for message sends to functions returning CF types. We
2722 // just obey the Cocoa conventions with these, even though the
2723 // return type is CF.
2724 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2725 return ACC_invalid;
2726
2727 // If the method is explicitly marked not-retained, it's +0.
2728 if (method->hasAttr<CFReturnsNotRetainedAttr>())
2729 return ACC_plusZero;
2730
2731 // If the method is explicitly marked as returning retained, or its
2732 // selector follows a +1 Cocoa convention, treat it as +1.
2733 if (method->hasAttr<CFReturnsRetainedAttr>())
2734 return ACC_plusOne;
2735
2736 switch (method->getSelector().getMethodFamily()) {
2737 case OMF_alloc:
2738 case OMF_copy:
2739 case OMF_mutableCopy:
2740 case OMF_new:
2741 return ACC_plusOne;
2742
2743 default:
2744 // Otherwise, treat it as +0.
2745 return ACC_plusZero;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00002746 }
2747 }
John McCall2cf031d2011-10-01 01:01:08 +00002748 };
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00002749}
2750
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002751static bool
2752KnownName(Sema &S, const char *name) {
2753 LookupResult R(S, &S.Context.Idents.get(name), SourceLocation(),
2754 Sema::LookupOrdinaryName);
2755 return S.LookupName(R, S.TUScope, false);
2756}
2757
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002758static void addFixitForObjCARCConversion(Sema &S,
2759 DiagnosticBuilder &DiagB,
2760 Sema::CheckedConversionKind CCK,
2761 SourceLocation afterLParen,
2762 QualType castType,
2763 Expr *castExpr,
2764 const char *bridgeKeyword,
2765 const char *CFBridgeName) {
2766 // We handle C-style and implicit casts here.
2767 switch (CCK) {
2768 case Sema::CCK_ImplicitConversion:
2769 case Sema::CCK_CStyleCast:
2770 break;
2771 case Sema::CCK_FunctionalCast:
2772 case Sema::CCK_OtherCast:
2773 return;
2774 }
2775
2776 if (CFBridgeName) {
2777 Expr *castedE = castExpr;
2778 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2779 castedE = CCE->getSubExpr();
2780 castedE = castedE->IgnoreImpCasts();
2781 SourceRange range = castedE->getSourceRange();
2782 if (isa<ParenExpr>(castedE)) {
2783 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2784 CFBridgeName));
2785 } else {
2786 std::string namePlusParen = CFBridgeName;
2787 namePlusParen += "(";
2788 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2789 namePlusParen));
2790 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2791 S.PP.getLocForEndOfToken(range.getEnd()),
2792 ")"));
2793 }
2794 return;
2795 }
2796
2797 if (CCK == Sema::CCK_CStyleCast) {
2798 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
2799 } else {
2800 std::string castCode = "(";
2801 castCode += bridgeKeyword;
2802 castCode += castType.getAsString();
2803 castCode += ")";
2804 Expr *castedE = castExpr->IgnoreImpCasts();
2805 SourceRange range = castedE->getSourceRange();
2806 if (isa<ParenExpr>(castedE)) {
2807 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2808 castCode));
2809 } else {
2810 castCode += "(";
2811 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2812 castCode));
2813 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2814 S.PP.getLocForEndOfToken(range.getEnd()),
2815 ")"));
2816 }
2817 }
2818}
2819
John McCall5acb0c92011-10-17 18:40:02 +00002820static void
2821diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
2822 QualType castType, ARCConversionTypeClass castACTC,
2823 Expr *castExpr, ARCConversionTypeClass exprACTC,
2824 Sema::CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00002825 SourceLocation loc =
John McCall2cf031d2011-10-01 01:01:08 +00002826 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00002827
John McCall5acb0c92011-10-17 18:40:02 +00002828 if (S.makeUnavailableInSystemHeader(loc,
John McCall2cf031d2011-10-01 01:01:08 +00002829 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCallf85e1932011-06-15 23:02:42 +00002830 return;
John McCall5acb0c92011-10-17 18:40:02 +00002831
2832 QualType castExprType = castExpr->getType();
John McCallf85e1932011-06-15 23:02:42 +00002833
John McCall71c482c2011-06-17 06:50:50 +00002834 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00002835 switch (exprACTC) {
John McCall2cf031d2011-10-01 01:01:08 +00002836 case ACTC_none:
2837 case ACTC_coreFoundation:
2838 case ACTC_voidPtr:
2839 srcKind = (castExprType->isPointerType() ? 1 : 0);
2840 break;
2841 case ACTC_retainable:
2842 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
2843 break;
2844 case ACTC_indirectRetainable:
2845 srcKind = 4;
2846 break;
John McCallf85e1932011-06-15 23:02:42 +00002847 }
2848
John McCall5acb0c92011-10-17 18:40:02 +00002849 // Check whether this could be fixed with a bridge cast.
2850 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
2851 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCallf85e1932011-06-15 23:02:42 +00002852
John McCall5acb0c92011-10-17 18:40:02 +00002853 // Bridge from an ARC type to a CF type.
2854 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002855
John McCall5acb0c92011-10-17 18:40:02 +00002856 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2857 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2858 << 2 // of C pointer type
2859 << castExprType
2860 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
2861 << castType
2862 << castRange
2863 << castExpr->getSourceRange();
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002864 bool br = KnownName(S, "CFBridgingRelease");
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002865 {
2866 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2867 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2868 castType, castExpr, "__bridge ", 0);
2869 }
2870 {
2871 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_transfer)
2872 << castExprType << br;
2873 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2874 castType, castExpr, "__bridge_transfer ",
2875 br ? "CFBridgingRelease" : 0);
2876 }
John McCall5acb0c92011-10-17 18:40:02 +00002877
2878 return;
2879 }
2880
2881 // Bridge from a CF type to an ARC type.
2882 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002883 bool br = KnownName(S, "CFBridgingRetain");
John McCall5acb0c92011-10-17 18:40:02 +00002884 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2885 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2886 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
2887 << castExprType
2888 << 2 // to C pointer type
2889 << castType
2890 << castRange
2891 << castExpr->getSourceRange();
2892
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002893 {
2894 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2895 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2896 castType, castExpr, "__bridge ", 0);
2897 }
2898 {
2899 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_retained)
2900 << castType << br;
2901 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2902 castType, castExpr, "__bridge_retained ",
2903 br ? "CFBridgingRetain" : 0);
2904 }
John McCall5acb0c92011-10-17 18:40:02 +00002905
2906 return;
John McCallf85e1932011-06-15 23:02:42 +00002907 }
2908
John McCall5acb0c92011-10-17 18:40:02 +00002909 S.Diag(loc, diag::err_arc_mismatched_cast)
2910 << (CCK != Sema::CCK_ImplicitConversion)
2911 << srcKind << castExprType << castType
John McCallf85e1932011-06-15 23:02:42 +00002912 << castRange << castExpr->getSourceRange();
2913}
2914
John McCall5acb0c92011-10-17 18:40:02 +00002915Sema::ARCConversionResult
2916Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
2917 Expr *&castExpr, CheckedConversionKind CCK) {
2918 QualType castExprType = castExpr->getType();
2919
2920 // For the purposes of the classification, we assume reference types
2921 // will bind to temporaries.
2922 QualType effCastType = castType;
2923 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
2924 effCastType = ref->getPointeeType();
2925
2926 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
2927 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002928 if (exprACTC == castACTC) {
2929 // check for viablity and report error if casting an rvalue to a
2930 // life-time qualifier.
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002931 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002932 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002933 (castType != castExprType)) {
2934 const Type *DT = castType.getTypePtr();
2935 QualType QDT = castType;
2936 // We desugar some types but not others. We ignore those
2937 // that cannot happen in a cast; i.e. auto, and those which
2938 // should not be de-sugared; i.e typedef.
2939 if (const ParenType *PT = dyn_cast<ParenType>(DT))
2940 QDT = PT->desugar();
2941 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
2942 QDT = TP->desugar();
2943 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
2944 QDT = AT->desugar();
2945 if (QDT != castType &&
2946 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
2947 SourceLocation loc =
2948 (castRange.isValid() ? castRange.getBegin()
2949 : castExpr->getExprLoc());
2950 Diag(loc, diag::err_arc_nolifetime_behavior);
2951 }
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002952 }
2953 return ACR_okay;
2954 }
2955
John McCall5acb0c92011-10-17 18:40:02 +00002956 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
2957
2958 // Allow all of these types to be cast to integer types (but not
2959 // vice-versa).
2960 if (castACTC == ACTC_none && castType->isIntegralType(Context))
2961 return ACR_okay;
2962
2963 // Allow casts between pointers to lifetime types (e.g., __strong id*)
2964 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
2965 // must be explicit.
2966 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
2967 return ACR_okay;
2968 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
2969 CCK != CCK_ImplicitConversion)
2970 return ACR_okay;
2971
2972 switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
2973 // For invalid casts, fall through.
2974 case ACC_invalid:
2975 break;
2976
2977 // Do nothing for both bottom and +0.
2978 case ACC_bottom:
2979 case ACC_plusZero:
2980 return ACR_okay;
2981
2982 // If the result is +1, consume it here.
2983 case ACC_plusOne:
2984 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
2985 CK_ARCConsumeObject, castExpr,
2986 0, VK_RValue);
2987 ExprNeedsCleanups = true;
2988 return ACR_okay;
2989 }
2990
2991 // If this is a non-implicit cast from id or block type to a
2992 // CoreFoundation type, delay complaining in case the cast is used
2993 // in an acceptable context.
2994 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
2995 CCK != CCK_ImplicitConversion)
2996 return ACR_unbridged;
2997
2998 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2999 castExpr, exprACTC, CCK);
3000 return ACR_okay;
3001}
3002
3003/// Given that we saw an expression with the ARCUnbridgedCastTy
3004/// placeholder type, complain bitterly.
3005void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3006 // We expect the spurious ImplicitCastExpr to already have been stripped.
3007 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3008 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3009
3010 SourceRange castRange;
3011 QualType castType;
3012 CheckedConversionKind CCK;
3013
3014 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3015 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3016 castType = cast->getTypeAsWritten();
3017 CCK = CCK_CStyleCast;
3018 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3019 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3020 castType = cast->getTypeAsWritten();
3021 CCK = CCK_OtherCast;
3022 } else {
3023 castType = cast->getType();
3024 CCK = CCK_ImplicitConversion;
3025 }
3026
3027 ARCConversionTypeClass castACTC =
3028 classifyTypeForARCConversion(castType.getNonReferenceType());
3029
3030 Expr *castExpr = realCast->getSubExpr();
3031 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3032
3033 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3034 castExpr, ACTC_retainable, CCK);
3035}
3036
3037/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3038/// type, remove the placeholder cast.
3039Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3040 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3041
3042 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3043 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3044 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3045 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3046 assert(uo->getOpcode() == UO_Extension);
3047 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3048 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3049 sub->getValueKind(), sub->getObjectKind(),
3050 uo->getOperatorLoc());
3051 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3052 assert(!gse->isResultDependent());
3053
3054 unsigned n = gse->getNumAssocs();
3055 SmallVector<Expr*, 4> subExprs(n);
3056 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3057 for (unsigned i = 0; i != n; ++i) {
3058 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3059 Expr *sub = gse->getAssocExpr(i);
3060 if (i == gse->getResultIndex())
3061 sub = stripARCUnbridgedCast(sub);
3062 subExprs[i] = sub;
3063 }
3064
3065 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3066 gse->getControllingExpr(),
3067 subTypes.data(), subExprs.data(),
3068 n, gse->getDefaultLoc(),
3069 gse->getRParenLoc(),
3070 gse->containsUnexpandedParameterPack(),
3071 gse->getResultIndex());
3072 } else {
3073 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3074 return cast<ImplicitCastExpr>(e)->getSubExpr();
3075 }
3076}
3077
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00003078bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3079 QualType exprType) {
3080 QualType canCastType =
3081 Context.getCanonicalType(castType).getUnqualifiedType();
3082 QualType canExprType =
3083 Context.getCanonicalType(exprType).getUnqualifiedType();
3084 if (isa<ObjCObjectPointerType>(canCastType) &&
3085 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3086 canExprType->isObjCObjectPointerType()) {
3087 if (const ObjCObjectPointerType *ObjT =
3088 canExprType->getAs<ObjCObjectPointerType>())
3089 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
3090 return false;
3091 }
3092 return true;
3093}
3094
John McCall7e5e5f42011-07-07 06:58:02 +00003095/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3096static Expr *maybeUndoReclaimObject(Expr *e) {
3097 // For now, we just undo operands that are *immediately* reclaim
3098 // expressions, which prevents the vast majority of potential
3099 // problems here. To catch them all, we'd need to rebuild arbitrary
3100 // value-propagating subexpressions --- we can't reliably rebuild
3101 // in-place because of expression sharing.
3102 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00003103 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00003104 return ice->getSubExpr();
3105
3106 return e;
3107}
3108
John McCallf85e1932011-06-15 23:02:42 +00003109ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3110 ObjCBridgeCastKind Kind,
3111 SourceLocation BridgeKeywordLoc,
3112 TypeSourceInfo *TSInfo,
3113 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00003114 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3115 if (SubResult.isInvalid()) return ExprError();
3116 SubExpr = SubResult.take();
3117
John McCallf85e1932011-06-15 23:02:42 +00003118 QualType T = TSInfo->getType();
3119 QualType FromType = SubExpr->getType();
3120
John McCall1d9b3b22011-09-09 05:25:32 +00003121 CastKind CK;
3122
John McCallf85e1932011-06-15 23:02:42 +00003123 bool MustConsume = false;
3124 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3125 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00003126 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00003127 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3128 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00003129 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3130 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00003131 switch (Kind) {
3132 case OBC_Bridge:
3133 break;
3134
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003135 case OBC_BridgeRetained: {
3136 bool br = KnownName(*this, "CFBridgingRelease");
John McCallf85e1932011-06-15 23:02:42 +00003137 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3138 << 2
3139 << FromType
3140 << (T->isBlockPointerType()? 1 : 0)
3141 << T
3142 << SubExpr->getSourceRange()
3143 << Kind;
3144 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3145 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3146 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003147 << FromType << br
John McCallf85e1932011-06-15 23:02:42 +00003148 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003149 br ? "CFBridgingRelease "
3150 : "__bridge_transfer ");
John McCallf85e1932011-06-15 23:02:42 +00003151
3152 Kind = OBC_Bridge;
3153 break;
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003154 }
John McCallf85e1932011-06-15 23:02:42 +00003155
3156 case OBC_BridgeTransfer:
3157 // We must consume the Objective-C object produced by the cast.
3158 MustConsume = true;
3159 break;
3160 }
3161 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3162 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00003163 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00003164 switch (Kind) {
3165 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00003166 // Reclaiming a value that's going to be __bridge-casted to CF
3167 // is very dangerous, so we don't do it.
3168 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00003169 break;
3170
3171 case OBC_BridgeRetained:
3172 // Produce the object before casting it.
3173 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00003174 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00003175 SubExpr, 0, VK_RValue);
3176 break;
3177
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003178 case OBC_BridgeTransfer: {
3179 bool br = KnownName(*this, "CFBridgingRetain");
John McCallf85e1932011-06-15 23:02:42 +00003180 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3181 << (FromType->isBlockPointerType()? 1 : 0)
3182 << FromType
3183 << 2
3184 << T
3185 << SubExpr->getSourceRange()
3186 << Kind;
3187
3188 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3189 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3190 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003191 << T << br
3192 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3193 br ? "CFBridgingRetain " : "__bridge_retained");
John McCallf85e1932011-06-15 23:02:42 +00003194
3195 Kind = OBC_Bridge;
3196 break;
3197 }
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003198 }
John McCallf85e1932011-06-15 23:02:42 +00003199 } else {
3200 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3201 << FromType << T << Kind
3202 << SubExpr->getSourceRange()
3203 << TSInfo->getTypeLoc().getSourceRange();
3204 return ExprError();
3205 }
3206
John McCall1d9b3b22011-09-09 05:25:32 +00003207 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00003208 BridgeKeywordLoc,
3209 TSInfo, SubExpr);
3210
3211 if (MustConsume) {
3212 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00003213 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00003214 0, VK_RValue);
3215 }
3216
3217 return Result;
3218}
3219
3220ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3221 SourceLocation LParenLoc,
3222 ObjCBridgeCastKind Kind,
3223 SourceLocation BridgeKeywordLoc,
3224 ParsedType Type,
3225 SourceLocation RParenLoc,
3226 Expr *SubExpr) {
3227 TypeSourceInfo *TSInfo = 0;
3228 QualType T = GetTypeFromParser(Type, &TSInfo);
3229 if (!TSInfo)
3230 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3231 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3232 SubExpr);
3233}