blob: c187a8deb768f170ef7f70a1b75c1de6d975aa0a [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 Jahanian289677d2012-04-19 21:44:57 +00001326void
1327Sema::DiagnoseARCUseOfWeakReceiver(NamedDecl *PDecl,
1328 QualType T, SourceLocation Loc) {
1329 if (!getLangOpts().ObjCAutoRefCount)
1330 return;
1331
1332 if (T.getObjCLifetime() == Qualifiers::OCL_Weak) {
1333 Diag(Loc, diag::warn_receiver_is_weak)
1334 << (!PDecl ? 0 : (isa<ObjCPropertyDecl>(PDecl) ? 1 : 2));
1335 if (PDecl) {
1336 if (isa<ObjCPropertyDecl>(PDecl))
1337 Diag(PDecl->getLocation(), diag::note_property_declare);
1338 else
1339 Diag(PDecl->getLocation(), diag::note_method_declared_at) << PDecl;
1340 }
1341 return;
1342 }
1343
1344 if (PDecl)
1345 if (ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(PDecl))
1346 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak) {
1347 Diag(Loc, diag::warn_receiver_is_weak) << 1;
1348 Diag(Prop->getLocation(), diag::note_property_declare);
1349 }
1350}
1351
Chris Lattner7f816522010-04-11 07:45:24 +00001352/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
1353/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +00001354ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +00001355HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001356 Expr *BaseExpr, SourceLocation OpLoc,
1357 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001358 SourceLocation MemberLoc,
1359 SourceLocation SuperLoc, QualType SuperType,
1360 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +00001361 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
1362 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +00001363
1364 if (MemberName.getNameKind() != DeclarationName::Identifier) {
1365 Diag(MemberLoc, diag::err_invalid_property_name)
1366 << MemberName << QualType(OPT, 0);
1367 return ExprError();
1368 }
1369
Chris Lattner7f816522010-04-11 07:45:24 +00001370 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregorb3029962011-11-14 22:10:01 +00001371 SourceRange BaseRange = Super? SourceRange(SuperLoc)
1372 : BaseExpr->getSourceRange();
1373 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
1374 PDiag(diag::err_property_not_found_forward_class)
1375 << MemberName << BaseRange))
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +00001376 return ExprError();
Douglas Gregorb3029962011-11-14 22:10:01 +00001377
Chris Lattner7f816522010-04-11 07:45:24 +00001378 // Search for a declared property first.
1379 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
1380 // Check whether we can reference this property.
1381 if (DiagnoseUseOfDecl(PD, MemberLoc))
1382 return ExprError();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001383 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001384 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001385 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001386 MemberLoc,
1387 SuperLoc, SuperType));
1388 else
John McCall3c3b7f92011-10-25 17:37:35 +00001389 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001390 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001391 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001392 }
1393 // Check protocols on qualified interfaces.
1394 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
1395 E = OPT->qual_end(); I != E; ++I)
1396 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1397 // Check whether we can reference this property.
1398 if (DiagnoseUseOfDecl(PD, MemberLoc))
1399 return ExprError();
Fariborz Jahanian289677d2012-04-19 21:44:57 +00001400
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001401 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +00001402 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1403 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001404 VK_LValue,
1405 OK_ObjCProperty,
1406 MemberLoc,
1407 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001408 else
John McCall3c3b7f92011-10-25 17:37:35 +00001409 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1410 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +00001411 VK_LValue,
1412 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001413 MemberLoc,
1414 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +00001415 }
1416 // If that failed, look for an "implicit" property by seeing if the nullary
1417 // selector is implemented.
1418
1419 // FIXME: The logic for looking up nullary and unary selectors should be
1420 // shared with the code in ActOnInstanceMessage.
1421
1422 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1423 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001424
1425 // May be founf in property's qualified list.
1426 if (!Getter)
1427 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +00001428
1429 // If this reference is in an @implementation, check for 'private' methods.
1430 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001431 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +00001432
1433 // Look through local category implementations associated with the class.
1434 if (!Getter)
1435 Getter = IFace->getCategoryInstanceMethod(Sel);
1436 if (Getter) {
1437 // Check if we can reference this property.
1438 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1439 return ExprError();
1440 }
1441 // If we found a getter then this may be a valid dot-reference, we
1442 // will look for the matching setter, in case it is needed.
1443 Selector SetterSel =
1444 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1445 PP.getSelectorTable(), Member);
1446 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001447
1448 // May be founf in property's qualified list.
1449 if (!Setter)
1450 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
1451
Chris Lattner7f816522010-04-11 07:45:24 +00001452 if (!Setter) {
1453 // If this reference is in an @implementation, also check for 'private'
1454 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +00001455 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +00001456 }
1457 // Look through local category implementations associated with the class.
1458 if (!Setter)
1459 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001460
Chris Lattner7f816522010-04-11 07:45:24 +00001461 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1462 return ExprError();
1463
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001464 if (Getter || Setter) {
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001465 if (Super)
John McCall12f78a62010-12-02 01:19:52 +00001466 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001467 Context.PseudoObjectTy,
1468 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001469 MemberLoc,
1470 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001471 else
John McCall12f78a62010-12-02 01:19:52 +00001472 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001473 Context.PseudoObjectTy,
1474 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001475 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001476
Chris Lattner7f816522010-04-11 07:45:24 +00001477 }
1478
1479 // Attempt to correct for typos in property names.
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001480 DeclFilterCCC<ObjCPropertyDecl> Validator;
1481 if (TypoCorrection Corrected = CorrectTypo(
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001482 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001483 NULL, Validator, IFace, false, OPT)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001484 ObjCPropertyDecl *Property =
1485 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001486 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +00001487 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001488 << MemberName << QualType(OPT, 0) << TypoResult
1489 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +00001490 Diag(Property->getLocation(), diag::note_previous_decl)
1491 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001492 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
1493 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001494 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +00001495 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001496 ObjCInterfaceDecl *ClassDeclared;
1497 if (ObjCIvarDecl *Ivar =
1498 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
1499 QualType T = Ivar->getType();
1500 if (const ObjCObjectPointerType * OBJPT =
1501 T->getAsObjCInterfacePointerType()) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001502 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
1503 PDiag(diag::err_property_not_as_forward_class)
1504 << MemberName << BaseExpr->getSourceRange()))
1505 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001506 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001507 Diag(MemberLoc,
1508 diag::err_ivar_access_using_property_syntax_suggest)
1509 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
1510 << FixItHint::CreateReplacement(OpLoc, "->");
1511 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +00001512 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +00001513
Chris Lattner7f816522010-04-11 07:45:24 +00001514 Diag(MemberLoc, diag::err_property_not_found)
1515 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001516 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +00001517 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +00001518 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +00001519 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +00001520}
1521
1522
1523
John McCall60d7b3a2010-08-24 06:29:42 +00001524ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +00001525ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
1526 IdentifierInfo &propertyName,
1527 SourceLocation receiverNameLoc,
1528 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +00001529
Douglas Gregorf06cdae2010-01-03 18:01:57 +00001530 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +00001531 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
1532 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +00001533
1534 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +00001535 if (IFace == 0) {
1536 // If the "receiver" is 'super' in a method, handle it as an expression-like
1537 // property reference.
John McCall26743b22011-02-03 09:00:02 +00001538 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001539 IsSuper = true;
1540
Eli Friedmanb942cb22012-02-03 22:47:37 +00001541 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnereb483eb2010-04-11 08:28:14 +00001542 if (CurMethod->isInstanceMethod()) {
1543 QualType T =
1544 Context.getObjCInterfaceType(CurMethod->getClassInterface());
1545 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001546
1547 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001548 /*BaseExpr*/0,
1549 SourceLocation()/*OpLoc*/,
1550 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001551 propertyNameLoc,
1552 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +00001553 }
Mike Stump1eb44332009-09-09 15:08:12 +00001554
Chris Lattnereb483eb2010-04-11 08:28:14 +00001555 // Otherwise, if this is a class method, try dispatching to our
1556 // superclass.
1557 IFace = CurMethod->getClassInterface()->getSuperClass();
1558 }
John McCall26743b22011-02-03 09:00:02 +00001559 }
Chris Lattnereb483eb2010-04-11 08:28:14 +00001560
1561 if (IFace == 0) {
1562 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
1563 return ExprError();
1564 }
1565 }
1566
1567 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +00001568 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001569 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001570
1571 // If this reference is in an @implementation, check for 'private' methods.
1572 if (!Getter)
1573 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1574 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001575 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001576 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001577
1578 if (Getter) {
1579 // FIXME: refactor/share with ActOnMemberReference().
1580 // Check if we can reference this property.
1581 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
1582 return ExprError();
1583 }
Mike Stump1eb44332009-09-09 15:08:12 +00001584
Steve Naroff61f72cb2009-03-09 21:12:44 +00001585 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +00001586 Selector SetterSel =
1587 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +00001588 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +00001589
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001590 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001591 if (!Setter) {
1592 // If this reference is in an @implementation, also check for 'private'
1593 // methods.
1594 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1595 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001596 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001597 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001598 }
1599 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +00001600 if (!Setter)
1601 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +00001602
1603 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
1604 return ExprError();
1605
1606 if (Getter || Setter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00001607 if (IsSuper)
1608 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001609 Context.PseudoObjectTy,
1610 VK_LValue, OK_ObjCProperty,
Douglas Gregor926df6c2011-06-11 01:09:30 +00001611 propertyNameLoc,
1612 receiverNameLoc,
1613 Context.getObjCInterfaceType(IFace)));
1614
John McCall12f78a62010-12-02 01:19:52 +00001615 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001616 Context.PseudoObjectTy,
1617 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +00001618 propertyNameLoc,
1619 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +00001620 }
1621 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
1622 << &propertyName << Context.getObjCInterfaceType(IFace));
1623}
1624
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001625namespace {
1626
1627class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
1628 public:
1629 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
1630 // Determine whether "super" is acceptable in the current context.
1631 if (Method && Method->getClassInterface())
1632 WantObjCSuper = Method->getClassInterface()->getSuperClass();
1633 }
1634
1635 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
1636 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
1637 candidate.isKeyword("super");
1638 }
1639};
1640
1641}
1642
Douglas Gregor47bd5432010-04-14 02:46:37 +00001643Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +00001644 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +00001645 SourceLocation NameLoc,
1646 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +00001647 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +00001648 ParsedType &ReceiverType) {
1649 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +00001650
Douglas Gregor47bd5432010-04-14 02:46:37 +00001651 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +00001652 // messaging super. If the identifier is "super" and there is a
1653 // trailing dot, it's an instance message.
1654 if (IsSuper && S->isInObjcMethodScope())
1655 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001656
1657 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1658 LookupName(Result, S);
1659
1660 switch (Result.getResultKind()) {
1661 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +00001662 // Normal name lookup didn't find anything. If we're in an
1663 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +00001664 // FIXME: This is a hack. Ivar lookup should be part of normal
1665 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +00001666 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidisccc9e762011-11-09 00:22:48 +00001667 if (!Method->getClassInterface()) {
1668 // Fall back: let the parser try to parse it as an instance message.
1669 return ObjCInstanceMessage;
1670 }
1671
Douglas Gregored464422010-04-19 20:09:36 +00001672 ObjCInterfaceDecl *ClassDeclared;
1673 if (Method->getClassInterface()->lookupInstanceVariable(Name,
1674 ClassDeclared))
1675 return ObjCInstanceMessage;
1676 }
Douglas Gregor95f42922010-10-14 22:11:03 +00001677
Douglas Gregor47bd5432010-04-14 02:46:37 +00001678 // Break out; we'll perform typo correction below.
1679 break;
1680
1681 case LookupResult::NotFoundInCurrentInstantiation:
1682 case LookupResult::FoundOverloaded:
1683 case LookupResult::FoundUnresolvedValue:
1684 case LookupResult::Ambiguous:
1685 Result.suppressDiagnostics();
1686 return ObjCInstanceMessage;
1687
1688 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +00001689 // If the identifier is a class or not, and there is a trailing dot,
1690 // it's an instance message.
1691 if (HasTrailingDot)
1692 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001693 // We found something. If it's a type, then we have a class
1694 // message. Otherwise, it's an instance message.
1695 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +00001696 QualType T;
1697 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
1698 T = Context.getObjCInterfaceType(Class);
1699 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
1700 T = Context.getTypeDeclType(Type);
1701 else
1702 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001703
Douglas Gregor1569f952010-04-21 20:38:13 +00001704 // We have a class message, and T is the type we're
1705 // messaging. Build source-location information for it.
1706 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +00001707 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +00001708 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001709 }
1710 }
1711
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001712 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001713 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
1714 Result.getLookupKind(), S, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001715 Validator)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001716 if (Corrected.isKeyword()) {
1717 // If we've found the keyword "super" (the only keyword that would be
1718 // returned by CorrectTypo), this is a send to super.
Douglas Gregoraaf87162010-04-14 20:04:41 +00001719 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001720 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +00001721 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +00001722 return ObjCSuperMessage;
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001723 } else if (ObjCInterfaceDecl *Class =
1724 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1725 // If we found a declaration, correct when it refers to an Objective-C
1726 // class.
1727 Diag(NameLoc, diag::err_unknown_receiver_suggest)
1728 << Name << Corrected.getCorrection()
1729 << FixItHint::CreateReplacement(SourceRange(NameLoc),
1730 Class->getNameAsString());
1731 Diag(Class->getLocation(), diag::note_previous_decl)
1732 << Corrected.getCorrection();
1733
1734 QualType T = Context.getObjCInterfaceType(Class);
1735 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
1736 ReceiverType = CreateParsedType(T, TSInfo);
1737 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +00001738 }
1739 }
1740
1741 // Fall back: let the parser try to parse it as an instance message.
1742 return ObjCInstanceMessage;
1743}
Steve Naroff61f72cb2009-03-09 21:12:44 +00001744
John McCall60d7b3a2010-08-24 06:29:42 +00001745ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001746 SourceLocation SuperLoc,
1747 Selector Sel,
1748 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001749 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001750 SourceLocation RBracLoc,
1751 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001752 // Determine whether we are inside a method or not.
Eli Friedmanb942cb22012-02-03 22:47:37 +00001753 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregorf95861a2010-04-21 20:01:04 +00001754 if (!Method) {
1755 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
1756 return ExprError();
1757 }
Chris Lattner85a932e2008-01-04 22:32:30 +00001758
Douglas Gregorf95861a2010-04-21 20:01:04 +00001759 ObjCInterfaceDecl *Class = Method->getClassInterface();
1760 if (!Class) {
1761 Diag(SuperLoc, diag::error_no_super_class_message)
1762 << Method->getDeclName();
1763 return ExprError();
1764 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001765
Douglas Gregorf95861a2010-04-21 20:01:04 +00001766 ObjCInterfaceDecl *Super = Class->getSuperClass();
1767 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001768 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +00001769 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
1770 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001771 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +00001772 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001773
Douglas Gregorf95861a2010-04-21 20:01:04 +00001774 // We are in a method whose class has a superclass, so 'super'
1775 // is acting as a keyword.
1776 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +00001777 if (Sel.getMethodFamily() == OMF_dealloc)
1778 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00001779 if (Sel.getMethodFamily() == OMF_finalize)
1780 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +00001781
Douglas Gregorf95861a2010-04-21 20:01:04 +00001782 // Since we are in an instance method, this is an instance
1783 // message to the superclass instance.
1784 QualType SuperTy = Context.getObjCInterfaceType(Super);
1785 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +00001786 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001787 Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001788 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001789 }
Douglas Gregorf95861a2010-04-21 20:01:04 +00001790
1791 // Since we are in a class method, this is a class message to
1792 // the superclass.
1793 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1794 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001795 SuperLoc, Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001796 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001797}
1798
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001799
1800ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1801 bool isSuperReceiver,
1802 SourceLocation Loc,
1803 Selector Sel,
1804 ObjCMethodDecl *Method,
1805 MultiExprArg Args) {
1806 TypeSourceInfo *receiverTypeInfo = 0;
1807 if (!ReceiverType.isNull())
1808 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1809
1810 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1811 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1812 Sel, Method, Loc, Loc, Loc, Args,
1813 /*isImplicit=*/true);
1814
1815}
1816
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001817static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg,
1818 unsigned DiagID,
1819 bool (*refactor)(const ObjCMessageExpr *,
1820 const NSAPI &, edit::Commit &)) {
1821 SourceLocation MsgLoc = Msg->getExprLoc();
1822 if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored)
1823 return;
1824
1825 SourceManager &SM = S.SourceMgr;
1826 edit::Commit ECommit(SM, S.LangOpts);
1827 if (refactor(Msg,*S.NSAPIObj, ECommit)) {
1828 DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID)
1829 << Msg->getSelector() << Msg->getSourceRange();
1830 // FIXME: Don't emit diagnostic at all if fixits are non-commitable.
1831 if (!ECommit.isCommitable())
1832 return;
1833 for (edit::Commit::edit_iterator
1834 I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) {
1835 const edit::Commit::Edit &Edit = *I;
1836 switch (Edit.Kind) {
1837 case edit::Commit::Act_Insert:
1838 Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc,
1839 Edit.Text,
1840 Edit.BeforePrev));
1841 break;
1842 case edit::Commit::Act_InsertFromRange:
1843 Builder.AddFixItHint(
1844 FixItHint::CreateInsertionFromRange(Edit.OrigLoc,
1845 Edit.getInsertFromRange(SM),
1846 Edit.BeforePrev));
1847 break;
1848 case edit::Commit::Act_Remove:
1849 Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM)));
1850 break;
1851 }
1852 }
1853 }
1854}
1855
1856static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) {
1857 applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use,
1858 edit::rewriteObjCRedundantCallWithLiteral);
1859}
1860
Douglas Gregor2725ca82010-04-21 19:57:20 +00001861/// \brief Build an Objective-C class message expression.
1862///
1863/// This routine takes care of both normal class messages and
1864/// class messages to the superclass.
1865///
1866/// \param ReceiverTypeInfo Type source information that describes the
1867/// receiver of this message. This may be NULL, in which case we are
1868/// sending to the superclass and \p SuperLoc must be a valid source
1869/// location.
1870
1871/// \param ReceiverType The type of the object receiving the
1872/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1873/// type as that refers to. For a superclass send, this is the type of
1874/// the superclass.
1875///
1876/// \param SuperLoc The location of the "super" keyword in a
1877/// superclass message.
1878///
1879/// \param Sel The selector to which the message is being sent.
1880///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001881/// \param Method The method that this class message is invoking, if
1882/// already known.
1883///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001884/// \param LBracLoc The location of the opening square bracket ']'.
1885///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001886/// \param RBrac The location of the closing square bracket ']'.
1887///
1888/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001889ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001890 QualType ReceiverType,
1891 SourceLocation SuperLoc,
1892 Selector Sel,
1893 ObjCMethodDecl *Method,
1894 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001895 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001896 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001897 MultiExprArg ArgsIn,
1898 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001899 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001900 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001901 if (LBracLoc.isInvalid()) {
1902 Diag(Loc, diag::err_missing_open_square_message_send)
1903 << FixItHint::CreateInsertion(Loc, "[");
1904 LBracLoc = Loc;
1905 }
1906
Douglas Gregor92e986e2010-04-22 16:44:27 +00001907 if (ReceiverType->isDependentType()) {
1908 // If the receiver type is dependent, we can't type-check anything
1909 // at this point. Build a dependent expression.
1910 unsigned NumArgs = ArgsIn.size();
1911 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1912 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001913 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1914 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001915 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001916 makeArrayRef(Args, NumArgs),RBracLoc,
1917 isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001918 }
Chris Lattner15faee12010-04-12 05:38:43 +00001919
Douglas Gregor2725ca82010-04-21 19:57:20 +00001920 // Find the class to which we are sending this message.
1921 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001922 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1923 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001924 Diag(Loc, diag::err_invalid_receiver_class_message)
1925 << ReceiverType;
1926 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001927 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001928 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001929 // objc++ diagnoses during typename annotation.
David Blaikie4e4d0842012-03-11 07:00:24 +00001930 if (!getLangOpts().CPlusPlus)
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001931 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001932 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001933 if (!Method) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001934 SourceRange TypeRange
1935 = SuperLoc.isValid()? SourceRange(SuperLoc)
1936 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
1937 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
David Blaikie4e4d0842012-03-11 07:00:24 +00001938 (getLangOpts().ObjCAutoRefCount
Douglas Gregorb3029962011-11-14 22:10:01 +00001939 ? PDiag(diag::err_arc_receiver_forward_class)
1940 : PDiag(diag::warn_receiver_forward_class))
1941 << TypeRange)) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001942 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001943 Method = LookupFactoryMethodInGlobalPool(Sel,
1944 SourceRange(LBracLoc, RBracLoc));
David Blaikie4e4d0842012-03-11 07:00:24 +00001945 if (Method && !getLangOpts().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001946 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1947 << Method->getDeclName();
1948 }
1949 if (!Method)
1950 Method = Class->lookupClassMethod(Sel);
1951
1952 // If we have an implementation in scope, check "private" methods.
1953 if (!Method)
1954 Method = LookupPrivateClassMethod(Sel, Class);
1955
1956 if (Method && DiagnoseUseOfDecl(Method, Loc))
1957 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001958 }
Mike Stump1eb44332009-09-09 15:08:12 +00001959
Douglas Gregor2725ca82010-04-21 19:57:20 +00001960 // Check the argument types and determine the result type.
1961 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001962 ExprValueKind VK = VK_RValue;
1963
Douglas Gregor2725ca82010-04-21 19:57:20 +00001964 unsigned NumArgs = ArgsIn.size();
1965 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001966 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1967 SuperLoc.isValid(), LBracLoc, RBracLoc,
1968 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001969 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001970
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001971 if (Method && !Method->getResultType()->isVoidType() &&
1972 RequireCompleteType(LBracLoc, Method->getResultType(),
1973 diag::err_illegal_message_expr_incomplete_type))
1974 return ExprError();
1975
Douglas Gregor2725ca82010-04-21 19:57:20 +00001976 // Construct the appropriate ObjCMessageExpr.
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001977 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001978 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001979 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001980 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001981 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001982 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001983 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001984 else {
John McCallf89e55a2010-11-18 06:31:45 +00001985 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001986 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001987 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001988 RBracLoc, isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001989 if (!isImplicit)
1990 checkCocoaAPI(*this, Result);
1991 }
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001992 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001993}
1994
Douglas Gregor2725ca82010-04-21 19:57:20 +00001995// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001996// ArgExprs is optional - if it is present, the number of expressions
1997// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001998ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001999 ParsedType Receiver,
2000 Selector Sel,
2001 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002002 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor77328d12010-09-15 23:19:31 +00002003 SourceLocation RBracLoc,
2004 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002005 TypeSourceInfo *ReceiverTypeInfo;
2006 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
2007 if (ReceiverType.isNull())
2008 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00002009
Mike Stump1eb44332009-09-09 15:08:12 +00002010
Douglas Gregor2725ca82010-04-21 19:57:20 +00002011 if (!ReceiverTypeInfo)
2012 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
2013
2014 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00002015 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002016 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00002017}
2018
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002019ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
2020 QualType ReceiverType,
2021 SourceLocation Loc,
2022 Selector Sel,
2023 ObjCMethodDecl *Method,
2024 MultiExprArg Args) {
2025 return BuildInstanceMessage(Receiver, ReceiverType,
2026 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
2027 Sel, Method, Loc, Loc, Loc, Args,
2028 /*isImplicit=*/true);
2029}
2030
Douglas Gregor2725ca82010-04-21 19:57:20 +00002031/// \brief Build an Objective-C instance message expression.
2032///
2033/// This routine takes care of both normal instance messages and
2034/// instance messages to the superclass instance.
2035///
2036/// \param Receiver The expression that computes the object that will
2037/// receive this message. This may be empty, in which case we are
2038/// sending to the superclass instance and \p SuperLoc must be a valid
2039/// source location.
2040///
2041/// \param ReceiverType The (static) type of the object receiving the
2042/// message. When a \p Receiver expression is provided, this is the
2043/// same type as that expression. For a superclass instance send, this
2044/// is a pointer to the type of the superclass.
2045///
2046/// \param SuperLoc The location of the "super" keyword in a
2047/// superclass instance message.
2048///
2049/// \param Sel The selector to which the message is being sent.
2050///
Douglas Gregorf49bb082010-04-22 17:01:48 +00002051/// \param Method The method that this instance message is invoking, if
2052/// already known.
2053///
Douglas Gregor2725ca82010-04-21 19:57:20 +00002054/// \param LBracLoc The location of the opening square bracket ']'.
2055///
Douglas Gregor2725ca82010-04-21 19:57:20 +00002056/// \param RBrac The location of the closing square bracket ']'.
2057///
2058/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00002059ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002060 QualType ReceiverType,
2061 SourceLocation SuperLoc,
2062 Selector Sel,
2063 ObjCMethodDecl *Method,
2064 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002065 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00002066 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002067 MultiExprArg ArgsIn,
2068 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00002069 // The location of the receiver.
2070 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
2071
2072 if (LBracLoc.isInvalid()) {
2073 Diag(Loc, diag::err_missing_open_square_message_send)
2074 << FixItHint::CreateInsertion(Loc, "[");
2075 LBracLoc = Loc;
2076 }
2077
Douglas Gregor2725ca82010-04-21 19:57:20 +00002078 // If we have a receiver expression, perform appropriate promotions
2079 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00002080 if (Receiver) {
John McCall5acb0c92011-10-17 18:40:02 +00002081 if (Receiver->hasPlaceholderType()) {
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00002082 ExprResult Result;
2083 if (Receiver->getType() == Context.UnknownAnyTy)
2084 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
2085 else
2086 Result = CheckPlaceholderExpr(Receiver);
2087 if (Result.isInvalid()) return ExprError();
2088 Receiver = Result.take();
John McCall5acb0c92011-10-17 18:40:02 +00002089 }
2090
Douglas Gregor92e986e2010-04-22 16:44:27 +00002091 if (Receiver->isTypeDependent()) {
2092 // If the receiver is type-dependent, we can't type-check anything
2093 // at this point. Build a dependent expression.
2094 unsigned NumArgs = ArgsIn.size();
2095 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2096 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
2097 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00002098 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002099 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00002100 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002101 RBracLoc, isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00002102 }
2103
Douglas Gregor2725ca82010-04-21 19:57:20 +00002104 // If necessary, apply function/array conversion to the receiver.
2105 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00002106 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
2107 if (Result.isInvalid())
2108 return ExprError();
2109 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00002110 ReceiverType = Receiver->getType();
2111 }
2112
Douglas Gregorf49bb082010-04-22 17:01:48 +00002113 if (!Method) {
2114 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00002115 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002116 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00002117 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
2118 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002119 SourceRange(LBracLoc, RBracLoc),
2120 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002121 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00002122 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002123 SourceRange(LBracLoc, RBracLoc),
2124 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002125 } else if (ReceiverType->isObjCClassType() ||
2126 ReceiverType->isObjCQualifiedClassType()) {
2127 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002128 // We allow sending a message to a qualified Class ("Class<foo>"), which
2129 // is ok as long as one of the protocols implements the selector (if not, warn).
2130 if (const ObjCObjectPointerType *QClassTy
2131 = ReceiverType->getAsObjCQualifiedClassType()) {
2132 // Search protocols for class methods.
2133 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
2134 if (!Method) {
2135 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
2136 // warn if instance method found for a Class message.
2137 if (Method) {
2138 Diag(Loc, diag::warn_instance_method_on_class_found)
2139 << Method->getSelector() << Sel;
Ted Kremenek3306ec12012-02-27 22:55:11 +00002140 Diag(Method->getLocation(), diag::note_method_declared_at)
2141 << Method->getDeclName();
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002142 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00002143 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002144 } else {
2145 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
2146 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
2147 // First check the public methods in the class interface.
2148 Method = ClassDecl->lookupClassMethod(Sel);
2149
2150 if (!Method)
2151 Method = LookupPrivateClassMethod(Sel, ClassDecl);
2152 }
2153 if (Method && DiagnoseUseOfDecl(Method, Loc))
2154 return ExprError();
2155 }
2156 if (!Method) {
2157 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00002158 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002159 Method = LookupFactoryMethodInGlobalPool(Sel,
2160 SourceRange(LBracLoc, RBracLoc),
2161 true);
2162 if (!Method) {
2163 // If no class (factory) method was found, check if an _instance_
2164 // method of the same name exists in the root class only.
2165 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002166 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00002167 true);
2168 if (Method)
2169 if (const ObjCInterfaceDecl *ID =
2170 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
2171 if (ID->getSuperClass())
2172 Diag(Loc, diag::warn_root_inst_method_not_found)
2173 << Sel << SourceRange(LBracLoc, RBracLoc);
2174 }
2175 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002176 }
2177 }
2178 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002179 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002180 ObjCInterfaceDecl* ClassDecl = 0;
2181
2182 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
2183 // long as one of the protocols implements the selector (if not, warn).
2184 if (const ObjCObjectPointerType *QIdTy
2185 = ReceiverType->getAsObjCQualifiedIdType()) {
2186 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002187 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
2188 if (!Method)
2189 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00002190 } else if (const ObjCObjectPointerType *OCIType
2191 = ReceiverType->getAsObjCInterfacePointerType()) {
2192 // We allow sending a message to a pointer to an interface (an object).
2193 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00002194
Douglas Gregorb3029962011-11-14 22:10:01 +00002195 // Try to complete the type. Under ARC, this is a hard error from which
2196 // we don't try to recover.
2197 const ObjCInterfaceDecl *forwardClass = 0;
2198 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002199 getLangOpts().ObjCAutoRefCount
Douglas Gregorb3029962011-11-14 22:10:01 +00002200 ? PDiag(diag::err_arc_receiver_forward_instance)
2201 << (Receiver ? Receiver->getSourceRange()
2202 : SourceRange(SuperLoc))
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00002203 : PDiag(diag::warn_receiver_forward_instance)
2204 << (Receiver ? Receiver->getSourceRange()
2205 : SourceRange(SuperLoc)))) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002206 if (getLangOpts().ObjCAutoRefCount)
Douglas Gregorb3029962011-11-14 22:10:01 +00002207 return ExprError();
2208
2209 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00002210 Diag(Receiver ? Receiver->getLocStart()
2211 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00002212 Method = 0;
2213 } else {
2214 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCallf85e1932011-06-15 23:02:42 +00002215 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002216
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002217 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002218 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00002219 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
2220
Douglas Gregorf49bb082010-04-22 17:01:48 +00002221 if (!Method) {
2222 // If we have implementations in scope, check "private" methods.
2223 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
2224
David Blaikie4e4d0842012-03-11 07:00:24 +00002225 if (!Method && getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002226 Diag(Loc, diag::err_arc_may_not_respond)
2227 << OCIType->getPointeeType() << Sel;
2228 return ExprError();
2229 }
2230
Douglas Gregorc737acb2011-09-27 16:10:05 +00002231 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002232 // If we still haven't found a method, look in the global pool. This
2233 // behavior isn't very desirable, however we need it for GCC
2234 // compatibility. FIXME: should we deviate??
2235 if (OCIType->qual_empty()) {
2236 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002237 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002238 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00002239 Diag(Loc, diag::warn_maynot_respond)
2240 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
2241 }
2242 }
2243 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00002244 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00002245 return ExprError();
David Blaikie4e4d0842012-03-11 07:00:24 +00002246 } else if (!getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002247 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00002248 (ReceiverType->isPointerType() ||
2249 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00002250 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00002251 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00002252 Diag(Loc, diag::warn_bad_receiver_type)
2253 << ReceiverType
2254 << Receiver->getSourceRange();
2255 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00002256 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002257 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00002258 else {
2259 // TODO: specialized warning on null receivers?
2260 bool IsNull = Receiver->isNullPointerConstant(Context,
2261 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00002262 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
2263 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00002264 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002265 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00002266 } else {
John Wiegley429bb272011-04-08 18:41:53 +00002267 ExprResult ReceiverRes;
David Blaikie4e4d0842012-03-11 07:00:24 +00002268 if (getLangOpts().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00002269 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00002270 if (ReceiverRes.isUsable()) {
2271 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00002272 return BuildInstanceMessage(Receiver,
2273 ReceiverType,
2274 SuperLoc,
2275 Sel,
2276 Method,
2277 LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002278 SelectorLocs,
John Wiegley429bb272011-04-08 18:41:53 +00002279 RBracLoc,
2280 move(ArgsIn));
2281 } else {
2282 // Reject other random receiver types (e.g. structs).
2283 Diag(Loc, diag::err_bad_receiver_type)
2284 << ReceiverType << Receiver->getSourceRange();
2285 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00002286 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00002287 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002288 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00002289 }
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Douglas Gregor2725ca82010-04-21 19:57:20 +00002291 // Check the message arguments.
2292 unsigned NumArgs = ArgsIn.size();
2293 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
2294 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00002295 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00002296 bool ClassMessage = (ReceiverType->isObjCClassType() ||
2297 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00002298 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
2299 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00002300 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00002301 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00002302
Douglas Gregor483dd2f2011-01-11 03:23:19 +00002303 if (Method && !Method->getResultType()->isVoidType() &&
2304 RequireCompleteType(LBracLoc, Method->getResultType(),
2305 diag::err_illegal_message_expr_incomplete_type))
2306 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002307
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002308 SourceLocation SelLoc = SelectorLocs.front();
2309
John McCallf85e1932011-06-15 23:02:42 +00002310 // In ARC, forbid the user from sending messages to
2311 // retain/release/autorelease/dealloc/retainCount explicitly.
David Blaikie4e4d0842012-03-11 07:00:24 +00002312 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +00002313 ObjCMethodFamily family =
2314 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
2315 switch (family) {
2316 case OMF_init:
2317 if (Method)
2318 checkInitMethod(Method, ReceiverType);
2319
2320 case OMF_None:
2321 case OMF_alloc:
2322 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00002323 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00002324 case OMF_mutableCopy:
2325 case OMF_new:
2326 case OMF_self:
2327 break;
2328
2329 case OMF_dealloc:
2330 case OMF_retain:
2331 case OMF_release:
2332 case OMF_autorelease:
2333 case OMF_retainCount:
2334 Diag(Loc, diag::err_arc_illegal_explicit_message)
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002335 << Sel << SelLoc;
John McCallf85e1932011-06-15 23:02:42 +00002336 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002337
2338 case OMF_performSelector:
2339 if (Method && NumArgs >= 1) {
2340 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
2341 Selector ArgSel = SelExp->getSelector();
2342 ObjCMethodDecl *SelMethod =
2343 LookupInstanceMethodInGlobalPool(ArgSel,
2344 SelExp->getSourceRange());
2345 if (!SelMethod)
2346 SelMethod =
2347 LookupFactoryMethodInGlobalPool(ArgSel,
2348 SelExp->getSourceRange());
2349 if (SelMethod) {
2350 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
2351 switch (SelFamily) {
2352 case OMF_alloc:
2353 case OMF_copy:
2354 case OMF_mutableCopy:
2355 case OMF_new:
2356 case OMF_self:
2357 case OMF_init:
2358 // Issue error, unless ns_returns_not_retained.
2359 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
2360 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002361 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002362 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002363 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2364 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002365 }
2366 break;
2367 default:
2368 // +0 call. OK. unless ns_returns_retained.
2369 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
2370 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002371 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002372 diag::err_arc_perform_selector_retains);
Ted Kremenek3306ec12012-02-27 22:55:11 +00002373 Diag(SelMethod->getLocation(), diag::note_method_declared_at)
2374 << SelMethod->getDeclName();
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002375 }
2376 break;
2377 }
2378 }
2379 } else {
2380 // error (may leak).
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002381 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanian9670e172011-07-05 22:38:59 +00002382 Diag(Args[0]->getExprLoc(), diag::note_used_here);
2383 }
2384 }
2385 break;
John McCallf85e1932011-06-15 23:02:42 +00002386 }
2387 }
2388
Douglas Gregor2725ca82010-04-21 19:57:20 +00002389 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00002390 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00002391 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00002392 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002393 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002394 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002395 makeArrayRef(Args, NumArgs), RBracLoc,
2396 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002397 else {
John McCallf89e55a2010-11-18 06:31:45 +00002398 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002399 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00002400 makeArrayRef(Args, NumArgs), RBracLoc,
2401 isImplicit);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002402 if (!isImplicit)
2403 checkCocoaAPI(*this, Result);
2404 }
John McCallf85e1932011-06-15 23:02:42 +00002405
David Blaikie4e4d0842012-03-11 07:00:24 +00002406 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian289677d2012-04-19 21:44:57 +00002407 if (Receiver)
2408 DiagnoseARCUseOfWeakReceiver(0 /* PDecl */,
2409 Receiver->IgnoreParenImpCasts()->getType(),
2410 Receiver->getLocStart());
Fariborz Jahanian878f8502012-04-04 20:05:25 +00002411
John McCallf85e1932011-06-15 23:02:42 +00002412 // In ARC, annotate delegate init calls.
2413 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00002414 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00002415 // Only consider init calls *directly* in init implementations,
2416 // not within blocks.
2417 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
2418 if (method && method->getMethodFamily() == OMF_init) {
2419 // The implicit assignment to self means we also don't want to
2420 // consume the result.
2421 Result->setDelegateInitCall(true);
2422 return Owned(Result);
2423 }
2424 }
2425
2426 // In ARC, check for message sends which are likely to introduce
2427 // retain cycles.
2428 checkRetainCycles(Result);
2429 }
2430
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00002431 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00002432}
2433
2434// ActOnInstanceMessage - used for both unary and keyword messages.
2435// ArgExprs is optional - if it is present, the number of expressions
2436// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00002437ExprResult Sema::ActOnInstanceMessage(Scope *S,
2438 Expr *Receiver,
2439 Selector Sel,
2440 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002441 ArrayRef<SourceLocation> SelectorLocs,
John McCall60d7b3a2010-08-24 06:29:42 +00002442 SourceLocation RBracLoc,
2443 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00002444 if (!Receiver)
2445 return ExprError();
2446
John McCall9ae2f072010-08-23 23:25:46 +00002447 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00002448 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00002449 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00002450}
Chris Lattnereca7be62008-04-07 05:30:13 +00002451
John McCallf85e1932011-06-15 23:02:42 +00002452enum ARCConversionTypeClass {
John McCall2cf031d2011-10-01 01:01:08 +00002453 /// int, void, struct A
John McCallf85e1932011-06-15 23:02:42 +00002454 ACTC_none,
John McCall2cf031d2011-10-01 01:01:08 +00002455
2456 /// id, void (^)()
John McCallf85e1932011-06-15 23:02:42 +00002457 ACTC_retainable,
John McCall2cf031d2011-10-01 01:01:08 +00002458
2459 /// id*, id***, void (^*)(),
2460 ACTC_indirectRetainable,
2461
2462 /// void* might be a normal C type, or it might a CF type.
2463 ACTC_voidPtr,
2464
2465 /// struct A*
2466 ACTC_coreFoundation
John McCallf85e1932011-06-15 23:02:42 +00002467};
John McCall2cf031d2011-10-01 01:01:08 +00002468static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
2469 return (ACTC == ACTC_retainable ||
2470 ACTC == ACTC_coreFoundation ||
2471 ACTC == ACTC_voidPtr);
2472}
2473static bool isAnyCLike(ARCConversionTypeClass ACTC) {
2474 return ACTC == ACTC_none ||
2475 ACTC == ACTC_voidPtr ||
2476 ACTC == ACTC_coreFoundation;
2477}
2478
John McCallf85e1932011-06-15 23:02:42 +00002479static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCall2cf031d2011-10-01 01:01:08 +00002480 bool isIndirect = false;
John McCallf85e1932011-06-15 23:02:42 +00002481
2482 // Ignore an outermost reference type.
John McCall2cf031d2011-10-01 01:01:08 +00002483 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCallf85e1932011-06-15 23:02:42 +00002484 type = ref->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002485 isIndirect = true;
2486 }
John McCallf85e1932011-06-15 23:02:42 +00002487
2488 // Drill through pointers and arrays recursively.
2489 while (true) {
2490 if (const PointerType *ptr = type->getAs<PointerType>()) {
2491 type = ptr->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00002492
2493 // The first level of pointer may be the innermost pointer on a CF type.
2494 if (!isIndirect) {
2495 if (type->isVoidType()) return ACTC_voidPtr;
2496 if (type->isRecordType()) return ACTC_coreFoundation;
2497 }
John McCallf85e1932011-06-15 23:02:42 +00002498 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
2499 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
2500 } else {
2501 break;
2502 }
John McCall2cf031d2011-10-01 01:01:08 +00002503 isIndirect = true;
John McCallf85e1932011-06-15 23:02:42 +00002504 }
2505
John McCall2cf031d2011-10-01 01:01:08 +00002506 if (isIndirect) {
2507 if (type->isObjCARCBridgableType())
2508 return ACTC_indirectRetainable;
2509 return ACTC_none;
2510 }
2511
2512 if (type->isObjCARCBridgableType())
2513 return ACTC_retainable;
2514
2515 return ACTC_none;
John McCallf85e1932011-06-15 23:02:42 +00002516}
2517
2518namespace {
John McCall2cf031d2011-10-01 01:01:08 +00002519 /// A result from the cast checker.
2520 enum ACCResult {
2521 /// Cannot be casted.
2522 ACC_invalid,
2523
2524 /// Can be safely retained or not retained.
2525 ACC_bottom,
2526
2527 /// Can be casted at +0.
2528 ACC_plusZero,
2529
2530 /// Can be casted at +1.
2531 ACC_plusOne
2532 };
2533 ACCResult merge(ACCResult left, ACCResult right) {
2534 if (left == right) return left;
2535 if (left == ACC_bottom) return right;
2536 if (right == ACC_bottom) return left;
2537 return ACC_invalid;
2538 }
2539
2540 /// A checker which white-lists certain expressions whose conversion
2541 /// to or from retainable type would otherwise be forbidden in ARC.
2542 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
2543 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
2544
John McCallf85e1932011-06-15 23:02:42 +00002545 ASTContext &Context;
John McCall2cf031d2011-10-01 01:01:08 +00002546 ARCConversionTypeClass SourceClass;
2547 ARCConversionTypeClass TargetClass;
2548
2549 static bool isCFType(QualType type) {
2550 // Someday this can use ns_bridged. For now, it has to do this.
2551 return type->isCARCBridgableType();
John McCallf85e1932011-06-15 23:02:42 +00002552 }
John McCall2cf031d2011-10-01 01:01:08 +00002553
2554 public:
2555 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
2556 ARCConversionTypeClass target)
2557 : Context(Context), SourceClass(source), TargetClass(target) {}
2558
2559 using super::Visit;
2560 ACCResult Visit(Expr *e) {
2561 return super::Visit(e->IgnoreParens());
2562 }
2563
2564 ACCResult VisitStmt(Stmt *s) {
2565 return ACC_invalid;
2566 }
2567
2568 /// Null pointer constants can be casted however you please.
2569 ACCResult VisitExpr(Expr *e) {
2570 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2571 return ACC_bottom;
2572 return ACC_invalid;
2573 }
2574
2575 /// Objective-C string literals can be safely casted.
2576 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
2577 // If we're casting to any retainable type, go ahead. Global
2578 // strings are immune to retains, so this is bottom.
2579 if (isAnyRetainable(TargetClass)) return ACC_bottom;
2580
2581 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002582 }
2583
John McCall2cf031d2011-10-01 01:01:08 +00002584 /// Look through certain implicit and explicit casts.
2585 ACCResult VisitCastExpr(CastExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002586 switch (e->getCastKind()) {
2587 case CK_NullToPointer:
John McCall2cf031d2011-10-01 01:01:08 +00002588 return ACC_bottom;
2589
John McCallf85e1932011-06-15 23:02:42 +00002590 case CK_NoOp:
2591 case CK_LValueToRValue:
2592 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00002593 case CK_CPointerToObjCPointerCast:
2594 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002595 case CK_AnyPointerToBlockPointerCast:
2596 return Visit(e->getSubExpr());
John McCall2cf031d2011-10-01 01:01:08 +00002597
John McCallf85e1932011-06-15 23:02:42 +00002598 default:
John McCall2cf031d2011-10-01 01:01:08 +00002599 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00002600 }
2601 }
John McCall2cf031d2011-10-01 01:01:08 +00002602
2603 /// Look through unary extension.
2604 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002605 return Visit(e->getSubExpr());
2606 }
John McCall2cf031d2011-10-01 01:01:08 +00002607
2608 /// Ignore the LHS of a comma operator.
2609 ACCResult VisitBinComma(BinaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00002610 return Visit(e->getRHS());
2611 }
John McCall2cf031d2011-10-01 01:01:08 +00002612
2613 /// Conditional operators are okay if both sides are okay.
2614 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
2615 ACCResult left = Visit(e->getTrueExpr());
2616 if (left == ACC_invalid) return ACC_invalid;
2617 return merge(left, Visit(e->getFalseExpr()));
John McCallf85e1932011-06-15 23:02:42 +00002618 }
John McCall2cf031d2011-10-01 01:01:08 +00002619
John McCall4b9c2d22011-11-06 09:01:30 +00002620 /// Look through pseudo-objects.
2621 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
2622 // If we're getting here, we should always have a result.
2623 return Visit(e->getResultExpr());
2624 }
2625
John McCall2cf031d2011-10-01 01:01:08 +00002626 /// Statement expressions are okay if their result expression is okay.
2627 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00002628 return Visit(e->getSubStmt()->body_back());
2629 }
John McCallf85e1932011-06-15 23:02:42 +00002630
John McCall2cf031d2011-10-01 01:01:08 +00002631 /// Some declaration references are okay.
2632 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
2633 // References to global constants from system headers are okay.
2634 // These are things like 'kCFStringTransformToLatin'. They are
2635 // can also be assumed to be immune to retains.
2636 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
2637 if (isAnyRetainable(TargetClass) &&
2638 isAnyRetainable(SourceClass) &&
2639 var &&
2640 var->getStorageClass() == SC_Extern &&
2641 var->getType().isConstQualified() &&
2642 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
2643 return ACC_bottom;
2644 }
2645
2646 // Nothing else.
2647 return ACC_invalid;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00002648 }
John McCall2cf031d2011-10-01 01:01:08 +00002649
2650 /// Some calls are okay.
2651 ACCResult VisitCallExpr(CallExpr *e) {
2652 if (FunctionDecl *fn = e->getDirectCallee())
2653 if (ACCResult result = checkCallToFunction(fn))
2654 return result;
2655
2656 return super::VisitCallExpr(e);
2657 }
2658
2659 ACCResult checkCallToFunction(FunctionDecl *fn) {
2660 // Require a CF*Ref return type.
2661 if (!isCFType(fn->getResultType()))
2662 return ACC_invalid;
2663
2664 if (!isAnyRetainable(TargetClass))
2665 return ACC_invalid;
2666
2667 // Honor an explicit 'not retained' attribute.
2668 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
2669 return ACC_plusZero;
2670
2671 // Honor an explicit 'retained' attribute, except that for
2672 // now we're not going to permit implicit handling of +1 results,
2673 // because it's a bit frightening.
2674 if (fn->hasAttr<CFReturnsRetainedAttr>())
2675 return ACC_invalid; // ACC_plusOne if we start accepting this
2676
2677 // Recognize this specific builtin function, which is used by CFSTR.
2678 unsigned builtinID = fn->getBuiltinID();
2679 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
2680 return ACC_bottom;
2681
2682 // Otherwise, don't do anything implicit with an unaudited function.
2683 if (!fn->hasAttr<CFAuditedTransferAttr>())
2684 return ACC_invalid;
2685
2686 // Otherwise, it's +0 unless it follows the create convention.
2687 if (ento::coreFoundation::followsCreateRule(fn))
2688 return ACC_invalid; // ACC_plusOne if we start accepting this
2689
2690 return ACC_plusZero;
2691 }
2692
2693 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
2694 return checkCallToMethod(e->getMethodDecl());
2695 }
2696
2697 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
2698 ObjCMethodDecl *method;
2699 if (e->isExplicitProperty())
2700 method = e->getExplicitProperty()->getGetterMethodDecl();
2701 else
2702 method = e->getImplicitPropertyGetter();
2703 return checkCallToMethod(method);
2704 }
2705
2706 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
2707 if (!method) return ACC_invalid;
2708
2709 // Check for message sends to functions returning CF types. We
2710 // just obey the Cocoa conventions with these, even though the
2711 // return type is CF.
2712 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
2713 return ACC_invalid;
2714
2715 // If the method is explicitly marked not-retained, it's +0.
2716 if (method->hasAttr<CFReturnsNotRetainedAttr>())
2717 return ACC_plusZero;
2718
2719 // If the method is explicitly marked as returning retained, or its
2720 // selector follows a +1 Cocoa convention, treat it as +1.
2721 if (method->hasAttr<CFReturnsRetainedAttr>())
2722 return ACC_plusOne;
2723
2724 switch (method->getSelector().getMethodFamily()) {
2725 case OMF_alloc:
2726 case OMF_copy:
2727 case OMF_mutableCopy:
2728 case OMF_new:
2729 return ACC_plusOne;
2730
2731 default:
2732 // Otherwise, treat it as +0.
2733 return ACC_plusZero;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00002734 }
2735 }
John McCall2cf031d2011-10-01 01:01:08 +00002736 };
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00002737}
2738
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002739static bool
2740KnownName(Sema &S, const char *name) {
2741 LookupResult R(S, &S.Context.Idents.get(name), SourceLocation(),
2742 Sema::LookupOrdinaryName);
2743 return S.LookupName(R, S.TUScope, false);
2744}
2745
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002746static void addFixitForObjCARCConversion(Sema &S,
2747 DiagnosticBuilder &DiagB,
2748 Sema::CheckedConversionKind CCK,
2749 SourceLocation afterLParen,
2750 QualType castType,
2751 Expr *castExpr,
2752 const char *bridgeKeyword,
2753 const char *CFBridgeName) {
2754 // We handle C-style and implicit casts here.
2755 switch (CCK) {
2756 case Sema::CCK_ImplicitConversion:
2757 case Sema::CCK_CStyleCast:
2758 break;
2759 case Sema::CCK_FunctionalCast:
2760 case Sema::CCK_OtherCast:
2761 return;
2762 }
2763
2764 if (CFBridgeName) {
2765 Expr *castedE = castExpr;
2766 if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE))
2767 castedE = CCE->getSubExpr();
2768 castedE = castedE->IgnoreImpCasts();
2769 SourceRange range = castedE->getSourceRange();
2770 if (isa<ParenExpr>(castedE)) {
2771 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2772 CFBridgeName));
2773 } else {
2774 std::string namePlusParen = CFBridgeName;
2775 namePlusParen += "(";
2776 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2777 namePlusParen));
2778 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2779 S.PP.getLocForEndOfToken(range.getEnd()),
2780 ")"));
2781 }
2782 return;
2783 }
2784
2785 if (CCK == Sema::CCK_CStyleCast) {
2786 DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword));
2787 } else {
2788 std::string castCode = "(";
2789 castCode += bridgeKeyword;
2790 castCode += castType.getAsString();
2791 castCode += ")";
2792 Expr *castedE = castExpr->IgnoreImpCasts();
2793 SourceRange range = castedE->getSourceRange();
2794 if (isa<ParenExpr>(castedE)) {
2795 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2796 castCode));
2797 } else {
2798 castCode += "(";
2799 DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(),
2800 castCode));
2801 DiagB.AddFixItHint(FixItHint::CreateInsertion(
2802 S.PP.getLocForEndOfToken(range.getEnd()),
2803 ")"));
2804 }
2805 }
2806}
2807
John McCall5acb0c92011-10-17 18:40:02 +00002808static void
2809diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
2810 QualType castType, ARCConversionTypeClass castACTC,
2811 Expr *castExpr, ARCConversionTypeClass exprACTC,
2812 Sema::CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00002813 SourceLocation loc =
John McCall2cf031d2011-10-01 01:01:08 +00002814 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00002815
John McCall5acb0c92011-10-17 18:40:02 +00002816 if (S.makeUnavailableInSystemHeader(loc,
John McCall2cf031d2011-10-01 01:01:08 +00002817 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCallf85e1932011-06-15 23:02:42 +00002818 return;
John McCall5acb0c92011-10-17 18:40:02 +00002819
2820 QualType castExprType = castExpr->getType();
John McCallf85e1932011-06-15 23:02:42 +00002821
John McCall71c482c2011-06-17 06:50:50 +00002822 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00002823 switch (exprACTC) {
John McCall2cf031d2011-10-01 01:01:08 +00002824 case ACTC_none:
2825 case ACTC_coreFoundation:
2826 case ACTC_voidPtr:
2827 srcKind = (castExprType->isPointerType() ? 1 : 0);
2828 break;
2829 case ACTC_retainable:
2830 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
2831 break;
2832 case ACTC_indirectRetainable:
2833 srcKind = 4;
2834 break;
John McCallf85e1932011-06-15 23:02:42 +00002835 }
2836
John McCall5acb0c92011-10-17 18:40:02 +00002837 // Check whether this could be fixed with a bridge cast.
2838 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
2839 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCallf85e1932011-06-15 23:02:42 +00002840
John McCall5acb0c92011-10-17 18:40:02 +00002841 // Bridge from an ARC type to a CF type.
2842 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002843
John McCall5acb0c92011-10-17 18:40:02 +00002844 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2845 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2846 << 2 // of C pointer type
2847 << castExprType
2848 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
2849 << castType
2850 << castRange
2851 << castExpr->getSourceRange();
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002852 bool br = KnownName(S, "CFBridgingRelease");
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002853 {
2854 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2855 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2856 castType, castExpr, "__bridge ", 0);
2857 }
2858 {
2859 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_transfer)
2860 << castExprType << br;
2861 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2862 castType, castExpr, "__bridge_transfer ",
2863 br ? "CFBridgingRelease" : 0);
2864 }
John McCall5acb0c92011-10-17 18:40:02 +00002865
2866 return;
2867 }
2868
2869 // Bridge from a CF type to an ARC type.
2870 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002871 bool br = KnownName(S, "CFBridgingRetain");
John McCall5acb0c92011-10-17 18:40:02 +00002872 S.Diag(loc, diag::err_arc_cast_requires_bridge)
2873 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
2874 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
2875 << castExprType
2876 << 2 // to C pointer type
2877 << castType
2878 << castRange
2879 << castExpr->getSourceRange();
2880
Argyrios Kyrtzidisae1b4af2012-02-16 17:31:07 +00002881 {
2882 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge);
2883 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2884 castType, castExpr, "__bridge ", 0);
2885 }
2886 {
2887 DiagnosticBuilder DiagB = S.Diag(noteLoc, diag::note_arc_bridge_retained)
2888 << castType << br;
2889 addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen,
2890 castType, castExpr, "__bridge_retained ",
2891 br ? "CFBridgingRetain" : 0);
2892 }
John McCall5acb0c92011-10-17 18:40:02 +00002893
2894 return;
John McCallf85e1932011-06-15 23:02:42 +00002895 }
2896
John McCall5acb0c92011-10-17 18:40:02 +00002897 S.Diag(loc, diag::err_arc_mismatched_cast)
2898 << (CCK != Sema::CCK_ImplicitConversion)
2899 << srcKind << castExprType << castType
John McCallf85e1932011-06-15 23:02:42 +00002900 << castRange << castExpr->getSourceRange();
2901}
2902
John McCall5acb0c92011-10-17 18:40:02 +00002903Sema::ARCConversionResult
2904Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
2905 Expr *&castExpr, CheckedConversionKind CCK) {
2906 QualType castExprType = castExpr->getType();
2907
2908 // For the purposes of the classification, we assume reference types
2909 // will bind to temporaries.
2910 QualType effCastType = castType;
2911 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
2912 effCastType = ref->getPointeeType();
2913
2914 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
2915 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002916 if (exprACTC == castACTC) {
2917 // check for viablity and report error if casting an rvalue to a
2918 // life-time qualifier.
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002919 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002920 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002921 (castType != castExprType)) {
2922 const Type *DT = castType.getTypePtr();
2923 QualType QDT = castType;
2924 // We desugar some types but not others. We ignore those
2925 // that cannot happen in a cast; i.e. auto, and those which
2926 // should not be de-sugared; i.e typedef.
2927 if (const ParenType *PT = dyn_cast<ParenType>(DT))
2928 QDT = PT->desugar();
2929 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
2930 QDT = TP->desugar();
2931 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
2932 QDT = AT->desugar();
2933 if (QDT != castType &&
2934 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
2935 SourceLocation loc =
2936 (castRange.isValid() ? castRange.getBegin()
2937 : castExpr->getExprLoc());
2938 Diag(loc, diag::err_arc_nolifetime_behavior);
2939 }
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002940 }
2941 return ACR_okay;
2942 }
2943
John McCall5acb0c92011-10-17 18:40:02 +00002944 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
2945
2946 // Allow all of these types to be cast to integer types (but not
2947 // vice-versa).
2948 if (castACTC == ACTC_none && castType->isIntegralType(Context))
2949 return ACR_okay;
2950
2951 // Allow casts between pointers to lifetime types (e.g., __strong id*)
2952 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
2953 // must be explicit.
2954 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
2955 return ACR_okay;
2956 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
2957 CCK != CCK_ImplicitConversion)
2958 return ACR_okay;
2959
2960 switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
2961 // For invalid casts, fall through.
2962 case ACC_invalid:
2963 break;
2964
2965 // Do nothing for both bottom and +0.
2966 case ACC_bottom:
2967 case ACC_plusZero:
2968 return ACR_okay;
2969
2970 // If the result is +1, consume it here.
2971 case ACC_plusOne:
2972 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
2973 CK_ARCConsumeObject, castExpr,
2974 0, VK_RValue);
2975 ExprNeedsCleanups = true;
2976 return ACR_okay;
2977 }
2978
2979 // If this is a non-implicit cast from id or block type to a
2980 // CoreFoundation type, delay complaining in case the cast is used
2981 // in an acceptable context.
2982 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
2983 CCK != CCK_ImplicitConversion)
2984 return ACR_unbridged;
2985
2986 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2987 castExpr, exprACTC, CCK);
2988 return ACR_okay;
2989}
2990
2991/// Given that we saw an expression with the ARCUnbridgedCastTy
2992/// placeholder type, complain bitterly.
2993void Sema::diagnoseARCUnbridgedCast(Expr *e) {
2994 // We expect the spurious ImplicitCastExpr to already have been stripped.
2995 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2996 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
2997
2998 SourceRange castRange;
2999 QualType castType;
3000 CheckedConversionKind CCK;
3001
3002 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
3003 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
3004 castType = cast->getTypeAsWritten();
3005 CCK = CCK_CStyleCast;
3006 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
3007 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
3008 castType = cast->getTypeAsWritten();
3009 CCK = CCK_OtherCast;
3010 } else {
3011 castType = cast->getType();
3012 CCK = CCK_ImplicitConversion;
3013 }
3014
3015 ARCConversionTypeClass castACTC =
3016 classifyTypeForARCConversion(castType.getNonReferenceType());
3017
3018 Expr *castExpr = realCast->getSubExpr();
3019 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
3020
3021 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
3022 castExpr, ACTC_retainable, CCK);
3023}
3024
3025/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
3026/// type, remove the placeholder cast.
3027Expr *Sema::stripARCUnbridgedCast(Expr *e) {
3028 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
3029
3030 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
3031 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
3032 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
3033 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
3034 assert(uo->getOpcode() == UO_Extension);
3035 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
3036 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
3037 sub->getValueKind(), sub->getObjectKind(),
3038 uo->getOperatorLoc());
3039 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
3040 assert(!gse->isResultDependent());
3041
3042 unsigned n = gse->getNumAssocs();
3043 SmallVector<Expr*, 4> subExprs(n);
3044 SmallVector<TypeSourceInfo*, 4> subTypes(n);
3045 for (unsigned i = 0; i != n; ++i) {
3046 subTypes[i] = gse->getAssocTypeSourceInfo(i);
3047 Expr *sub = gse->getAssocExpr(i);
3048 if (i == gse->getResultIndex())
3049 sub = stripARCUnbridgedCast(sub);
3050 subExprs[i] = sub;
3051 }
3052
3053 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
3054 gse->getControllingExpr(),
3055 subTypes.data(), subExprs.data(),
3056 n, gse->getDefaultLoc(),
3057 gse->getRParenLoc(),
3058 gse->containsUnexpandedParameterPack(),
3059 gse->getResultIndex());
3060 } else {
3061 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
3062 return cast<ImplicitCastExpr>(e)->getSubExpr();
3063 }
3064}
3065
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00003066bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
3067 QualType exprType) {
3068 QualType canCastType =
3069 Context.getCanonicalType(castType).getUnqualifiedType();
3070 QualType canExprType =
3071 Context.getCanonicalType(exprType).getUnqualifiedType();
3072 if (isa<ObjCObjectPointerType>(canCastType) &&
3073 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
3074 canExprType->isObjCObjectPointerType()) {
3075 if (const ObjCObjectPointerType *ObjT =
3076 canExprType->getAs<ObjCObjectPointerType>())
3077 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
3078 return false;
3079 }
3080 return true;
3081}
3082
John McCall7e5e5f42011-07-07 06:58:02 +00003083/// Look for an ObjCReclaimReturnedObject cast and destroy it.
3084static Expr *maybeUndoReclaimObject(Expr *e) {
3085 // For now, we just undo operands that are *immediately* reclaim
3086 // expressions, which prevents the vast majority of potential
3087 // problems here. To catch them all, we'd need to rebuild arbitrary
3088 // value-propagating subexpressions --- we can't reliably rebuild
3089 // in-place because of expression sharing.
3090 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00003091 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00003092 return ice->getSubExpr();
3093
3094 return e;
3095}
3096
John McCallf85e1932011-06-15 23:02:42 +00003097ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
3098 ObjCBridgeCastKind Kind,
3099 SourceLocation BridgeKeywordLoc,
3100 TypeSourceInfo *TSInfo,
3101 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00003102 ExprResult SubResult = UsualUnaryConversions(SubExpr);
3103 if (SubResult.isInvalid()) return ExprError();
3104 SubExpr = SubResult.take();
3105
John McCallf85e1932011-06-15 23:02:42 +00003106 QualType T = TSInfo->getType();
3107 QualType FromType = SubExpr->getType();
3108
John McCall1d9b3b22011-09-09 05:25:32 +00003109 CastKind CK;
3110
John McCallf85e1932011-06-15 23:02:42 +00003111 bool MustConsume = false;
3112 if (T->isDependentType() || SubExpr->isTypeDependent()) {
3113 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00003114 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00003115 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
3116 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00003117 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
3118 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00003119 switch (Kind) {
3120 case OBC_Bridge:
3121 break;
3122
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003123 case OBC_BridgeRetained: {
3124 bool br = KnownName(*this, "CFBridgingRelease");
John McCallf85e1932011-06-15 23:02:42 +00003125 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3126 << 2
3127 << FromType
3128 << (T->isBlockPointerType()? 1 : 0)
3129 << T
3130 << SubExpr->getSourceRange()
3131 << Kind;
3132 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3133 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
3134 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003135 << FromType << br
John McCallf85e1932011-06-15 23:02:42 +00003136 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003137 br ? "CFBridgingRelease "
3138 : "__bridge_transfer ");
John McCallf85e1932011-06-15 23:02:42 +00003139
3140 Kind = OBC_Bridge;
3141 break;
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003142 }
John McCallf85e1932011-06-15 23:02:42 +00003143
3144 case OBC_BridgeTransfer:
3145 // We must consume the Objective-C object produced by the cast.
3146 MustConsume = true;
3147 break;
3148 }
3149 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
3150 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00003151 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00003152 switch (Kind) {
3153 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00003154 // Reclaiming a value that's going to be __bridge-casted to CF
3155 // is very dangerous, so we don't do it.
3156 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00003157 break;
3158
3159 case OBC_BridgeRetained:
3160 // Produce the object before casting it.
3161 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00003162 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00003163 SubExpr, 0, VK_RValue);
3164 break;
3165
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003166 case OBC_BridgeTransfer: {
3167 bool br = KnownName(*this, "CFBridgingRetain");
John McCallf85e1932011-06-15 23:02:42 +00003168 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
3169 << (FromType->isBlockPointerType()? 1 : 0)
3170 << FromType
3171 << 2
3172 << T
3173 << SubExpr->getSourceRange()
3174 << Kind;
3175
3176 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
3177 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
3178 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003179 << T << br
3180 << FixItHint::CreateReplacement(BridgeKeywordLoc,
3181 br ? "CFBridgingRetain " : "__bridge_retained");
John McCallf85e1932011-06-15 23:02:42 +00003182
3183 Kind = OBC_Bridge;
3184 break;
3185 }
Fariborz Jahanian52b62362012-02-01 22:56:20 +00003186 }
John McCallf85e1932011-06-15 23:02:42 +00003187 } else {
3188 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
3189 << FromType << T << Kind
3190 << SubExpr->getSourceRange()
3191 << TSInfo->getTypeLoc().getSourceRange();
3192 return ExprError();
3193 }
3194
John McCall1d9b3b22011-09-09 05:25:32 +00003195 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00003196 BridgeKeywordLoc,
3197 TSInfo, SubExpr);
3198
3199 if (MustConsume) {
3200 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00003201 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00003202 0, VK_RValue);
3203 }
3204
3205 return Result;
3206}
3207
3208ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
3209 SourceLocation LParenLoc,
3210 ObjCBridgeCastKind Kind,
3211 SourceLocation BridgeKeywordLoc,
3212 ParsedType Type,
3213 SourceLocation RParenLoc,
3214 Expr *SubExpr) {
3215 TypeSourceInfo *TSInfo = 0;
3216 QualType T = GetTypeFromParser(Type, &TSInfo);
3217 if (!TSInfo)
3218 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
3219 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
3220 SubExpr);
3221}