blob: 12f5dc72884e20132ea689caf0c4302ee8a7bbec [file] [log] [blame]
Chris Lattner85a932e2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000016#include "clang/Sema/Scope.h"
John McCall26743b22011-02-03 09:00:02 +000017#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000018#include "clang/Sema/Initialization.h"
John McCall2cf031d2011-10-01 01:01:08 +000019#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
Ted Kremenekebcb57a2012-03-06 20:05:56 +000020#include "clang/Edit/Rewriters.h"
21#include "clang/Edit/Commit.h"
Chris Lattner85a932e2008-01-04 22:32:30 +000022#include "clang/AST/ASTContext.h"
23#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000024#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000025#include "clang/AST/StmtVisitor.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000026#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000027#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000028#include "clang/Lex/Preprocessor.h"
29
Chris Lattner85a932e2008-01-04 22:32:30 +000030using namespace clang;
John McCall26743b22011-02-03 09:00:02 +000031using namespace sema;
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +000032using llvm::makeArrayRef;
Chris Lattner85a932e2008-01-04 22:32:30 +000033
John McCallf312b1e2010-08-26 23:41:50 +000034ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
35 Expr **strings,
36 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000037 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
38
Chris Lattnerf4b136f2009-02-18 06:13:04 +000039 // Most ObjC strings are formed out of a single piece. However, we *can*
40 // have strings formed out of multiple @ strings with multiple pptokens in
41 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
42 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner39c28bb2009-02-18 06:48:40 +000043 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000044
Chris Lattnerf4b136f2009-02-18 06:13:04 +000045 // If we have a multi-part string, merge it all together.
46 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000047 // Concatenate objc strings.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000048 SmallString<128> StrBuf;
Chris Lattner5f9e2722011-07-23 10:55:15 +000049 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000050
Chris Lattner726e1682009-02-18 05:49:11 +000051 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000052 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000053
Douglas Gregor5cee1192011-07-27 05:40:30 +000054 // ObjC strings can't be wide or UTF.
55 if (!S->isAscii()) {
Chris Lattnerf4b136f2009-02-18 06:13:04 +000056 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
57 << S->getSourceRange();
58 return true;
59 }
Mike Stump1eb44332009-09-09 15:08:12 +000060
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +000061 // Append the string.
62 StrBuf += S->getString();
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattner39c28bb2009-02-18 06:48:40 +000064 // Get the locations of the string tokens.
65 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattner85a932e2008-01-04 22:32:30 +000066 }
Mike Stump1eb44332009-09-09 15:08:12 +000067
Chris Lattner39c28bb2009-02-18 06:48:40 +000068 // Create the aggregate string with the appropriate content and location
69 // information.
Jay Foad65aa6882011-06-21 15:13:30 +000070 S = StringLiteral::Create(Context, StrBuf,
Douglas Gregor5cee1192011-07-27 05:40:30 +000071 StringLiteral::Ascii, /*Pascal=*/false,
Chris Lattner2085fd62009-02-18 06:40:38 +000072 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000073 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000074 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +000075
76 return BuildObjCStringLiteral(AtLocs[0], S);
77}
Mike Stump1eb44332009-09-09 15:08:12 +000078
Ted Kremenekebcb57a2012-03-06 20:05:56 +000079ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){
Chris Lattner69039812009-02-18 06:01:06 +000080 // Verify that this composite string is acceptable for ObjC strings.
81 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000082 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000083
84 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000085 // the NSString interface is seen in this translation unit. Note: We
86 // don't use NSConstantString, since the runtime team considers this
87 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000088 QualType Ty = Context.getObjCConstantStringInterface();
89 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000090 Ty = Context.getObjCObjectPointerType(Ty);
David Blaikie4e4d0842012-03-11 07:00:24 +000091 } else if (getLangOpts().NoConstantCFStrings) {
Fariborz Jahanian4c733072010-10-19 17:19:29 +000092 IdentifierInfo *NSIdent=0;
David Blaikie4e4d0842012-03-11 07:00:24 +000093 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Fariborz Jahanian4c733072010-10-19 17:19:29 +000094
95 if (StringClass.empty())
96 NSIdent = &Context.Idents.get("NSConstantString");
97 else
98 NSIdent = &Context.Idents.get(StringClass);
99
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000100 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Fariborz Jahanian8a437762010-04-23 23:19:04 +0000101 LookupOrdinaryName);
102 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
103 Context.setObjCConstantStringInterface(StrIF);
104 Ty = Context.getObjCConstantStringInterface();
105 Ty = Context.getObjCObjectPointerType(Ty);
106 } else {
107 // If there is no NSConstantString interface defined then treat this
108 // as error and recover from it.
109 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
110 << S->getSourceRange();
111 Ty = Context.getObjCIdType();
112 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000113 } else {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000114 IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000115 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc,
Douglas Gregorc83c6872010-04-15 22:33:43 +0000116 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000117 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
118 Context.setObjCConstantStringInterface(StrIF);
119 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000120 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000121 } else {
Fariborz Jahanianf64bc202012-02-23 22:51:36 +0000122 // If there is no NSString interface defined, implicitly declare
123 // a @class NSString; and use that instead. This is to make sure
124 // type of an NSString literal is represented correctly, instead of
125 // being an 'id' type.
126 Ty = Context.getObjCNSStringType();
127 if (Ty.isNull()) {
128 ObjCInterfaceDecl *NSStringIDecl =
129 ObjCInterfaceDecl::Create (Context,
130 Context.getTranslationUnitDecl(),
131 SourceLocation(), NSIdent,
132 0, SourceLocation());
133 Ty = Context.getObjCInterfaceType(NSStringIDecl);
134 Context.setObjCNSStringType(Ty);
135 }
136 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000137 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000138 }
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000140 return new (Context) ObjCStringLiteral(S, Ty, AtLoc);
141}
142
143/// \brief Retrieve the NSNumber factory method that should be used to create
144/// an Objective-C literal for the given type.
145static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc,
Patrick Beardeb382ec2012-04-19 00:25:12 +0000146 QualType NumberType,
147 bool isLiteral = false,
148 SourceRange R = SourceRange()) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000149 llvm::Optional<NSAPI::NSNumberLiteralMethodKind> Kind
Patrick Beardeb382ec2012-04-19 00:25:12 +0000150 = S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000151
152 if (!Kind) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000153 if (isLiteral) {
154 S.Diag(Loc, diag::err_invalid_nsnumber_type)
155 << NumberType << R;
156 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000157 return 0;
158 }
Patrick Beardeb382ec2012-04-19 00:25:12 +0000159
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000160 // If we already looked up this method, we're done.
161 if (S.NSNumberLiteralMethods[*Kind])
162 return S.NSNumberLiteralMethods[*Kind];
163
164 Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind,
165 /*Instance=*/false);
166
Patrick Beardeb382ec2012-04-19 00:25:12 +0000167 ASTContext &CX = S.Context;
168
169 // Look up the NSNumber class, if we haven't done so already. It's cached
170 // in the Sema instance.
171 if (!S.NSNumberDecl) {
172 IdentifierInfo *NSNumberId = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber);
173 NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId,
174 Loc, Sema::LookupOrdinaryName);
175 S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
176 if (!S.NSNumberDecl) {
177 if (S.getLangOpts().DebuggerObjCLiteral) {
178 // Create a stub definition of NSNumber.
179 S.NSNumberDecl = ObjCInterfaceDecl::Create (CX,
180 CX.getTranslationUnitDecl(),
181 SourceLocation(), NSNumberId,
182 0, SourceLocation());
183 } else {
184 // Otherwise, require a declaration of NSNumber.
185 S.Diag(Loc, diag::err_undeclared_nsnumber);
186 return 0;
187 }
188 } else if (!S.NSNumberDecl->hasDefinition()) {
189 S.Diag(Loc, diag::err_undeclared_nsnumber);
190 return 0;
191 }
192
193 // generate the pointer to NSNumber type.
194 S.NSNumberPointer = CX.getObjCObjectPointerType(CX.getObjCInterfaceType(S.NSNumberDecl));
195 }
196
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000197 // Look for the appropriate method within NSNumber.
198 ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel);;
David Blaikie4e4d0842012-03-11 07:00:24 +0000199 if (!Method && S.getLangOpts().DebuggerObjCLiteral) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000200 // create a stub definition this NSNumber factory method.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000201 TypeSourceInfo *ResultTInfo = 0;
Patrick Beardeb382ec2012-04-19 00:25:12 +0000202 Method = ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel,
203 S.NSNumberPointer, ResultTInfo, S.NSNumberDecl,
204 /*isInstance=*/false, /*isVariadic=*/false,
205 /*isSynthesized=*/false,
206 /*isImplicitlyDeclared=*/true,
207 /*isDefined=*/false, ObjCMethodDecl::Required,
208 /*HasRelatedResultType=*/false);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000209 ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method,
210 SourceLocation(), SourceLocation(),
Patrick Beardeb382ec2012-04-19 00:25:12 +0000211 &CX.Idents.get("value"),
212 NumberType, /*TInfo=*/0, SC_None, SC_None, 0);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000213 Method->setMethodParams(S.Context, value, ArrayRef<SourceLocation>());
214 }
215
216 if (!Method) {
217 S.Diag(Loc, diag::err_undeclared_nsnumber_method) << Sel;
218 return 0;
219 }
220
221 // Make sure the return type is reasonable.
222 if (!Method->getResultType()->isObjCObjectPointerType()) {
223 S.Diag(Loc, diag::err_objc_literal_method_sig)
224 << Sel;
225 S.Diag(Method->getLocation(), diag::note_objc_literal_method_return)
226 << Method->getResultType();
227 return 0;
228 }
229
230 // Note: if the parameter type is out-of-line, we'll catch it later in the
231 // implicit conversion.
232
233 S.NSNumberLiteralMethods[*Kind] = Method;
234 return Method;
235}
236
Patrick Beardeb382ec2012-04-19 00:25:12 +0000237/// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the
238/// numeric literal expression. Type of the expression will be "NSNumber *".
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000239ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) {
Patrick Beardeb382ec2012-04-19 00:25:12 +0000240 // compute the effective range of the literal, including the leading '@'.
241 SourceRange SR(AtLoc, Number->getSourceRange().getEnd());
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000242
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000243 // Determine the type of the literal.
244 QualType NumberType = Number->getType();
245 if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) {
246 // In C, character literals have type 'int'. That's not the type we want
247 // to use to determine the Objective-c literal kind.
248 switch (Char->getKind()) {
249 case CharacterLiteral::Ascii:
250 NumberType = Context.CharTy;
251 break;
252
253 case CharacterLiteral::Wide:
254 NumberType = Context.getWCharType();
255 break;
256
257 case CharacterLiteral::UTF16:
258 NumberType = Context.Char16Ty;
259 break;
260
261 case CharacterLiteral::UTF32:
262 NumberType = Context.Char32Ty;
263 break;
264 }
265 }
266
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000267 // Look for the appropriate method within NSNumber.
268 // Construct the literal.
Patrick Beardeb382ec2012-04-19 00:25:12 +0000269 ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType,
270 true, Number->getSourceRange());
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000271 if (!Method)
272 return ExprError();
273
274 // Convert the number to the type that the parameter expects.
Patrick Beardeb382ec2012-04-19 00:25:12 +0000275 QualType ArgType = Method->param_begin()[0]->getType();
276 ExprResult ConvertedNumber = PerformImplicitConversion(Number, ArgType,
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000277 AA_Sending);
278 if (ConvertedNumber.isInvalid())
279 return ExprError();
280 Number = ConvertedNumber.get();
281
282 return MaybeBindToTemporary(
Patrick Beardeb382ec2012-04-19 00:25:12 +0000283 new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method, SR));
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000284}
285
286ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc,
287 SourceLocation ValueLoc,
288 bool Value) {
289 ExprResult Inner;
David Blaikie4e4d0842012-03-11 07:00:24 +0000290 if (getLangOpts().CPlusPlus) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000291 Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false);
292 } else {
293 // C doesn't actually have a way to represent literal values of type
294 // _Bool. So, we'll use 0/1 and implicit cast to _Bool.
295 Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0);
296 Inner = ImpCastExprToType(Inner.get(), Context.BoolTy,
297 CK_IntegralToBoolean);
298 }
299
300 return BuildObjCNumericLiteral(AtLoc, Inner.get());
301}
302
303/// \brief Check that the given expression is a valid element of an Objective-C
304/// collection literal.
305static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element,
306 QualType T) {
307 // If the expression is type-dependent, there's nothing for us to do.
308 if (Element->isTypeDependent())
309 return Element;
310
311 ExprResult Result = S.CheckPlaceholderExpr(Element);
312 if (Result.isInvalid())
313 return ExprError();
314 Element = Result.get();
315
316 // In C++, check for an implicit conversion to an Objective-C object pointer
317 // type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000318 if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000319 InitializedEntity Entity
320 = InitializedEntity::InitializeParameter(S.Context, T, /*Consumed=*/false);
321 InitializationKind Kind
322 = InitializationKind::CreateCopy(Element->getLocStart(), SourceLocation());
323 InitializationSequence Seq(S, Entity, Kind, &Element, 1);
324 if (!Seq.Failed())
325 return Seq.Perform(S, Entity, Kind, MultiExprArg(S, &Element, 1));
326 }
327
328 Expr *OrigElement = Element;
329
330 // Perform lvalue-to-rvalue conversion.
331 Result = S.DefaultLvalueConversion(Element);
332 if (Result.isInvalid())
333 return ExprError();
334 Element = Result.get();
335
336 // Make sure that we have an Objective-C pointer type or block.
337 if (!Element->getType()->isObjCObjectPointerType() &&
338 !Element->getType()->isBlockPointerType()) {
339 bool Recovered = false;
340
341 // If this is potentially an Objective-C numeric literal, add the '@'.
342 if (isa<IntegerLiteral>(OrigElement) ||
343 isa<CharacterLiteral>(OrigElement) ||
344 isa<FloatingLiteral>(OrigElement) ||
345 isa<ObjCBoolLiteralExpr>(OrigElement) ||
346 isa<CXXBoolLiteralExpr>(OrigElement)) {
347 if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) {
348 int Which = isa<CharacterLiteral>(OrigElement) ? 1
349 : (isa<CXXBoolLiteralExpr>(OrigElement) ||
350 isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2
351 : 3;
352
353 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
354 << Which << OrigElement->getSourceRange()
355 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
356
357 Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(),
358 OrigElement);
359 if (Result.isInvalid())
360 return ExprError();
361
362 Element = Result.get();
363 Recovered = true;
364 }
365 }
366 // If this is potentially an Objective-C string literal, add the '@'.
367 else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) {
368 if (String->isAscii()) {
369 S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection)
370 << 0 << OrigElement->getSourceRange()
371 << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@");
372
373 Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String);
374 if (Result.isInvalid())
375 return ExprError();
376
377 Element = Result.get();
378 Recovered = true;
379 }
380 }
381
382 if (!Recovered) {
383 S.Diag(Element->getLocStart(), diag::err_invalid_collection_element)
384 << Element->getType();
385 return ExprError();
386 }
387 }
388
389 // Make sure that the element has the type that the container factory
390 // function expects.
391 return S.PerformCopyInitialization(
392 InitializedEntity::InitializeParameter(S.Context, T,
393 /*Consumed=*/false),
394 Element->getLocStart(), Element);
395}
396
Patrick Beardeb382ec2012-04-19 00:25:12 +0000397ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
398 if (ValueExpr->isTypeDependent()) {
399 ObjCBoxedExpr *BoxedExpr =
400 new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR);
401 return Owned(BoxedExpr);
402 }
403 ObjCMethodDecl *BoxingMethod = NULL;
404 QualType BoxedType;
405 // Convert the expression to an RValue, so we can check for pointer types...
406 ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr);
407 if (RValue.isInvalid()) {
408 return ExprError();
409 }
410 ValueExpr = RValue.get();
411 QualType ValueType(ValueExpr->getType().getCanonicalType());
412 if (const PointerType *PT = ValueType->getAs<PointerType>()) {
413 QualType PointeeType = PT->getPointeeType();
414 if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) {
415
416 if (!NSStringDecl) {
417 IdentifierInfo *NSStringId =
418 NSAPIObj->getNSClassId(NSAPI::ClassId_NSString);
419 NamedDecl *Decl = LookupSingleName(TUScope, NSStringId,
420 SR.getBegin(), LookupOrdinaryName);
421 NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl);
422 if (!NSStringDecl) {
423 if (getLangOpts().DebuggerObjCLiteral) {
424 // Support boxed expressions in the debugger w/o NSString declaration.
425 NSStringDecl = ObjCInterfaceDecl::Create(Context,
426 Context.getTranslationUnitDecl(),
427 SourceLocation(), NSStringId,
428 0, SourceLocation());
429 } else {
430 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
431 return ExprError();
432 }
433 } else if (!NSStringDecl->hasDefinition()) {
434 Diag(SR.getBegin(), diag::err_undeclared_nsstring);
435 return ExprError();
436 }
437 assert(NSStringDecl && "NSStringDecl should not be NULL");
438 NSStringPointer =
439 Context.getObjCObjectPointerType(Context.getObjCInterfaceType(NSStringDecl));
440 }
441
442 if (!StringWithUTF8StringMethod) {
443 IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String");
444 Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II);
445
446 // Look for the appropriate method within NSString.
447 StringWithUTF8StringMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String);
448 if (!StringWithUTF8StringMethod && getLangOpts().DebuggerObjCLiteral) {
449 // Debugger needs to work even if NSString hasn't been defined.
450 TypeSourceInfo *ResultTInfo = 0;
451 ObjCMethodDecl *M =
452 ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(),
453 stringWithUTF8String, NSStringPointer,
454 ResultTInfo, NSStringDecl,
455 /*isInstance=*/false, /*isVariadic=*/false,
456 /*isSynthesized=*/false,
457 /*isImplicitlyDeclared=*/true,
458 /*isDefined=*/false,
459 ObjCMethodDecl::Required,
460 /*HasRelatedResultType=*/false);
461 ParmVarDecl *value =
462 ParmVarDecl::Create(Context, M,
463 SourceLocation(), SourceLocation(),
464 &Context.Idents.get("value"),
465 Context.getPointerType(Context.CharTy.withConst()),
466 /*TInfo=*/0,
467 SC_None, SC_None, 0);
468 M->setMethodParams(Context, value, ArrayRef<SourceLocation>());
469 StringWithUTF8StringMethod = M;
470 }
471 assert(StringWithUTF8StringMethod &&
472 "StringWithUTF8StringMethod should not be NULL");
473 }
474
475 BoxingMethod = StringWithUTF8StringMethod;
476 BoxedType = NSStringPointer;
477 }
478 } else if (isa<BuiltinType>(ValueType)) {
479 // The other types we support are numeric, char and BOOL/bool. We could also
480 // provide limited support for structure types, such as NSRange, NSRect, and
481 // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h>
482 // for more details.
483
484 // Check for a top-level character literal.
485 if (const CharacterLiteral *Char =
486 dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) {
487 // In C, character literals have type 'int'. That's not the type we want
488 // to use to determine the Objective-c literal kind.
489 switch (Char->getKind()) {
490 case CharacterLiteral::Ascii:
491 ValueType = Context.CharTy;
492 break;
493
494 case CharacterLiteral::Wide:
495 ValueType = Context.getWCharType();
496 break;
497
498 case CharacterLiteral::UTF16:
499 ValueType = Context.Char16Ty;
500 break;
501
502 case CharacterLiteral::UTF32:
503 ValueType = Context.Char32Ty;
504 break;
505 }
506 }
507
508 // FIXME: Do I need to do anything special with BoolTy expressions?
509
510 // Look for the appropriate method within NSNumber.
511 BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType);
512 BoxedType = NSNumberPointer;
513 }
514
515 if (!BoxingMethod) {
516 Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type)
517 << ValueType << ValueExpr->getSourceRange();
518 return ExprError();
519 }
520
521 // Convert the expression to the type that the parameter requires.
522 QualType ArgType = BoxingMethod->param_begin()[0]->getType();
523 ExprResult ConvertedValueExpr = PerformImplicitConversion(ValueExpr, ArgType,
524 AA_Sending);
525 if (ConvertedValueExpr.isInvalid())
526 return ExprError();
527 ValueExpr = ConvertedValueExpr.get();
528
529 ObjCBoxedExpr *BoxedExpr =
530 new (Context) ObjCBoxedExpr(ValueExpr, BoxedType,
531 BoxingMethod, SR);
532 return MaybeBindToTemporary(BoxedExpr);
533}
534
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000535ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr,
536 Expr *IndexExpr,
537 ObjCMethodDecl *getterMethod,
538 ObjCMethodDecl *setterMethod) {
539 // Feature support is for modern abi.
540 if (!LangOpts.ObjCNonFragileABI)
541 return ExprError();
542 // If the expression is type-dependent, there's nothing for us to do.
543 assert ((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) &&
544 "base or index cannot have dependent type here");
545 ExprResult Result = CheckPlaceholderExpr(IndexExpr);
546 if (Result.isInvalid())
547 return ExprError();
548 IndexExpr = Result.get();
549
550 // Perform lvalue-to-rvalue conversion.
551 Result = DefaultLvalueConversion(BaseExpr);
552 if (Result.isInvalid())
553 return ExprError();
554 BaseExpr = Result.get();
555 return Owned(ObjCSubscriptRefExpr::Create(Context,
556 BaseExpr,
557 IndexExpr,
558 Context.PseudoObjectTy,
559 getterMethod,
560 setterMethod, RB));
561
562}
563
564ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) {
565 // Look up the NSArray class, if we haven't done so already.
566 if (!NSArrayDecl) {
567 NamedDecl *IF = LookupSingleName(TUScope,
568 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
569 SR.getBegin(),
570 LookupOrdinaryName);
571 NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikie4e4d0842012-03-11 07:00:24 +0000572 if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000573 NSArrayDecl = ObjCInterfaceDecl::Create (Context,
574 Context.getTranslationUnitDecl(),
575 SourceLocation(),
576 NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray),
577 0, SourceLocation());
578
579 if (!NSArrayDecl) {
580 Diag(SR.getBegin(), diag::err_undeclared_nsarray);
581 return ExprError();
582 }
583 }
584
585 // Find the arrayWithObjects:count: method, if we haven't done so already.
586 QualType IdT = Context.getObjCIdType();
587 if (!ArrayWithObjectsMethod) {
588 Selector
589 Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount);
590 ArrayWithObjectsMethod = NSArrayDecl->lookupClassMethod(Sel);
David Blaikie4e4d0842012-03-11 07:00:24 +0000591 if (!ArrayWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000592 TypeSourceInfo *ResultTInfo = 0;
593 ArrayWithObjectsMethod =
594 ObjCMethodDecl::Create(Context,
595 SourceLocation(), SourceLocation(), Sel,
596 IdT,
597 ResultTInfo,
598 Context.getTranslationUnitDecl(),
599 false /*Instance*/, false/*isVariadic*/,
600 /*isSynthesized=*/false,
601 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
602 ObjCMethodDecl::Required,
603 false);
604 SmallVector<ParmVarDecl *, 2> Params;
605 ParmVarDecl *objects = ParmVarDecl::Create(Context, ArrayWithObjectsMethod,
606 SourceLocation(), SourceLocation(),
607 &Context.Idents.get("objects"),
608 Context.getPointerType(IdT),
609 /*TInfo=*/0,
610 SC_None,
611 SC_None,
612 0);
613 Params.push_back(objects);
614 ParmVarDecl *cnt = ParmVarDecl::Create(Context, ArrayWithObjectsMethod,
615 SourceLocation(), SourceLocation(),
616 &Context.Idents.get("cnt"),
617 Context.UnsignedLongTy,
618 /*TInfo=*/0,
619 SC_None,
620 SC_None,
621 0);
622 Params.push_back(cnt);
623 ArrayWithObjectsMethod->setMethodParams(Context, Params,
624 ArrayRef<SourceLocation>());
625
626
627 }
628
629 if (!ArrayWithObjectsMethod) {
630 Diag(SR.getBegin(), diag::err_undeclared_arraywithobjects) << Sel;
631 return ExprError();
632 }
633 }
634
635 // Make sure the return type is reasonable.
636 if (!ArrayWithObjectsMethod->getResultType()->isObjCObjectPointerType()) {
637 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
638 << ArrayWithObjectsMethod->getSelector();
639 Diag(ArrayWithObjectsMethod->getLocation(),
640 diag::note_objc_literal_method_return)
641 << ArrayWithObjectsMethod->getResultType();
642 return ExprError();
643 }
644
645 // Dig out the type that all elements should be converted to.
646 QualType T = ArrayWithObjectsMethod->param_begin()[0]->getType();
647 const PointerType *PtrT = T->getAs<PointerType>();
648 if (!PtrT ||
649 !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) {
650 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
651 << ArrayWithObjectsMethod->getSelector();
652 Diag(ArrayWithObjectsMethod->param_begin()[0]->getLocation(),
653 diag::note_objc_literal_method_param)
654 << 0 << T
655 << Context.getPointerType(IdT.withConst());
656 return ExprError();
657 }
658 T = PtrT->getPointeeType();
659
660 // Check that the 'count' parameter is integral.
661 if (!ArrayWithObjectsMethod->param_begin()[1]->getType()->isIntegerType()) {
662 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
663 << ArrayWithObjectsMethod->getSelector();
664 Diag(ArrayWithObjectsMethod->param_begin()[1]->getLocation(),
665 diag::note_objc_literal_method_param)
666 << 1
667 << ArrayWithObjectsMethod->param_begin()[1]->getType()
668 << "integral";
669 return ExprError();
670 }
671
672 // Check that each of the elements provided is valid in a collection literal,
673 // performing conversions as necessary.
674 Expr **ElementsBuffer = Elements.get();
675 for (unsigned I = 0, N = Elements.size(); I != N; ++I) {
676 ExprResult Converted = CheckObjCCollectionLiteralElement(*this,
677 ElementsBuffer[I],
678 T);
679 if (Converted.isInvalid())
680 return ExprError();
681
682 ElementsBuffer[I] = Converted.get();
683 }
684
685 QualType Ty
686 = Context.getObjCObjectPointerType(
687 Context.getObjCInterfaceType(NSArrayDecl));
688
689 return MaybeBindToTemporary(
690 ObjCArrayLiteral::Create(Context,
691 llvm::makeArrayRef(Elements.get(),
692 Elements.size()),
693 Ty, ArrayWithObjectsMethod, SR));
694}
695
696ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR,
697 ObjCDictionaryElement *Elements,
698 unsigned NumElements) {
699 // Look up the NSDictionary class, if we haven't done so already.
700 if (!NSDictionaryDecl) {
701 NamedDecl *IF = LookupSingleName(TUScope,
702 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
703 SR.getBegin(), LookupOrdinaryName);
704 NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
David Blaikie4e4d0842012-03-11 07:00:24 +0000705 if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral)
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000706 NSDictionaryDecl = ObjCInterfaceDecl::Create (Context,
707 Context.getTranslationUnitDecl(),
708 SourceLocation(),
709 NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary),
710 0, SourceLocation());
711
712 if (!NSDictionaryDecl) {
713 Diag(SR.getBegin(), diag::err_undeclared_nsdictionary);
714 return ExprError();
715 }
716 }
717
718 // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done
719 // so already.
720 QualType IdT = Context.getObjCIdType();
721 if (!DictionaryWithObjectsMethod) {
722 Selector Sel = NSAPIObj->getNSDictionarySelector(
723 NSAPI::NSDict_dictionaryWithObjectsForKeysCount);
724 DictionaryWithObjectsMethod = NSDictionaryDecl->lookupClassMethod(Sel);
David Blaikie4e4d0842012-03-11 07:00:24 +0000725 if (!DictionaryWithObjectsMethod && getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000726 DictionaryWithObjectsMethod =
727 ObjCMethodDecl::Create(Context,
728 SourceLocation(), SourceLocation(), Sel,
729 IdT,
730 0 /*TypeSourceInfo */,
731 Context.getTranslationUnitDecl(),
732 false /*Instance*/, false/*isVariadic*/,
733 /*isSynthesized=*/false,
734 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
735 ObjCMethodDecl::Required,
736 false);
737 SmallVector<ParmVarDecl *, 3> Params;
738 ParmVarDecl *objects = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
739 SourceLocation(), SourceLocation(),
740 &Context.Idents.get("objects"),
741 Context.getPointerType(IdT),
742 /*TInfo=*/0,
743 SC_None,
744 SC_None,
745 0);
746 Params.push_back(objects);
747 ParmVarDecl *keys = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
748 SourceLocation(), SourceLocation(),
749 &Context.Idents.get("keys"),
750 Context.getPointerType(IdT),
751 /*TInfo=*/0,
752 SC_None,
753 SC_None,
754 0);
755 Params.push_back(keys);
756 ParmVarDecl *cnt = ParmVarDecl::Create(Context, DictionaryWithObjectsMethod,
757 SourceLocation(), SourceLocation(),
758 &Context.Idents.get("cnt"),
759 Context.UnsignedLongTy,
760 /*TInfo=*/0,
761 SC_None,
762 SC_None,
763 0);
764 Params.push_back(cnt);
765 DictionaryWithObjectsMethod->setMethodParams(Context, Params,
766 ArrayRef<SourceLocation>());
767 }
768
769 if (!DictionaryWithObjectsMethod) {
770 Diag(SR.getBegin(), diag::err_undeclared_dictwithobjects) << Sel;
771 return ExprError();
772 }
773 }
774
775 // Make sure the return type is reasonable.
776 if (!DictionaryWithObjectsMethod->getResultType()->isObjCObjectPointerType()){
777 Diag(SR.getBegin(), diag::err_objc_literal_method_sig)
778 << DictionaryWithObjectsMethod->getSelector();
779 Diag(DictionaryWithObjectsMethod->getLocation(),
780 diag::note_objc_literal_method_return)
781 << DictionaryWithObjectsMethod->getResultType();
782 return ExprError();
783 }
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,
907 PDiag(diag::err_incomplete_type_objc_at_encode)
908 << EncodedTypeInfo->getTypeLoc().getSourceRange()))
909 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 Gregor688fc9b2010-04-21 23:24:10 +00001173 PDiag(diag::err_call_incomplete_argument)
1174 << argExpr->getSourceRange()))
1175 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +00001176
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00001177 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall5acb0c92011-10-17 18:40:02 +00001178 param);
John McCall3fa5cae2010-10-26 07:05:15 +00001179 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +00001180 if (ArgE.isInvalid())
1181 IsError = true;
1182 else
1183 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +00001184 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001185
1186 // Promote additional arguments to variadic methods.
1187 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001188 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
1189 if (Args[i]->isTypeDependent())
1190 continue;
1191
John Wiegley429bb272011-04-08 18:41:53 +00001192 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
1193 IsError |= Arg.isInvalid();
1194 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +00001195 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001196 } else {
1197 // Check for extra arguments to non-variadic methods.
1198 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +00001199 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001200 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +00001201 << 2 /*method*/ << NumNamedArgs << NumArgs
1202 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001203 << SourceRange(Args[NumNamedArgs]->getLocStart(),
1204 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +00001205 }
1206 }
1207
Douglas Gregor2725ca82010-04-21 19:57:20 +00001208 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +00001209
1210 // Do additional checkings on method.
1211 IsError |= CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
1212
Chris Lattner312531a2009-04-12 08:11:20 +00001213 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +00001214}
1215
Douglas Gregorc737acb2011-09-27 16:10:05 +00001216bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +00001217 // 'self' is objc 'self' in an objc method only.
John McCall4b9c2d22011-11-06 09:01:30 +00001218 ObjCMethodDecl *method =
1219 dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
1220 if (!method) return false;
1221
John McCallf85e1932011-06-15 23:02:42 +00001222 receiver = receiver->IgnoreParenLValueCasts();
1223 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCall4b9c2d22011-11-06 09:01:30 +00001224 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregorc737acb2011-09-27 16:10:05 +00001225 return true;
1226 return false;
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001227}
1228
Steve Narofff1afaf62009-02-26 15:55:06 +00001229// Helper method for ActOnClassMethod/ActOnInstanceMethod.
1230// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +00001231// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +00001232// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +00001233ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +00001234 ObjCInterfaceDecl *ClassDecl) {
1235 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +00001236 // lookup in class and all superclasses
1237 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001238 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001239 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Steve Naroff5609ec02009-03-08 18:56:13 +00001241 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001242 if (!Method)
1243 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Steve Naroff5609ec02009-03-08 18:56:13 +00001245 // Before we give up, check if the selector is an instance method.
1246 // But only in the root. This matches gcc's behaviour and what the
1247 // runtime expects.
1248 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001249 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001250 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +00001251 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +00001252 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +00001253 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1254 }
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Steve Naroff5609ec02009-03-08 18:56:13 +00001256 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +00001257 }
Steve Naroff5609ec02009-03-08 18:56:13 +00001258 return Method;
1259}
1260
1261ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
1262 ObjCInterfaceDecl *ClassDecl) {
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00001263 if (!ClassDecl->hasDefinition())
1264 return 0;
1265
Steve Naroff5609ec02009-03-08 18:56:13 +00001266 ObjCMethodDecl *Method = 0;
1267 while (ClassDecl && !Method) {
1268 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001269 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001270 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Steve Naroff5609ec02009-03-08 18:56:13 +00001272 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001273 if (!Method)
1274 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +00001275 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +00001276 }
Steve Narofff1afaf62009-02-26 15:55:06 +00001277 return Method;
1278}
1279
John McCall3c3b7f92011-10-25 17:37:35 +00001280/// LookupMethodInType - Look up a method in an ObjCObjectType.
1281ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
1282 bool isInstance) {
1283 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
1284 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
1285 // Look it up in the main interface (and categories, etc.)
1286 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
1287 return method;
1288
1289 // Okay, look for "private" methods declared in any
1290 // @implementations we've seen.
1291 if (isInstance) {
1292 if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
1293 return method;
1294 } else {
1295 if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
1296 return method;
1297 }
1298 }
1299
1300 // Check qualifiers.
1301 for (ObjCObjectType::qual_iterator
1302 i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
1303 if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
1304 return method;
1305
1306 return 0;
1307}
1308
Fariborz Jahanian61478062011-03-09 20:18:06 +00001309/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
1310/// list of a qualified objective pointer type.
1311ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
1312 const ObjCObjectPointerType *OPT,
1313 bool Instance)
1314{
1315 ObjCMethodDecl *MD = 0;
1316 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1317 E = OPT->qual_end(); I != E; ++I) {
1318 ObjCProtocolDecl *PROTO = (*I);
1319 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
1320 return MD;
1321 }
1322 }
1323 return 0;
1324}
1325
Fariborz Jahanian98795562012-04-19 23:49:39 +00001326static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) {
1327 if (!Receiver)
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001328 return;
1329
Fariborz Jahanian98795562012-04-19 23:49:39 +00001330 Expr *RExpr = Receiver->IgnoreParenImpCasts();
1331 SourceLocation Loc = RExpr->getLocStart();
1332 QualType T = RExpr->getType();
1333 ObjCPropertyDecl *PDecl = 0;
1334 ObjCMethodDecl *GDecl = 0;
1335 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) {
1336 RExpr = POE->getSyntacticForm();
1337 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) {
1338 if (PRE->isImplicitProperty()) {
1339 GDecl = PRE->getImplicitPropertyGetter();
1340 if (GDecl) {
1341 T = GDecl->getResultType();
1342 }
1343 }
1344 else {
1345 PDecl = PRE->getExplicitProperty();
1346 if (PDecl) {
1347 T = PDecl->getType();
1348 }
1349 }
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001350 }
Fariborz Jahanian98795562012-04-19 23:49:39 +00001351 }
1352
1353 if (T.getObjCLifetime() == Qualifiers::OCL_Weak) {
1354 S.Diag(Loc, diag::warn_receiver_is_weak)
1355 << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2));
1356 if (PDecl)
1357 S.Diag(PDecl->getLocation(), diag::note_property_declare);
1358 else if (GDecl)
1359 S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl;
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001360 return;
1361 }
1362
Fariborz Jahanian98795562012-04-19 23:49:39 +00001363 if (PDecl &&
1364 (PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)) {
1365 S.Diag(Loc, diag::warn_receiver_is_weak) << 1;
1366 S.Diag(PDecl->getLocation(), diag::note_property_declare);
1367 }
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001368}
1369
Chris Lattner7f816522010-04-11 07:45:24 +00001370/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1371/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001372ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +00001373HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001374 Expr *BaseExpr, SourceLocation OpLoc,
1375 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001376 SourceLocation MemberLoc,
1377 SourceLocation SuperLoc, QualType SuperType,
1378 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +00001379 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1380 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +00001381
1382 if (MemberName.getNameKind() != DeclarationName::Identifier) {
1383 Diag(MemberLoc, diag::err_invalid_property_name)
1384 << MemberName << QualType(OPT, 0);
1385 return ExprError();
1386 }
1387
Chris Lattner7f816522010-04-11 07:45:24 +00001388 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregorb3029962011-11-14 22:10:01 +00001389 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1390 : BaseExpr->getSourceRange();
1391 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1392 PDiag(diag::err_property_not_found_forward_class)
1393 << MemberName << BaseRange))
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +00001394 return ExprError();
Douglas Gregorb3029962011-11-14 22:10:01 +00001395
Chris Lattner7f816522010-04-11 07:45:24 +00001396 // Search for a declared property first.
1397 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1398 // Check whether we can reference this property.
1399 if (DiagnoseUseOfDecl(PD, MemberLoc))
1400 return ExprError();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001401 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001402 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001403 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001404 MemberLoc,
1405 SuperLoc, SuperType));
1406 else
John McCall3c3b7f92011-10-25 17:37:35 +00001407 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001408 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001409 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001410 }
1411 // Check protocols on qualified interfaces.
1412 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1413 E = OPT->qual_end(); I != E; ++I)
1414 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1415 // Check whether we can reference this property.
1416 if (DiagnoseUseOfDecl(PD, MemberLoc))
1417 return ExprError();
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001418
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001419 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001420 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1421 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001422 VK_LValue,
1423 OK_ObjCProperty,
1424 MemberLoc,
1425 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001426 else
John McCall3c3b7f92011-10-25 17:37:35 +00001427 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1428 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001429 VK_LValue,
1430 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001431 MemberLoc,
1432 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001433 }
1434 // If that failed, look for an "implicit" property by seeing if the nullary
1435 // selector is implemented.
1436
1437 // FIXME: The logic for looking up nullary and unary selectors should be
1438 // shared with the code in ActOnInstanceMessage.
1439
1440 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1441 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001442
1443 // May be founf in property's qualified list.
1444 if (!Getter)
1445 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +00001446
1447 // If this reference is in an @implementation, check for 'private' methods.
1448 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001449 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +00001450
1451 // Look through local category implementations associated with the class.
1452 if (!Getter)
1453 Getter = IFace->getCategoryInstanceMethod(Sel);
1454 if (Getter) {
1455 // Check if we can reference this property.
1456 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1457 return ExprError();
1458 }
1459 // If we found a getter then this may be a valid dot-reference, we
1460 // will look for the matching setter, in case it is needed.
1461 Selector SetterSel =
1462 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1463 PP.getSelectorTable(), Member);
1464 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001465
1466 // May be founf in property's qualified list.
1467 if (!Setter)
1468 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1469
Chris Lattner7f816522010-04-11 07:45:24 +00001470 if (!Setter) {
1471 // If this reference is in an @implementation, also check for 'private'
1472 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001473 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +00001474 }
1475 // Look through local category implementations associated with the class.
1476 if (!Setter)
1477 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001478
Chris Lattner7f816522010-04-11 07:45:24 +00001479 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1480 return ExprError();
1481
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001482 if (Getter || Setter) {
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001483 if (Super)
John McCall12f78a62010-12-02 01:19:52 +00001484 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001485 Context.PseudoObjectTy,
1486 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001487 MemberLoc,
1488 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001489 else
John McCall12f78a62010-12-02 01:19:52 +00001490 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001491 Context.PseudoObjectTy,
1492 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001493 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001494
Chris Lattner7f816522010-04-11 07:45:24 +00001495 }
1496
1497 // Attempt to correct for typos in property names.
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001498 DeclFilterCCC<ObjCPropertyDecl> Validator;
1499 if (TypoCorrection Corrected = CorrectTypo(
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001500 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001501 NULL, Validator, IFace, false, OPT)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001502 ObjCPropertyDecl *Property =
1503 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001504 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +00001505 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001506 << MemberName << QualType(OPT, 0) << TypoResult
1507 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +00001508 Diag(Property->getLocation(), diag::note_previous_decl)
1509 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001510 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1511 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001512 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +00001513 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001514 ObjCInterfaceDecl *ClassDeclared;
1515 if (ObjCIvarDecl *Ivar =
1516 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1517 QualType T = Ivar->getType();
1518 if (const ObjCObjectPointerType * OBJPT =
1519 T->getAsObjCInterfacePointerType()) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001520 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1521 PDiag(diag::err_property_not_as_forward_class)
1522 << MemberName << BaseExpr->getSourceRange()))
1523 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001524 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001525 Diag(MemberLoc,
1526 diag::err_ivar_access_using_property_syntax_suggest)
1527 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1528 << FixItHint::CreateReplacement(OpLoc, "->");
1529 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001530 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001531
Chris Lattner7f816522010-04-11 07:45:24 +00001532 Diag(MemberLoc, diag::err_property_not_found)
1533 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001534 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +00001535 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001536 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +00001537 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +00001538}
1539
1540
1541
John McCall60d7b3a2010-08-24 06:29:42 +00001542ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +00001543ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1544 IdentifierInfo &propertyName,
1545 SourceLocation receiverNameLoc,
1546 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001548 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +00001549 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1550 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +00001551
1552 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +00001553 if (IFace == 0) {
1554 // If the "receiver" is 'super' in a method, handle it as an expression-like
1555 // property reference.
John McCall26743b22011-02-03 09:00:02 +00001556 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001557 IsSuper = true;
1558
Eli Friedmanb942cb22012-02-03 22:47:37 +00001559 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnereb483eb2010-04-11 08:28:14 +00001560 if (CurMethod->isInstanceMethod()) {
1561 QualType T =
1562 Context.getObjCInterfaceType(CurMethod->getClassInterface());
1563 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001564
1565 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001566 /*BaseExpr*/0,
1567 SourceLocation()/*OpLoc*/,
1568 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001569 propertyNameLoc,
1570 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001571 }
Mike Stump1eb44332009-09-09 15:08:12 +00001572
Chris Lattnereb483eb2010-04-11 08:28:14 +00001573 // Otherwise, if this is a class method, try dispatching to our
1574 // superclass.
1575 IFace = CurMethod->getClassInterface()->getSuperClass();
1576 }
John McCall26743b22011-02-03 09:00:02 +00001577 }
Chris Lattnereb483eb2010-04-11 08:28:14 +00001578
1579 if (IFace == 0) {
1580 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1581 return ExprError();
1582 }
1583 }
1584
1585 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +00001586 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001587 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001588
1589 // If this reference is in an @implementation, check for 'private' methods.
1590 if (!Getter)
1591 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1592 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001593 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001594 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001595
1596 if (Getter) {
1597 // FIXME: refactor/share with ActOnMemberReference().
1598 // Check if we can reference this property.
1599 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1600 return ExprError();
1601 }
Mike Stump1eb44332009-09-09 15:08:12 +00001602
Steve Naroff61f72cb2009-03-09 21:12:44 +00001603 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00001604 Selector SetterSel =
1605 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +00001606 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001608 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001609 if (!Setter) {
1610 // If this reference is in an @implementation, also check for 'private'
1611 // methods.
1612 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1613 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001614 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001615 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001616 }
1617 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001618 if (!Setter)
1619 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001620
1621 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1622 return ExprError();
1623
1624 if (Getter || Setter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001625 if (IsSuper)
1626 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001627 Context.PseudoObjectTy,
1628 VK_LValue, OK_ObjCProperty,
Douglas Gregor926df6c2011-06-11 01:09:30 +00001629 propertyNameLoc,
1630 receiverNameLoc,
1631 Context.getObjCInterfaceType(IFace)));
1632
John McCall12f78a62010-12-02 01:19:52 +00001633 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001634 Context.PseudoObjectTy,
1635 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001636 propertyNameLoc,
1637 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +00001638 }
1639 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1640 << &propertyName << Context.getObjCInterfaceType(IFace));
1641}
1642
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001643namespace {
1644
1645class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1646 public:
1647 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1648 // Determine whether "super" is acceptable in the current context.
1649 if (Method && Method->getClassInterface())
1650 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1651 }
1652
1653 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1654 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1655 candidate.isKeyword("super");
1656 }
1657};
1658
1659}
1660
Douglas Gregor47bd5432010-04-14 02:46:37 +00001661Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +00001662 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +00001663 SourceLocation NameLoc,
1664 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +00001665 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +00001666 ParsedType &ReceiverType) {
1667 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +00001668
Douglas Gregor47bd5432010-04-14 02:46:37 +00001669 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +00001670 // messaging super. If the identifier is "super" and there is a
1671 // trailing dot, it's an instance message.
1672 if (IsSuper && S->isInObjcMethodScope())
1673 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001674
1675 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1676 LookupName(Result, S);
1677
1678 switch (Result.getResultKind()) {
1679 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +00001680 // Normal name lookup didn't find anything. If we're in an
1681 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +00001682 // FIXME: This is a hack. Ivar lookup should be part of normal
1683 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +00001684 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidisccc9e762011-11-09 00:22:48 +00001685 if (!Method->getClassInterface()) {
1686 // Fall back: let the parser try to parse it as an instance message.
1687 return ObjCInstanceMessage;
1688 }
1689
Douglas Gregored464422010-04-19 20:09:36 +00001690 ObjCInterfaceDecl *ClassDeclared;
1691 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1692 ClassDeclared))
1693 return ObjCInstanceMessage;
1694 }
Douglas Gregor95f42922010-10-14 22:11:03 +00001695
Douglas Gregor47bd5432010-04-14 02:46:37 +00001696 // Break out; we'll perform typo correction below.
1697 break;
1698
1699 case LookupResult::NotFoundInCurrentInstantiation:
1700 case LookupResult::FoundOverloaded:
1701 case LookupResult::FoundUnresolvedValue:
1702 case LookupResult::Ambiguous:
1703 Result.suppressDiagnostics();
1704 return ObjCInstanceMessage;
1705
1706 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +00001707 // If the identifier is a class or not, and there is a trailing dot,
1708 // it's an instance message.
1709 if (HasTrailingDot)
1710 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001711 // We found something. If it's a type, then we have a class
1712 // message. Otherwise, it's an instance message.
1713 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +00001714 QualType T;
1715 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1716 T = Context.getObjCInterfaceType(Class);
1717 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
1718 T = Context.getTypeDeclType(Type);
1719 else
1720 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001721
Douglas Gregor1569f952010-04-21 20:38:13 +00001722 // We have a class message, and T is the type we're
1723 // messaging. Build source-location information for it.
1724 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +00001725 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +00001726 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001727 }
1728 }
1729
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001730 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001731 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1732 Result.getLookupKind(), S, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001733 Validator)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001734 if (Corrected.isKeyword()) {
1735 // If we've found the keyword "super" (the only keyword that would be
1736 // returned by CorrectTypo), this is a send to super.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001737 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001738 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +00001739 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +00001740 return ObjCSuperMessage;
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001741 } else if (ObjCInterfaceDecl *Class =
1742 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1743 // If we found a declaration, correct when it refers to an Objective-C
1744 // class.
1745 Diag(NameLoc, diag::err_unknown_receiver_suggest)
1746 << Name << Corrected.getCorrection()
1747 << FixItHint::CreateReplacement(SourceRange(NameLoc),
1748 Class->getNameAsString());
1749 Diag(Class->getLocation(), diag::note_previous_decl)
1750 << Corrected.getCorrection();
1751
1752 QualType T = Context.getObjCInterfaceType(Class);
1753 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1754 ReceiverType = CreateParsedType(T, TSInfo);
1755 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001756 }
1757 }
1758
1759 // Fall back: let the parser try to parse it as an instance message.
1760 return ObjCInstanceMessage;
1761}
Steve Naroff61f72cb2009-03-09 21:12:44 +00001762
John McCall60d7b3a2010-08-24 06:29:42 +00001763ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001764 SourceLocation SuperLoc,
1765 Selector Sel,
1766 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001767 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001768 SourceLocation RBracLoc,
1769 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001770 // Determine whether we are inside a method or not.
Eli Friedmanb942cb22012-02-03 22:47:37 +00001771 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregorf95861a2010-04-21 20:01:04 +00001772 if (!Method) {
1773 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1774 return ExprError();
1775 }
Chris Lattner85a932e2008-01-04 22:32:30 +00001776
Douglas Gregorf95861a2010-04-21 20:01:04 +00001777 ObjCInterfaceDecl *Class = Method->getClassInterface();
1778 if (!Class) {
1779 Diag(SuperLoc, diag::error_no_super_class_message)
1780 << Method->getDeclName();
1781 return ExprError();
1782 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001783
Douglas Gregorf95861a2010-04-21 20:01:04 +00001784 ObjCInterfaceDecl *Super = Class->getSuperClass();
1785 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001786 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +00001787 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1788 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001789 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +00001790 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001791
Douglas Gregorf95861a2010-04-21 20:01:04 +00001792 // We are in a method whose class has a superclass, so 'super'
1793 // is acting as a keyword.
1794 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +00001795 if (Sel.getMethodFamily() == OMF_dealloc)
1796 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00001797 if (Sel.getMethodFamily() == OMF_finalize)
1798 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +00001799
Douglas Gregorf95861a2010-04-21 20:01:04 +00001800 // Since we are in an instance method, this is an instance
1801 // message to the superclass instance.
1802 QualType SuperTy = Context.getObjCInterfaceType(Super);
1803 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +00001804 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001805 Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001806 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001807 }
Douglas Gregorf95861a2010-04-21 20:01:04 +00001808
1809 // Since we are in a class method, this is a class message to
1810 // the superclass.
1811 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1812 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001813 SuperLoc, Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001814 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001815}
1816
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001817
1818ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1819 bool isSuperReceiver,
1820 SourceLocation Loc,
1821 Selector Sel,
1822 ObjCMethodDecl *Method,
1823 MultiExprArg Args) {
1824 TypeSourceInfo *receiverTypeInfo = 0;
1825 if (!ReceiverType.isNull())
1826 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1827
1828 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1829 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1830 Sel, Method, Loc, Loc, Loc, Args,
1831 /*isImplicit=*/true);
1832
1833}
1834
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001835static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1836 unsigned DiagID,
1837 bool (*refactor)(const ObjCMessageExpr *,
1838 const NSAPI &, edit::Commit &)) {
1839 SourceLocation MsgLoc = Msg->getExprLoc();
1840 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
1841 return;
1842
1843 SourceManager &SM = S.SourceMgr;
1844 edit::Commit ECommit(SM, S.LangOpts);
1845 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1846 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1847 << Msg->getSelector() << Msg->getSourceRange();
1848 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1849 if (!ECommit.isCommitable())
1850 return;
1851 for (edit::Commit::edit_iterator
1852 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1853 const edit::Commit::Edit &Edit = *I;
1854 switch (Edit.Kind) {
1855 case edit::Commit::Act_Insert:
1856 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1857 Edit.Text,
1858 Edit.BeforePrev));
1859 break;
1860 case edit::Commit::Act_InsertFromRange:
1861 Builder.AddFixItHint(
1862 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1863 Edit.getInsertFromRange(SM),
1864 Edit.BeforePrev));
1865 break;
1866 case edit::Commit::Act_Remove:
1867 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1868 break;
1869 }
1870 }
1871 }
1872}
1873
1874static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1875 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1876 edit::rewriteObjCRedundantCallWithLiteral);
1877}
1878
Douglas Gregor2725ca82010-04-21 19:57:20 +00001879/// \brief Build an Objective-C class message expression.
1880///
1881/// This routine takes care of both normal class messages and
1882/// class messages to the superclass.
1883///
1884/// \param ReceiverTypeInfo Type source information that describes the
1885/// receiver of this message. This may be NULL, in which case we are
1886/// sending to the superclass and \p SuperLoc must be a valid source
1887/// location.
1888
1889/// \param ReceiverType The type of the object receiving the
1890/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1891/// type as that refers to. For a superclass send, this is the type of
1892/// the superclass.
1893///
1894/// \param SuperLoc The location of the "super" keyword in a
1895/// superclass message.
1896///
1897/// \param Sel The selector to which the message is being sent.
1898///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001899/// \param Method The method that this class message is invoking, if
1900/// already known.
1901///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001902/// \param LBracLoc The location of the opening square bracket ']'.
1903///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001904/// \param RBrac The location of the closing square bracket ']'.
1905///
1906/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001907ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001908 QualType ReceiverType,
1909 SourceLocation SuperLoc,
1910 Selector Sel,
1911 ObjCMethodDecl *Method,
1912 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001913 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001914 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001915 MultiExprArg ArgsIn,
1916 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001917 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001918 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001919 if (LBracLoc.isInvalid()) {
1920 Diag(Loc, diag::err_missing_open_square_message_send)
1921 << FixItHint::CreateInsertion(Loc, "[");
1922 LBracLoc = Loc;
1923 }
1924
Douglas Gregor92e986e2010-04-22 16:44:27 +00001925 if (ReceiverType->isDependentType()) {
1926 // If the receiver type is dependent, we can't type-check anything
1927 // at this point. Build a dependent expression.
1928 unsigned NumArgs = ArgsIn.size();
1929 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1930 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001931 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1932 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001933 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001934 makeArrayRef(Args, NumArgs),RBracLoc,
1935 isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001936 }
Chris Lattner15faee12010-04-12 05:38:43 +00001937
Douglas Gregor2725ca82010-04-21 19:57:20 +00001938 // Find the class to which we are sending this message.
1939 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001940 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1941 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001942 Diag(Loc, diag::err_invalid_receiver_class_message)
1943 << ReceiverType;
1944 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001945 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001946 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001947 // objc++ diagnoses during typename annotation.
David Blaikie4e4d0842012-03-11 07:00:24 +00001948 if (!getLangOpts().CPlusPlus)
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001949 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001950 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001951 if (!Method) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001952 SourceRange TypeRange
1953 = SuperLoc.isValid()? SourceRange(SuperLoc)
1954 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
1955 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikie4e4d0842012-03-11 07:00:24 +00001956 (getLangOpts().ObjCAutoRefCount
Douglas Gregorb3029962011-11-14 22:10:01 +00001957 ? PDiag(diag::err_arc_receiver_forward_class)
1958 : PDiag(diag::warn_receiver_forward_class))
1959 << TypeRange)) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001960 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001961 Method = LookupFactoryMethodInGlobalPool(Sel,
1962 SourceRange(LBracLoc, RBracLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00001963 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001964 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1965 << Method->getDeclName();
1966 }
1967 if (!Method)
1968 Method = Class->lookupClassMethod(Sel);
1969
1970 // If we have an implementation in scope, check "private" methods.
1971 if (!Method)
1972 Method = LookupPrivateClassMethod(Sel, Class);
1973
1974 if (Method && DiagnoseUseOfDecl(Method, Loc))
1975 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001976 }
Mike Stump1eb44332009-09-09 15:08:12 +00001977
Douglas Gregor2725ca82010-04-21 19:57:20 +00001978 // Check the argument types and determine the result type.
1979 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001980 ExprValueKind VK = VK_RValue;
1981
Douglas Gregor2725ca82010-04-21 19:57:20 +00001982 unsigned NumArgs = ArgsIn.size();
1983 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001984 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1985 SuperLoc.isValid(), LBracLoc, RBracLoc,
1986 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001987 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001988
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001989 if (Method && !Method->getResultType()->isVoidType() &&
1990 RequireCompleteType(LBracLoc, Method->getResultType(),
1991 diag::err_illegal_message_expr_incomplete_type))
1992 return ExprError();
1993
Douglas Gregor2725ca82010-04-21 19:57:20 +00001994 // Construct the appropriate ObjCMessageExpr.
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001995 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001996 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001997 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001998 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001999 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002000 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002001 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002002 else {
John McCallf89e55a2010-11-18 06:31:45 +00002003 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002004 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002005 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002006 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002007 if (!isImplicit)
2008 checkCocoaAPI(*this, Result);
2009 }
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002010 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00002011}
2012
Douglas Gregor2725ca82010-04-21 19:57:20 +00002013// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00002014// ArgExprs is optional - if it is present, the number of expressions
2015// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00002016ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00002017 ParsedType Receiver,
2018 Selector Sel,
2019 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002020 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor77328d12010-09-15 23:19:31 +00002021 SourceLocation RBracLoc,
2022 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002023 TypeSourceInfo *ReceiverTypeInfo;
2024 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2025 if (ReceiverType.isNull())
2026 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002027
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Douglas Gregor2725ca82010-04-21 19:57:20 +00002029 if (!ReceiverTypeInfo)
2030 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2031
2032 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00002033 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002034 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00002035}
2036
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002037ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2038 QualType ReceiverType,
2039 SourceLocation Loc,
2040 Selector Sel,
2041 ObjCMethodDecl *Method,
2042 MultiExprArg Args) {
2043 return BuildInstanceMessage(Receiver, ReceiverType,
2044 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2045 Sel, Method, Loc, Loc, Loc, Args,
2046 /*isImplicit=*/true);
2047}
2048
Douglas Gregor2725ca82010-04-21 19:57:20 +00002049/// \brief Build an Objective-C instance message expression.
2050///
2051/// This routine takes care of both normal instance messages and
2052/// instance messages to the superclass instance.
2053///
2054/// \param Receiver The expression that computes the object that will
2055/// receive this message. This may be empty, in which case we are
2056/// sending to the superclass instance and \p SuperLoc must be a valid
2057/// source location.
2058///
2059/// \param ReceiverType The (static) type of the object receiving the
2060/// message. When a \p Receiver expression is provided, this is the
2061/// same type as that expression. For a superclass instance send, this
2062/// is a pointer to the type of the superclass.
2063///
2064/// \param SuperLoc The location of the "super" keyword in a
2065/// superclass instance message.
2066///
2067/// \param Sel The selector to which the message is being sent.
2068///
Douglas Gregorf49bb082010-04-22 17:01:48 +00002069/// \param Method The method that this instance message is invoking, if
2070/// already known.
2071///
Douglas Gregor2725ca82010-04-21 19:57:20 +00002072/// \param LBracLoc The location of the opening square bracket ']'.
2073///
Douglas Gregor2725ca82010-04-21 19:57:20 +00002074/// \param RBrac The location of the closing square bracket ']'.
2075///
2076/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00002077ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002078 QualType ReceiverType,
2079 SourceLocation SuperLoc,
2080 Selector Sel,
2081 ObjCMethodDecl *Method,
2082 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002083 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002084 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002085 MultiExprArg ArgsIn,
2086 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00002087 // The location of the receiver.
2088 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2089
2090 if (LBracLoc.isInvalid()) {
2091 Diag(Loc, diag::err_missing_open_square_message_send)
2092 << FixItHint::CreateInsertion(Loc, "[");
2093 LBracLoc = Loc;
2094 }
2095
Douglas Gregor2725ca82010-04-21 19:57:20 +00002096 // If we have a receiver expression, perform appropriate promotions
2097 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00002098 if (Receiver) {
John McCall5acb0c92011-10-17 18:40:02 +00002099 if (Receiver->hasPlaceholderType()) {
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00002100 ExprResult Result;
2101 if (Receiver->getType() == Context.UnknownAnyTy)
2102 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2103 else
2104 Result = CheckPlaceholderExpr(Receiver);
2105 if (Result.isInvalid()) return ExprError();
2106 Receiver = Result.take();
John McCall5acb0c92011-10-17 18:40:02 +00002107 }
2108
Douglas Gregor92e986e2010-04-22 16:44:27 +00002109 if (Receiver->isTypeDependent()) {
2110 // If the receiver is type-dependent, we can't type-check anything
2111 // at this point. Build a dependent expression.
2112 unsigned NumArgs = ArgsIn.size();
2113 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2114 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2115 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00002116 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002117 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002118 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002119 RBracLoc, isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00002120 }
2121
Douglas Gregor2725ca82010-04-21 19:57:20 +00002122 // If necessary, apply function/array conversion to the receiver.
2123 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00002124 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2125 if (Result.isInvalid())
2126 return ExprError();
2127 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00002128 ReceiverType = Receiver->getType();
2129 }
2130
Douglas Gregorf49bb082010-04-22 17:01:48 +00002131 if (!Method) {
2132 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00002133 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002134 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00002135 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2136 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002137 SourceRange(LBracLoc, RBracLoc),
2138 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002139 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00002140 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002141 SourceRange(LBracLoc, RBracLoc),
2142 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002143 } else if (ReceiverType->isObjCClassType() ||
2144 ReceiverType->isObjCQualifiedClassType()) {
2145 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002146 // We allow sending a message to a qualified Class ("Class<foo>"), which
2147 // is ok as long as one of the protocols implements the selector (if not, warn).
2148 if (const ObjCObjectPointerType *QClassTy
2149 = ReceiverType->getAsObjCQualifiedClassType()) {
2150 // Search protocols for class methods.
2151 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2152 if (!Method) {
2153 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2154 // warn if instance method found for a Class message.
2155 if (Method) {
2156 Diag(Loc, diag::warn_instance_method_on_class_found)
2157 << Method->getSelector() << Sel;
Ted Kremenek3306ec12012-02-27 22:55:11 +00002158 Diag(Method->getLocation(), diag::note_method_declared_at)
2159 << Method->getDeclName();
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002160 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00002161 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002162 } else {
2163 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2164 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2165 // First check the public methods in the class interface.
2166 Method = ClassDecl->lookupClassMethod(Sel);
2167
2168 if (!Method)
2169 Method = LookupPrivateClassMethod(Sel, ClassDecl);
2170 }
2171 if (Method && DiagnoseUseOfDecl(Method, Loc))
2172 return ExprError();
2173 }
2174 if (!Method) {
2175 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00002176 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002177 Method = LookupFactoryMethodInGlobalPool(Sel,
2178 SourceRange(LBracLoc, RBracLoc),
2179 true);
2180 if (!Method) {
2181 // If no class (factory) method was found, check if an _instance_
2182 // method of the same name exists in the root class only.
2183 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002184 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002185 true);
2186 if (Method)
2187 if (const ObjCInterfaceDecl *ID =
2188 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2189 if (ID->getSuperClass())
2190 Diag(Loc, diag::warn_root_inst_method_not_found)
2191 << Sel << SourceRange(LBracLoc, RBracLoc);
2192 }
2193 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002194 }
2195 }
2196 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002197 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002198 ObjCInterfaceDecl* ClassDecl = 0;
2199
2200 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2201 // long as one of the protocols implements the selector (if not, warn).
2202 if (const ObjCObjectPointerType *QIdTy
2203 = ReceiverType->getAsObjCQualifiedIdType()) {
2204 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002205 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2206 if (!Method)
2207 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002208 } else if (const ObjCObjectPointerType *OCIType
2209 = ReceiverType->getAsObjCInterfacePointerType()) {
2210 // We allow sending a message to a pointer to an interface (an object).
2211 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00002212
Douglas Gregorb3029962011-11-14 22:10:01 +00002213 // Try to complete the type. Under ARC, this is a hard error from which
2214 // we don't try to recover.
2215 const ObjCInterfaceDecl *forwardClass = 0;
2216 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002217 getLangOpts().ObjCAutoRefCount
Douglas Gregorb3029962011-11-14 22:10:01 +00002218 ? PDiag(diag::err_arc_receiver_forward_instance)
2219 << (Receiver ? Receiver->getSourceRange()
2220 : SourceRange(SuperLoc))
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00002221 : PDiag(diag::warn_receiver_forward_instance)
2222 << (Receiver ? Receiver->getSourceRange()
2223 : SourceRange(SuperLoc)))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002224 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregorb3029962011-11-14 22:10:01 +00002225 return ExprError();
2226
2227 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00002228 Diag(Receiver ? Receiver->getLocStart()
2229 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00002230 Method = 0;
2231 } else {
2232 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCallf85e1932011-06-15 23:02:42 +00002233 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002234
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002235 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002236 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002237 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2238
Douglas Gregorf49bb082010-04-22 17:01:48 +00002239 if (!Method) {
2240 // If we have implementations in scope, check "private" methods.
2241 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
2242
David Blaikie4e4d0842012-03-11 07:00:24 +00002243 if (!Method && getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002244 Diag(Loc, diag::err_arc_may_not_respond)
2245 << OCIType->getPointeeType() << Sel;
2246 return ExprError();
2247 }
2248
Douglas Gregorc737acb2011-09-27 16:10:05 +00002249 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002250 // If we still haven't found a method, look in the global pool. This
2251 // behavior isn't very desirable, however we need it for GCC
2252 // compatibility. FIXME: should we deviate??
2253 if (OCIType->qual_empty()) {
2254 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002255 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002256 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002257 Diag(Loc, diag::warn_maynot_respond)
2258 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
2259 }
2260 }
2261 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002262 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00002263 return ExprError();
David Blaikie4e4d0842012-03-11 07:00:24 +00002264 } else if (!getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002265 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00002266 (ReceiverType->isPointerType() ||
2267 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002268 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00002269 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00002270 Diag(Loc, diag::warn_bad_receiver_type)
2271 << ReceiverType
2272 << Receiver->getSourceRange();
2273 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00002274 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002275 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00002276 else {
2277 // TODO: specialized warning on null receivers?
2278 bool IsNull = Receiver->isNullPointerConstant(Context,
2279 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00002280 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2281 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00002282 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002283 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00002284 } else {
John Wiegley429bb272011-04-08 18:41:53 +00002285 ExprResult ReceiverRes;
David Blaikie4e4d0842012-03-11 07:00:24 +00002286 if (getLangOpts().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00002287 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00002288 if (ReceiverRes.isUsable()) {
2289 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00002290 return BuildInstanceMessage(Receiver,
2291 ReceiverType,
2292 SuperLoc,
2293 Sel,
2294 Method,
2295 LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002296 SelectorLocs,
John Wiegley429bb272011-04-08 18:41:53 +00002297 RBracLoc,
2298 move(ArgsIn));
2299 } else {
2300 // Reject other random receiver types (e.g. structs).
2301 Diag(Loc, diag::err_bad_receiver_type)
2302 << ReceiverType << Receiver->getSourceRange();
2303 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00002304 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002305 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002306 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00002307 }
Mike Stump1eb44332009-09-09 15:08:12 +00002308
Douglas Gregor2725ca82010-04-21 19:57:20 +00002309 // Check the message arguments.
2310 unsigned NumArgs = ArgsIn.size();
2311 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2312 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00002313 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00002314 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2315 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00002316 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
2317 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00002318 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00002319 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00002320
Douglas Gregor483dd2f2011-01-11 03:23:19 +00002321 if (Method && !Method->getResultType()->isVoidType() &&
2322 RequireCompleteType(LBracLoc, Method->getResultType(),
2323 diag::err_illegal_message_expr_incomplete_type))
2324 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002325
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002326 SourceLocation SelLoc = SelectorLocs.front();
2327
John McCallf85e1932011-06-15 23:02:42 +00002328 // In ARC, forbid the user from sending messages to
2329 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002330 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002331 ObjCMethodFamily family =
2332 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2333 switch (family) {
2334 case OMF_init:
2335 if (Method)
2336 checkInitMethod(Method, ReceiverType);
2337
2338 case OMF_None:
2339 case OMF_alloc:
2340 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00002341 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00002342 case OMF_mutableCopy:
2343 case OMF_new:
2344 case OMF_self:
2345 break;
2346
2347 case OMF_dealloc:
2348 case OMF_retain:
2349 case OMF_release:
2350 case OMF_autorelease:
2351 case OMF_retainCount:
2352 Diag(Loc, diag::err_arc_illegal_explicit_message)
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002353 << Sel << SelLoc;
John McCallf85e1932011-06-15 23:02:42 +00002354 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002355
2356 case OMF_performSelector:
2357 if (Method && NumArgs >= 1) {
2358 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2359 Selector ArgSel = SelExp->getSelector();
2360 ObjCMethodDecl *SelMethod =
2361 LookupInstanceMethodInGlobalPool(ArgSel,
2362 SelExp->getSourceRange());
2363 if (!SelMethod)
2364 SelMethod =
2365 LookupFactoryMethodInGlobalPool(ArgSel,
2366 SelExp->getSourceRange());
2367 if (SelMethod) {
2368 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2369 switch (SelFamily) {
2370 case OMF_alloc:
2371 case OMF_copy:
2372 case OMF_mutableCopy:
2373 case OMF_new:
2374 case OMF_self:
2375 case OMF_init:
2376 // Issue error, unless ns_returns_not_retained.
2377 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2378 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002379 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002380 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002381 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2382 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002383 }
2384 break;
2385 default:
2386 // +0 call. OK. unless ns_returns_retained.
2387 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2388 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002389 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002390 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002391 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2392 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002393 }
2394 break;
2395 }
2396 }
2397 } else {
2398 // error (may leak).
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002399 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002400 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2401 }
2402 }
2403 break;
John McCallf85e1932011-06-15 23:02:42 +00002404 }
2405 }
2406
Douglas Gregor2725ca82010-04-21 19:57:20 +00002407 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00002408 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00002409 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00002410 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002411 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002412 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002413 makeArrayRef(Args, NumArgs), RBracLoc,
2414 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002415 else {
John McCallf89e55a2010-11-18 06:31:45 +00002416 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002417 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002418 makeArrayRef(Args, NumArgs), RBracLoc,
2419 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002420 if (!isImplicit)
2421 checkCocoaAPI(*this, Result);
2422 }
John McCallf85e1932011-06-15 23:02:42 +00002423
David Blaikie4e4d0842012-03-11 07:00:24 +00002424 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian98795562012-04-19 23:49:39 +00002425 DiagnoseARCUseOfWeakReceiver(*this, Receiver);
Fariborz Jahanian878f8502012-04-04 20:05:25 +00002426
John McCallf85e1932011-06-15 23:02:42 +00002427 // In ARC, annotate delegate init calls.
2428 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00002429 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00002430 // Only consider init calls *directly* in init implementations,
2431 // not within blocks.
2432 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2433 if (method && method->getMethodFamily() == OMF_init) {
2434 // The implicit assignment to self means we also don't want to
2435 // consume the result.
2436 Result->setDelegateInitCall(true);
2437 return Owned(Result);
2438 }
2439 }
2440
2441 // In ARC, check for message sends which are likely to introduce
2442 // retain cycles.
2443 checkRetainCycles(Result);
2444 }
2445
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002446 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00002447}
2448
2449// ActOnInstanceMessage - used for both unary and keyword messages.
2450// ArgExprs is optional - if it is present, the number of expressions
2451// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00002452ExprResult Sema::ActOnInstanceMessage(Scope *S,
2453 Expr *Receiver,
2454 Selector Sel,
2455 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002456 ArrayRef<SourceLocation> SelectorLocs,
John McCall60d7b3a2010-08-24 06:29:42 +00002457 SourceLocation RBracLoc,
2458 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002459 if (!Receiver)
2460 return ExprError();
2461
John McCall9ae2f072010-08-23 23:25:46 +00002462 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00002463 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002464 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00002465}
Chris Lattnereca7be62008-04-07 05:30:13 +00002466
John McCallf85e1932011-06-15 23:02:42 +00002467enum ARCConversionTypeClass {
John McCall2cf031d2011-10-01 01:01:08 +00002468 /// int, void, struct A
John McCallf85e1932011-06-15 23:02:42 +00002469 ACTC_none,
John McCall2cf031d2011-10-01 01:01:08 +00002470
2471 /// id, void (^)()
John McCallf85e1932011-06-15 23:02:42 +00002472 ACTC_retainable,
John McCall2cf031d2011-10-01 01:01:08 +00002473
2474 /// id*, id***, void (^*)(),
2475 ACTC_indirectRetainable,
2476
2477 /// void* might be a normal C type, or it might a CF type.
2478 ACTC_voidPtr,
2479
2480 /// struct A*
2481 ACTC_coreFoundation
John McCallf85e1932011-06-15 23:02:42 +00002482};
John McCall2cf031d2011-10-01 01:01:08 +00002483static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2484 return (ACTC == ACTC_retainable ||
2485 ACTC == ACTC_coreFoundation ||
2486 ACTC == ACTC_voidPtr);
2487}
2488static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2489 return ACTC == ACTC_none ||
2490 ACTC == ACTC_voidPtr ||
2491 ACTC == ACTC_coreFoundation;
2492}
2493
John McCallf85e1932011-06-15 23:02:42 +00002494static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCall2cf031d2011-10-01 01:01:08 +00002495 bool isIndirect = false;
John McCallf85e1932011-06-15 23:02:42 +00002496
2497 // Ignore an outermost reference type.
John McCall2cf031d2011-10-01 01:01:08 +00002498 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCallf85e1932011-06-15 23:02:42 +00002499 type = ref->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002500 isIndirect = true;
2501 }
John McCallf85e1932011-06-15 23:02:42 +00002502
2503 // Drill through pointers and arrays recursively.
2504 while (true) {
2505 if (const PointerType *ptr = type->getAs<PointerType>()) {
2506 type = ptr->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002507
2508 // The first level of pointer may be the innermost pointer on a CF type.
2509 if (!isIndirect) {
2510 if (type->isVoidType()) return ACTC_voidPtr;
2511 if (type->isRecordType()) return ACTC_coreFoundation;
2512 }
John McCallf85e1932011-06-15 23:02:42 +00002513 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2514 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2515 } else {
2516 break;
2517 }
John McCall2cf031d2011-10-01 01:01:08 +00002518 isIndirect = true;
John McCallf85e1932011-06-15 23:02:42 +00002519 }
2520
John McCall2cf031d2011-10-01 01:01:08 +00002521 if (isIndirect) {
2522 if (type->isObjCARCBridgableType())
2523 return ACTC_indirectRetainable;
2524 return ACTC_none;
2525 }
2526
2527 if (type->isObjCARCBridgableType())
2528 return ACTC_retainable;
2529
2530 return ACTC_none;
John McCallf85e1932011-06-15 23:02:42 +00002531}
2532
2533namespace {
John McCall2cf031d2011-10-01 01:01:08 +00002534 /// A result from the cast checker.
2535 enum ACCResult {
2536 /// Cannot be casted.
2537 ACC_invalid,
2538
2539 /// Can be safely retained or not retained.
2540 ACC_bottom,
2541
2542 /// Can be casted at +0.
2543 ACC_plusZero,
2544
2545 /// Can be casted at +1.
2546 ACC_plusOne
2547 };
2548 ACCResult merge(ACCResult left, ACCResult right) {
2549 if (left == right) return left;
2550 if (left == ACC_bottom) return right;
2551 if (right == ACC_bottom) return left;
2552 return ACC_invalid;
2553 }
2554
2555 /// A checker which white-lists certain expressions whose conversion
2556 /// to or from retainable type would otherwise be forbidden in ARC.
2557 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2558 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2559
John McCallf85e1932011-06-15 23:02:42 +00002560 ASTContext &Context;
John McCall2cf031d2011-10-01 01:01:08 +00002561 ARCConversionTypeClass SourceClass;
2562 ARCConversionTypeClass TargetClass;
2563
2564 static bool isCFType(QualType type) {
2565 // Someday this can use ns_bridged. For now, it has to do this.
2566 return type->isCARCBridgableType();
John McCallf85e1932011-06-15 23:02:42 +00002567 }
John McCall2cf031d2011-10-01 01:01:08 +00002568
2569 public:
2570 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2571 ARCConversionTypeClass target)
2572 : Context(Context), SourceClass(source), TargetClass(target) {}
2573
2574 using super::Visit;
2575 ACCResult Visit(Expr *e) {
2576 return super::Visit(e->IgnoreParens());
2577 }
2578
2579 ACCResult VisitStmt(Stmt *s) {
2580 return ACC_invalid;
2581 }
2582
2583 /// Null pointer constants can be casted however you please.
2584 ACCResult VisitExpr(Expr *e) {
2585 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2586 return ACC_bottom;
2587 return ACC_invalid;
2588 }
2589
2590 /// Objective-C string literals can be safely casted.
2591 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2592 // If we're casting to any retainable type, go ahead. Global
2593 // strings are immune to retains, so this is bottom.
2594 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2595
2596 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002597 }
2598
John McCall2cf031d2011-10-01 01:01:08 +00002599 /// Look through certain implicit and explicit casts.
2600 ACCResult VisitCastExpr(CastExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002601 switch (e->getCastKind()) {
2602 case CK_NullToPointer:
John McCall2cf031d2011-10-01 01:01:08 +00002603 return ACC_bottom;
2604
John McCallf85e1932011-06-15 23:02:42 +00002605 case CK_NoOp:
2606 case CK_LValueToRValue:
2607 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002608 case CK_CPointerToObjCPointerCast:
2609 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002610 case CK_AnyPointerToBlockPointerCast:
2611 return Visit(e->getSubExpr());
John McCall2cf031d2011-10-01 01:01:08 +00002612
John McCallf85e1932011-06-15 23:02:42 +00002613 default:
John McCall2cf031d2011-10-01 01:01:08 +00002614 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002615 }
2616 }
John McCall2cf031d2011-10-01 01:01:08 +00002617
2618 /// Look through unary extension.
2619 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002620 return Visit(e->getSubExpr());
2621 }
John McCall2cf031d2011-10-01 01:01:08 +00002622
2623 /// Ignore the LHS of a comma operator.
2624 ACCResult VisitBinComma(BinaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002625 return Visit(e->getRHS());
2626 }
John McCall2cf031d2011-10-01 01:01:08 +00002627
2628 /// Conditional operators are okay if both sides are okay.
2629 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2630 ACCResult left = Visit(e->getTrueExpr());
2631 if (left == ACC_invalid) return ACC_invalid;
2632 return merge(left, Visit(e->getFalseExpr()));
John McCallf85e1932011-06-15 23:02:42 +00002633 }
John McCall2cf031d2011-10-01 01:01:08 +00002634
John McCall4b9c2d22011-11-06 09:01:30 +00002635 /// Look through pseudo-objects.
2636 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2637 // If we're getting here, we should always have a result.
2638 return Visit(e->getResultExpr());
2639 }
2640
John McCall2cf031d2011-10-01 01:01:08 +00002641 /// Statement expressions are okay if their result expression is okay.
2642 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002643 return Visit(e->getSubStmt()->body_back());
2644 }
John McCallf85e1932011-06-15 23:02:42 +00002645
John McCall2cf031d2011-10-01 01:01:08 +00002646 /// Some declaration references are okay.
2647 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2648 // References to global constants from system headers are okay.
2649 // These are things like 'kCFStringTransformToLatin'. They are
2650 // can also be assumed to be immune to retains.
2651 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2652 if (isAnyRetainable(TargetClass) &&
2653 isAnyRetainable(SourceClass) &&
2654 var &&
2655 var->getStorageClass() == SC_Extern &&
2656 var->getType().isConstQualified() &&
2657 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2658 return ACC_bottom;
2659 }
2660
2661 // Nothing else.
2662 return ACC_invalid;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00002663 }
John McCall2cf031d2011-10-01 01:01:08 +00002664
2665 /// Some calls are okay.
2666 ACCResult VisitCallExpr(CallExpr *e) {
2667 if (FunctionDecl *fn = e->getDirectCallee())
2668 if (ACCResult result = checkCallToFunction(fn))
2669 return result;
2670
2671 return super::VisitCallExpr(e);
2672 }
2673
2674 ACCResult checkCallToFunction(FunctionDecl *fn) {
2675 // Require a CF*Ref return type.
2676 if (!isCFType(fn->getResultType()))
2677 return ACC_invalid;
2678
2679 if (!isAnyRetainable(TargetClass))
2680 return ACC_invalid;
2681
2682 // Honor an explicit 'not retained' attribute.
2683 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2684 return ACC_plusZero;
2685
2686 // Honor an explicit 'retained' attribute, except that for
2687 // now we're not going to permit implicit handling of +1 results,
2688 // because it's a bit frightening.
2689 if (fn->hasAttr<CFReturnsRetainedAttr>())
2690 return ACC_invalid; // ACC_plusOne if we start accepting this
2691
2692 // Recognize this specific builtin function, which is used by CFSTR.
2693 unsigned builtinID = fn->getBuiltinID();
2694 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2695 return ACC_bottom;
2696
2697 // Otherwise, don't do anything implicit with an unaudited function.
2698 if (!fn->hasAttr<CFAuditedTransferAttr>())
2699 return ACC_invalid;
2700
2701 // Otherwise, it's +0 unless it follows the create convention.
2702 if (ento::coreFoundation::followsCreateRule(fn))
2703 return ACC_invalid; // ACC_plusOne if we start accepting this
2704
2705 return ACC_plusZero;
2706 }
2707
2708 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2709 return checkCallToMethod(e->getMethodDecl());
2710 }
2711
2712 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2713 ObjCMethodDecl *method;
2714 if (e->isExplicitProperty())
2715 method = e->getExplicitProperty()->getGetterMethodDecl();
2716 else
2717 method = e->getImplicitPropertyGetter();
2718 return checkCallToMethod(method);
2719 }
2720
2721 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2722 if (!method) return ACC_invalid;
2723
2724 // Check for message sends to functions returning CF types. We
2725 // just obey the Cocoa conventions with these, even though the
2726 // return type is CF.
2727 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2728 return ACC_invalid;
2729
2730 // If the method is explicitly marked not-retained, it's +0.
2731 if (method->hasAttr<CFReturnsNotRetainedAttr>())
2732 return ACC_plusZero;
2733
2734 // If the method is explicitly marked as returning retained, or its
2735 // selector follows a +1 Cocoa convention, treat it as +1.
2736 if (method->hasAttr<CFReturnsRetainedAttr>())
2737 return ACC_plusOne;
2738
2739 switch (method->getSelector().getMethodFamily()) {
2740 case OMF_alloc:
2741 case OMF_copy:
2742 case OMF_mutableCopy:
2743 case OMF_new:
2744 return ACC_plusOne;
2745
2746 default:
2747 // Otherwise, treat it as +0.
2748 return ACC_plusZero;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00002749 }
2750 }
John McCall2cf031d2011-10-01 01:01:08 +00002751 };
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00002752}
2753
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002754static bool
2755KnownName(Sema &S, const char *name) {
2756 LookupResult R(S, &S.Context.Idents.get(name), SourceLocation(),
2757 Sema::LookupOrdinaryName);
2758 return S.LookupName(R, S.TUScope, false);
2759}
2760
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002761static void addFixitForObjCARCConversion(Sema &S,
2762 DiagnosticBuilder &DiagB,
2763 Sema::CheckedConversionKind CCK,
2764 SourceLocation afterLParen,
2765 QualType castType,
2766 Expr *castExpr,
2767 const char *bridgeKeyword,
2768 const char *CFBridgeName) {
2769 // We handle C-style and implicit casts here.
2770 switch (CCK) {
2771 case Sema::CCK_ImplicitConversion:
2772 case Sema::CCK_CStyleCast:
2773 break;
2774 case Sema::CCK_FunctionalCast:
2775 case Sema::CCK_OtherCast:
2776 return;
2777 }
2778
2779 if (CFBridgeName) {
2780 Expr *castedE = castExpr;
2781 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2782 castedE = CCE->getSubExpr();
2783 castedE = castedE->IgnoreImpCasts();
2784 SourceRange range = castedE->getSourceRange();
2785 if (isa<ParenExpr>(castedE)) {
2786 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2787 CFBridgeName));
2788 } else {
2789 std::string namePlusParen = CFBridgeName;
2790 namePlusParen += "(";
2791 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2792 namePlusParen));
2793 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2794 S.PP.getLocForEndOfToken(range.getEnd()),
2795 ")"));
2796 }
2797 return;
2798 }
2799
2800 if (CCK == Sema::CCK_CStyleCast) {
2801 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
2802 } else {
2803 std::string castCode = "(";
2804 castCode += bridgeKeyword;
2805 castCode += castType.getAsString();
2806 castCode += ")";
2807 Expr *castedE = castExpr->IgnoreImpCasts();
2808 SourceRange range = castedE->getSourceRange();
2809 if (isa<ParenExpr>(castedE)) {
2810 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2811 castCode));
2812 } else {
2813 castCode += "(";
2814 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2815 castCode));
2816 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2817 S.PP.getLocForEndOfToken(range.getEnd()),
2818 ")"));
2819 }
2820 }
2821}
2822
John McCall5acb0c92011-10-17 18:40:02 +00002823static void
2824diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
2825 QualType castType, ARCConversionTypeClass castACTC,
2826 Expr *castExpr, ARCConversionTypeClass exprACTC,
2827 Sema::CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00002828 SourceLocation loc =
John McCall2cf031d2011-10-01 01:01:08 +00002829 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00002830
John McCall5acb0c92011-10-17 18:40:02 +00002831 if (S.makeUnavailableInSystemHeader(loc,
John McCall2cf031d2011-10-01 01:01:08 +00002832 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCallf85e1932011-06-15 23:02:42 +00002833 return;
John McCall5acb0c92011-10-17 18:40:02 +00002834
2835 QualType castExprType = castExpr->getType();
John McCallf85e1932011-06-15 23:02:42 +00002836
John McCall71c482c2011-06-17 06:50:50 +00002837 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00002838 switch (exprACTC) {
John McCall2cf031d2011-10-01 01:01:08 +00002839 case ACTC_none:
2840 case ACTC_coreFoundation:
2841 case ACTC_voidPtr:
2842 srcKind = (castExprType->isPointerType() ? 1 : 0);
2843 break;
2844 case ACTC_retainable:
2845 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
2846 break;
2847 case ACTC_indirectRetainable:
2848 srcKind = 4;
2849 break;
John McCallf85e1932011-06-15 23:02:42 +00002850 }
2851
John McCall5acb0c92011-10-17 18:40:02 +00002852 // Check whether this could be fixed with a bridge cast.
2853 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
2854 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCallf85e1932011-06-15 23:02:42 +00002855
John McCall5acb0c92011-10-17 18:40:02 +00002856 // Bridge from an ARC type to a CF type.
2857 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002858
John McCall5acb0c92011-10-17 18:40:02 +00002859 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2860 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2861 << 2 // of C pointer type
2862 << castExprType
2863 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
2864 << castType
2865 << castRange
2866 << castExpr->getSourceRange();
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002867 bool br = KnownName(S, "CFBridgingRelease");
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002868 {
2869 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2870 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2871 castType, castExpr, "__bridge ", 0);
2872 }
2873 {
2874 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_transfer)
2875 << castExprType << br;
2876 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2877 castType, castExpr, "__bridge_transfer ",
2878 br ? "CFBridgingRelease" : 0);
2879 }
John McCall5acb0c92011-10-17 18:40:02 +00002880
2881 return;
2882 }
2883
2884 // Bridge from a CF type to an ARC type.
2885 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002886 bool br = KnownName(S, "CFBridgingRetain");
John McCall5acb0c92011-10-17 18:40:02 +00002887 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2888 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2889 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
2890 << castExprType
2891 << 2 // to C pointer type
2892 << castType
2893 << castRange
2894 << castExpr->getSourceRange();
2895
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002896 {
2897 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2898 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2899 castType, castExpr, "__bridge ", 0);
2900 }
2901 {
2902 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_retained)
2903 << castType << br;
2904 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2905 castType, castExpr, "__bridge_retained ",
2906 br ? "CFBridgingRetain" : 0);
2907 }
John McCall5acb0c92011-10-17 18:40:02 +00002908
2909 return;
John McCallf85e1932011-06-15 23:02:42 +00002910 }
2911
John McCall5acb0c92011-10-17 18:40:02 +00002912 S.Diag(loc, diag::err_arc_mismatched_cast)
2913 << (CCK != Sema::CCK_ImplicitConversion)
2914 << srcKind << castExprType << castType
John McCallf85e1932011-06-15 23:02:42 +00002915 << castRange << castExpr->getSourceRange();
2916}
2917
John McCall5acb0c92011-10-17 18:40:02 +00002918Sema::ARCConversionResult
2919Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
2920 Expr *&castExpr, CheckedConversionKind CCK) {
2921 QualType castExprType = castExpr->getType();
2922
2923 // For the purposes of the classification, we assume reference types
2924 // will bind to temporaries.
2925 QualType effCastType = castType;
2926 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
2927 effCastType = ref->getPointeeType();
2928
2929 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
2930 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002931 if (exprACTC == castACTC) {
2932 // check for viablity and report error if casting an rvalue to a
2933 // life-time qualifier.
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002934 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002935 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002936 (castType != castExprType)) {
2937 const Type *DT = castType.getTypePtr();
2938 QualType QDT = castType;
2939 // We desugar some types but not others. We ignore those
2940 // that cannot happen in a cast; i.e. auto, and those which
2941 // should not be de-sugared; i.e typedef.
2942 if (const ParenType *PT = dyn_cast<ParenType>(DT))
2943 QDT = PT->desugar();
2944 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
2945 QDT = TP->desugar();
2946 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
2947 QDT = AT->desugar();
2948 if (QDT != castType &&
2949 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
2950 SourceLocation loc =
2951 (castRange.isValid() ? castRange.getBegin()
2952 : castExpr->getExprLoc());
2953 Diag(loc, diag::err_arc_nolifetime_behavior);
2954 }
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002955 }
2956 return ACR_okay;
2957 }
2958
John McCall5acb0c92011-10-17 18:40:02 +00002959 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
2960
2961 // Allow all of these types to be cast to integer types (but not
2962 // vice-versa).
2963 if (castACTC == ACTC_none && castType->isIntegralType(Context))
2964 return ACR_okay;
2965
2966 // Allow casts between pointers to lifetime types (e.g., __strong id*)
2967 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
2968 // must be explicit.
2969 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
2970 return ACR_okay;
2971 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
2972 CCK != CCK_ImplicitConversion)
2973 return ACR_okay;
2974
2975 switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
2976 // For invalid casts, fall through.
2977 case ACC_invalid:
2978 break;
2979
2980 // Do nothing for both bottom and +0.
2981 case ACC_bottom:
2982 case ACC_plusZero:
2983 return ACR_okay;
2984
2985 // If the result is +1, consume it here.
2986 case ACC_plusOne:
2987 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
2988 CK_ARCConsumeObject, castExpr,
2989 0, VK_RValue);
2990 ExprNeedsCleanups = true;
2991 return ACR_okay;
2992 }
2993
2994 // If this is a non-implicit cast from id or block type to a
2995 // CoreFoundation type, delay complaining in case the cast is used
2996 // in an acceptable context.
2997 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
2998 CCK != CCK_ImplicitConversion)
2999 return ACR_unbridged;
3000
3001 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3002 castExpr, exprACTC, CCK);
3003 return ACR_okay;
3004}
3005
3006/// Given that we saw an expression with the ARCUnbridgedCastTy
3007/// placeholder type, complain bitterly.
3008void Sema::diagnoseARCUnbridgedCast(Expr *e) {
3009 // We expect the spurious ImplicitCastExpr to already have been stripped.
3010 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3011 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
3012
3013 SourceRange castRange;
3014 QualType castType;
3015 CheckedConversionKind CCK;
3016
3017 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3018 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3019 castType = cast->getTypeAsWritten();
3020 CCK = CCK_CStyleCast;
3021 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3022 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3023 castType = cast->getTypeAsWritten();
3024 CCK = CCK_OtherCast;
3025 } else {
3026 castType = cast->getType();
3027 CCK = CCK_ImplicitConversion;
3028 }
3029
3030 ARCConversionTypeClass castACTC =
3031 classifyTypeForARCConversion(castType.getNonReferenceType());
3032
3033 Expr *castExpr = realCast->getSubExpr();
3034 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3035
3036 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3037 castExpr, ACTC_retainable, CCK);
3038}
3039
3040/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3041/// type, remove the placeholder cast.
3042Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3043 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3044
3045 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3046 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3047 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3048 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3049 assert(uo->getOpcode() == UO_Extension);
3050 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3051 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3052 sub->getValueKind(), sub->getObjectKind(),
3053 uo->getOperatorLoc());
3054 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3055 assert(!gse->isResultDependent());
3056
3057 unsigned n = gse->getNumAssocs();
3058 SmallVector<Expr*, 4> subExprs(n);
3059 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3060 for (unsigned i = 0; i != n; ++i) {
3061 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3062 Expr *sub = gse->getAssocExpr(i);
3063 if (i == gse->getResultIndex())
3064 sub = stripARCUnbridgedCast(sub);
3065 subExprs[i] = sub;
3066 }
3067
3068 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3069 gse->getControllingExpr(),
3070 subTypes.data(), subExprs.data(),
3071 n, gse->getDefaultLoc(),
3072 gse->getRParenLoc(),
3073 gse->containsUnexpandedParameterPack(),
3074 gse->getResultIndex());
3075 } else {
3076 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3077 return cast<ImplicitCastExpr>(e)->getSubExpr();
3078 }
3079}
3080
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00003081bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3082 QualType exprType) {
3083 QualType canCastType =
3084 Context.getCanonicalType(castType).getUnqualifiedType();
3085 QualType canExprType =
3086 Context.getCanonicalType(exprType).getUnqualifiedType();
3087 if (isa<ObjCObjectPointerType>(canCastType) &&
3088 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3089 canExprType->isObjCObjectPointerType()) {
3090 if (const ObjCObjectPointerType *ObjT =
3091 canExprType->getAs<ObjCObjectPointerType>())
3092 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
3093 return false;
3094 }
3095 return true;
3096}
3097
John McCall7e5e5f42011-07-07 06:58:02 +00003098/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3099static Expr *maybeUndoReclaimObject(Expr *e) {
3100 // For now, we just undo operands that are *immediately* reclaim
3101 // expressions, which prevents the vast majority of potential
3102 // problems here. To catch them all, we'd need to rebuild arbitrary
3103 // value-propagating subexpressions --- we can't reliably rebuild
3104 // in-place because of expression sharing.
3105 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00003106 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00003107 return ice->getSubExpr();
3108
3109 return e;
3110}
3111
John McCallf85e1932011-06-15 23:02:42 +00003112ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3113 ObjCBridgeCastKind Kind,
3114 SourceLocation BridgeKeywordLoc,
3115 TypeSourceInfo *TSInfo,
3116 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00003117 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3118 if (SubResult.isInvalid()) return ExprError();
3119 SubExpr = SubResult.take();
3120
John McCallf85e1932011-06-15 23:02:42 +00003121 QualType T = TSInfo->getType();
3122 QualType FromType = SubExpr->getType();
3123
John McCall1d9b3b22011-09-09 05:25:32 +00003124 CastKind CK;
3125
John McCallf85e1932011-06-15 23:02:42 +00003126 bool MustConsume = false;
3127 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3128 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00003129 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00003130 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3131 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00003132 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3133 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00003134 switch (Kind) {
3135 case OBC_Bridge:
3136 break;
3137
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003138 case OBC_BridgeRetained: {
3139 bool br = KnownName(*this, "CFBridgingRelease");
John McCallf85e1932011-06-15 23:02:42 +00003140 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3141 << 2
3142 << FromType
3143 << (T->isBlockPointerType()? 1 : 0)
3144 << T
3145 << SubExpr->getSourceRange()
3146 << Kind;
3147 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3148 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3149 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003150 << FromType << br
John McCallf85e1932011-06-15 23:02:42 +00003151 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003152 br ? "CFBridgingRelease "
3153 : "__bridge_transfer ");
John McCallf85e1932011-06-15 23:02:42 +00003154
3155 Kind = OBC_Bridge;
3156 break;
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003157 }
John McCallf85e1932011-06-15 23:02:42 +00003158
3159 case OBC_BridgeTransfer:
3160 // We must consume the Objective-C object produced by the cast.
3161 MustConsume = true;
3162 break;
3163 }
3164 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3165 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00003166 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00003167 switch (Kind) {
3168 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00003169 // Reclaiming a value that's going to be __bridge-casted to CF
3170 // is very dangerous, so we don't do it.
3171 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00003172 break;
3173
3174 case OBC_BridgeRetained:
3175 // Produce the object before casting it.
3176 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00003177 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00003178 SubExpr, 0, VK_RValue);
3179 break;
3180
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003181 case OBC_BridgeTransfer: {
3182 bool br = KnownName(*this, "CFBridgingRetain");
John McCallf85e1932011-06-15 23:02:42 +00003183 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3184 << (FromType->isBlockPointerType()? 1 : 0)
3185 << FromType
3186 << 2
3187 << T
3188 << SubExpr->getSourceRange()
3189 << Kind;
3190
3191 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3192 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3193 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003194 << T << br
3195 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3196 br ? "CFBridgingRetain " : "__bridge_retained");
John McCallf85e1932011-06-15 23:02:42 +00003197
3198 Kind = OBC_Bridge;
3199 break;
3200 }
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003201 }
John McCallf85e1932011-06-15 23:02:42 +00003202 } else {
3203 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3204 << FromType << T << Kind
3205 << SubExpr->getSourceRange()
3206 << TSInfo->getTypeLoc().getSourceRange();
3207 return ExprError();
3208 }
3209
John McCall1d9b3b22011-09-09 05:25:32 +00003210 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00003211 BridgeKeywordLoc,
3212 TSInfo, SubExpr);
3213
3214 if (MustConsume) {
3215 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00003216 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00003217 0, VK_RValue);
3218 }
3219
3220 return Result;
3221}
3222
3223ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3224 SourceLocation LParenLoc,
3225 ObjCBridgeCastKind Kind,
3226 SourceLocation BridgeKeywordLoc,
3227 ParsedType Type,
3228 SourceLocation RParenLoc,
3229 Expr *SubExpr) {
3230 TypeSourceInfo *TSInfo = 0;
3231 QualType T = GetTypeFromParser(Type, &TSInfo);
3232 if (!TSInfo)
3233 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3234 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3235 SubExpr);
3236}