blob: 497b2ec5f577df06cfa4d37f58383cede8c6024e [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"
Chris Lattner85a932e2008-01-04 22:32:30 +000020#include "clang/AST/ASTContext.h"
21#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000022#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000023#include "clang/AST/StmtVisitor.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000024#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000025#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000026#include "clang/Lex/Preprocessor.h"
27
Chris Lattner85a932e2008-01-04 22:32:30 +000028using namespace clang;
John McCall26743b22011-02-03 09:00:02 +000029using namespace sema;
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +000030using llvm::makeArrayRef;
Chris Lattner85a932e2008-01-04 22:32:30 +000031
John McCallf312b1e2010-08-26 23:41:50 +000032ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
33 Expr **strings,
34 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000035 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
36
Chris Lattnerf4b136f2009-02-18 06:13:04 +000037 // Most ObjC strings are formed out of a single piece. However, we *can*
38 // have strings formed out of multiple @ strings with multiple pptokens in
39 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
40 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner39c28bb2009-02-18 06:48:40 +000041 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattnerf4b136f2009-02-18 06:13:04 +000043 // If we have a multi-part string, merge it all together.
44 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000045 // Concatenate objc strings.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +000046 SmallString<128> StrBuf;
Chris Lattner5f9e2722011-07-23 10:55:15 +000047 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000048
Chris Lattner726e1682009-02-18 05:49:11 +000049 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000050 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000051
Douglas Gregor5cee1192011-07-27 05:40:30 +000052 // ObjC strings can't be wide or UTF.
53 if (!S->isAscii()) {
Chris Lattnerf4b136f2009-02-18 06:13:04 +000054 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
55 << S->getSourceRange();
56 return true;
57 }
Mike Stump1eb44332009-09-09 15:08:12 +000058
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +000059 // Append the string.
60 StrBuf += S->getString();
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattner39c28bb2009-02-18 06:48:40 +000062 // Get the locations of the string tokens.
63 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattner85a932e2008-01-04 22:32:30 +000064 }
Mike Stump1eb44332009-09-09 15:08:12 +000065
Chris Lattner39c28bb2009-02-18 06:48:40 +000066 // Create the aggregate string with the appropriate content and location
67 // information.
Jay Foad65aa6882011-06-21 15:13:30 +000068 S = StringLiteral::Create(Context, StrBuf,
Douglas Gregor5cee1192011-07-27 05:40:30 +000069 StringLiteral::Ascii, /*Pascal=*/false,
Chris Lattner2085fd62009-02-18 06:40:38 +000070 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000071 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000072 }
Mike Stump1eb44332009-09-09 15:08:12 +000073
Chris Lattner69039812009-02-18 06:01:06 +000074 // Verify that this composite string is acceptable for ObjC strings.
75 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000076 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000077
78 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000079 // the NSString interface is seen in this translation unit. Note: We
80 // don't use NSConstantString, since the runtime team considers this
81 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000082 QualType Ty = Context.getObjCConstantStringInterface();
83 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000084 Ty = Context.getObjCObjectPointerType(Ty);
Fariborz Jahanian8a437762010-04-23 23:19:04 +000085 } else if (getLangOptions().NoConstantCFStrings) {
Fariborz Jahanian4c733072010-10-19 17:19:29 +000086 IdentifierInfo *NSIdent=0;
87 std::string StringClass(getLangOptions().ObjCConstantStringClass);
88
89 if (StringClass.empty())
90 NSIdent = &Context.Idents.get("NSConstantString");
91 else
92 NSIdent = &Context.Idents.get(StringClass);
93
Fariborz Jahanian8a437762010-04-23 23:19:04 +000094 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
95 LookupOrdinaryName);
96 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
97 Context.setObjCConstantStringInterface(StrIF);
98 Ty = Context.getObjCConstantStringInterface();
99 Ty = Context.getObjCObjectPointerType(Ty);
100 } else {
101 // If there is no NSConstantString interface defined then treat this
102 // as error and recover from it.
103 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
104 << S->getSourceRange();
105 Ty = Context.getObjCIdType();
106 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000107 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000108 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +0000109 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
110 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000111 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
112 Context.setObjCConstantStringInterface(StrIF);
113 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000114 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000115 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000116 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000117 // strings as untyped objects and let the runtime figure it out later.
118 Ty = Context.getObjCIdType();
119 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000120 }
Mike Stump1eb44332009-09-09 15:08:12 +0000121
Chris Lattnerf4b136f2009-02-18 06:13:04 +0000122 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +0000123}
124
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000125ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000126 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000127 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000128 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000129 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000130 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000131 StrTy = Context.DependentTy;
132 else {
Fariborz Jahanian6c916152011-06-16 22:34:44 +0000133 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
134 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000135 if (RequireCompleteType(AtLoc, EncodedType,
136 PDiag(diag::err_incomplete_type_objc_at_encode)
137 << EncodedTypeInfo->getTypeLoc().getSourceRange()))
138 return ExprError();
139
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000140 std::string Str;
141 Context.getObjCEncodingForType(EncodedType, Str);
142
143 // The type of @encode is the same as the type of the corresponding string,
144 // which is an array type.
145 StrTy = Context.CharTy;
146 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000147 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000148 StrTy.addConst();
149 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
150 ArrayType::Normal, 0);
151 }
Mike Stump1eb44332009-09-09 15:08:12 +0000152
Douglas Gregor81d34662010-04-20 15:39:42 +0000153 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000154}
155
John McCallf312b1e2010-08-26 23:41:50 +0000156ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
157 SourceLocation EncodeLoc,
158 SourceLocation LParenLoc,
159 ParsedType ty,
160 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000161 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000162 TypeSourceInfo *TInfo;
163 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
164 if (!TInfo)
165 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
166 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000167
Douglas Gregor81d34662010-04-20 15:39:42 +0000168 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000169}
170
John McCallf312b1e2010-08-26 23:41:50 +0000171ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
172 SourceLocation AtLoc,
173 SourceLocation SelLoc,
174 SourceLocation LParenLoc,
175 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000176 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000177 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000178 if (!Method)
179 Method = LookupFactoryMethodInGlobalPool(Sel,
180 SourceRange(LParenLoc, RParenLoc));
181 if (!Method)
182 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian4c91d892011-07-13 19:05:43 +0000183
184 if (!Method ||
185 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
186 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
187 = ReferencedSelectors.find(Sel);
188 if (Pos == ReferencedSelectors.end())
189 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
190 }
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000191
John McCallf85e1932011-06-15 23:02:42 +0000192 // In ARC, forbid the user from using @selector for
193 // retain/release/autorelease/dealloc/retainCount.
194 if (getLangOptions().ObjCAutoRefCount) {
195 switch (Sel.getMethodFamily()) {
196 case OMF_retain:
197 case OMF_release:
198 case OMF_autorelease:
199 case OMF_retainCount:
200 case OMF_dealloc:
201 Diag(AtLoc, diag::err_arc_illegal_selector) <<
202 Sel << SourceRange(LParenLoc, RParenLoc);
203 break;
204
205 case OMF_None:
206 case OMF_alloc:
207 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +0000208 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +0000209 case OMF_init:
210 case OMF_mutableCopy:
211 case OMF_new:
212 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +0000213 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +0000214 break;
215 }
216 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000217 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000218 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000219}
220
John McCallf312b1e2010-08-26 23:41:50 +0000221ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
222 SourceLocation AtLoc,
223 SourceLocation ProtoLoc,
224 SourceLocation LParenLoc,
225 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000226 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000227 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000228 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000229 return true;
230 }
Mike Stump1eb44332009-09-09 15:08:12 +0000231
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000232 QualType Ty = Context.getObjCProtoType();
233 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000234 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000235 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000236 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000237}
238
John McCall26743b22011-02-03 09:00:02 +0000239/// Try to capture an implicit reference to 'self'.
Eli Friedmanb942cb22012-02-03 22:47:37 +0000240ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) {
241 DeclContext *DC = getFunctionLevelDeclContext();
John McCall26743b22011-02-03 09:00:02 +0000242
243 // If we're not in an ObjC method, error out. Note that, unlike the
244 // C++ case, we don't require an instance method --- class methods
245 // still have a 'self', and we really do still need to capture it!
246 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
247 if (!method)
248 return 0;
249
Eli Friedmanb942cb22012-02-03 22:47:37 +0000250 TryCaptureVar(method->getSelfDecl(), Loc);
John McCall26743b22011-02-03 09:00:02 +0000251
252 return method;
253}
254
Douglas Gregor5c16d632011-09-09 20:05:21 +0000255static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
256 if (T == Context.getObjCInstanceType())
257 return Context.getObjCIdType();
258
259 return T;
260}
261
Douglas Gregor926df6c2011-06-11 01:09:30 +0000262QualType Sema::getMessageSendResultType(QualType ReceiverType,
263 ObjCMethodDecl *Method,
264 bool isClassMessage, bool isSuperMessage) {
265 assert(Method && "Must have a method");
266 if (!Method->hasRelatedResultType())
267 return Method->getSendResultType();
268
269 // If a method has a related return type:
270 // - if the method found is an instance method, but the message send
271 // was a class message send, T is the declared return type of the method
272 // found
273 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor5c16d632011-09-09 20:05:21 +0000274 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000275
276 // - if the receiver is super, T is a pointer to the class of the
277 // enclosing method definition
278 if (isSuperMessage) {
279 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
280 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
281 return Context.getObjCObjectPointerType(
282 Context.getObjCInterfaceType(Class));
283 }
284
285 // - if the receiver is the name of a class U, T is a pointer to U
286 if (ReceiverType->getAs<ObjCInterfaceType>() ||
287 ReceiverType->isObjCQualifiedInterfaceType())
288 return Context.getObjCObjectPointerType(ReceiverType);
289 // - if the receiver is of type Class or qualified Class type,
290 // T is the declared return type of the method.
291 if (ReceiverType->isObjCClassType() ||
292 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor5c16d632011-09-09 20:05:21 +0000293 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000294
295 // - if the receiver is id, qualified id, Class, or qualified Class, T
296 // is the receiver type, otherwise
297 // - T is the type of the receiver expression.
298 return ReceiverType;
299}
John McCall26743b22011-02-03 09:00:02 +0000300
Douglas Gregor926df6c2011-06-11 01:09:30 +0000301void Sema::EmitRelatedResultTypeNote(const Expr *E) {
302 E = E->IgnoreParenImpCasts();
303 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
304 if (!MsgSend)
305 return;
306
307 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
308 if (!Method)
309 return;
310
311 if (!Method->hasRelatedResultType())
312 return;
313
314 if (Context.hasSameUnqualifiedType(Method->getResultType()
315 .getNonReferenceType(),
316 MsgSend->getType()))
317 return;
318
Douglas Gregore97179c2011-09-08 01:46:34 +0000319 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
320 Context.getObjCInstanceType()))
321 return;
322
Douglas Gregor926df6c2011-06-11 01:09:30 +0000323 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
324 << Method->isInstanceMethod() << Method->getSelector()
325 << MsgSend->getType();
326}
327
328bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
329 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000330 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000331 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000332 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000333 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000334 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000335 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000336 for (unsigned i = 0; i != NumArgs; i++) {
337 if (Args[i]->isTypeDependent())
338 continue;
339
John Wiegley429bb272011-04-08 18:41:53 +0000340 ExprResult Result = DefaultArgumentPromotion(Args[i]);
341 if (Result.isInvalid())
342 return true;
343 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000344 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000345
John McCallf85e1932011-06-15 23:02:42 +0000346 unsigned DiagID;
347 if (getLangOptions().ObjCAutoRefCount)
348 DiagID = diag::err_arc_method_not_found;
349 else
350 DiagID = isClassMessage ? diag::warn_class_method_not_found
351 : diag::warn_inst_method_not_found;
John McCall819e7452011-08-31 20:57:36 +0000352 if (!getLangOptions().DebuggerSupport)
353 Diag(lbrac, DiagID)
354 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +0000355
356 // In debuggers, we want to use __unknown_anytype for these
357 // results so that clients can cast them.
358 if (getLangOptions().DebuggerSupport) {
359 ReturnType = Context.UnknownAnyTy;
360 } else {
361 ReturnType = Context.getObjCIdType();
362 }
John McCallf89e55a2010-11-18 06:31:45 +0000363 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000364 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000365 }
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Douglas Gregor926df6c2011-06-11 01:09:30 +0000367 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
368 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000369 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000371 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000372 // Method might have more arguments than selector indicates. This is due
373 // to addition of c-style arguments in method.
374 if (Method->param_size() > Sel.getNumArgs())
375 NumNamedArgs = Method->param_size();
376 // FIXME. This need be cleaned up.
377 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000378 Diag(lbrac, diag::err_typecheck_call_too_few_args)
379 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000380 return false;
381 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000382
Chris Lattner312531a2009-04-12 08:11:20 +0000383 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000384 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000385 // We can't do any type-checking on a type-dependent argument.
386 if (Args[i]->isTypeDependent())
387 continue;
388
Chris Lattner85a932e2008-01-04 22:32:30 +0000389 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000390
John McCall5acb0c92011-10-17 18:40:02 +0000391 ParmVarDecl *param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000392 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000393
John McCall5acb0c92011-10-17 18:40:02 +0000394 // Strip the unbridged-cast placeholder expression off unless it's
395 // a consumed argument.
396 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
397 !param->hasAttr<CFConsumedAttr>())
398 argExpr = stripARCUnbridgedCast(argExpr);
399
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000400 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall5acb0c92011-10-17 18:40:02 +0000401 param->getType(),
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000402 PDiag(diag::err_call_incomplete_argument)
403 << argExpr->getSourceRange()))
404 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000405
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000406 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall5acb0c92011-10-17 18:40:02 +0000407 param);
John McCall3fa5cae2010-10-26 07:05:15 +0000408 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000409 if (ArgE.isInvalid())
410 IsError = true;
411 else
412 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000413 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000414
415 // Promote additional arguments to variadic methods.
416 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000417 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
418 if (Args[i]->isTypeDependent())
419 continue;
420
John Wiegley429bb272011-04-08 18:41:53 +0000421 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
422 IsError |= Arg.isInvalid();
423 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000424 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000425 } else {
426 // Check for extra arguments to non-variadic methods.
427 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000428 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000429 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000430 << 2 /*method*/ << NumNamedArgs << NumArgs
431 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000432 << SourceRange(Args[NumNamedArgs]->getLocStart(),
433 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000434 }
435 }
436
Douglas Gregor2725ca82010-04-21 19:57:20 +0000437 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000438
439 // Do additional checkings on method.
440 IsError |= CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
441
Chris Lattner312531a2009-04-12 08:11:20 +0000442 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000443}
444
Douglas Gregorc737acb2011-09-27 16:10:05 +0000445bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000446 // 'self' is objc 'self' in an objc method only.
John McCall4b9c2d22011-11-06 09:01:30 +0000447 ObjCMethodDecl *method =
448 dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
449 if (!method) return false;
450
John McCallf85e1932011-06-15 23:02:42 +0000451 receiver = receiver->IgnoreParenLValueCasts();
452 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCall4b9c2d22011-11-06 09:01:30 +0000453 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregorc737acb2011-09-27 16:10:05 +0000454 return true;
455 return false;
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000456}
457
Steve Narofff1afaf62009-02-26 15:55:06 +0000458// Helper method for ActOnClassMethod/ActOnInstanceMethod.
459// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000460// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000461// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000462ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000463 ObjCInterfaceDecl *ClassDecl) {
464 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000465 // lookup in class and all superclasses
466 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000467 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000468 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Steve Naroff5609ec02009-03-08 18:56:13 +0000470 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000471 if (!Method)
472 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Steve Naroff5609ec02009-03-08 18:56:13 +0000474 // Before we give up, check if the selector is an instance method.
475 // But only in the root. This matches gcc's behaviour and what the
476 // runtime expects.
477 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000478 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000479 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000480 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000481 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000482 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Steve Naroff5609ec02009-03-08 18:56:13 +0000485 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000486 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000487 return Method;
488}
489
490ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
491 ObjCInterfaceDecl *ClassDecl) {
Douglas Gregor2e5c15b2011-12-15 05:27:12 +0000492 if (!ClassDecl->hasDefinition())
493 return 0;
494
Steve Naroff5609ec02009-03-08 18:56:13 +0000495 ObjCMethodDecl *Method = 0;
496 while (ClassDecl && !Method) {
497 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000498 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000499 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Steve Naroff5609ec02009-03-08 18:56:13 +0000501 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000502 if (!Method)
503 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000504 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000505 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000506 return Method;
507}
508
John McCall3c3b7f92011-10-25 17:37:35 +0000509/// LookupMethodInType - Look up a method in an ObjCObjectType.
510ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
511 bool isInstance) {
512 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
513 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
514 // Look it up in the main interface (and categories, etc.)
515 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
516 return method;
517
518 // Okay, look for "private" methods declared in any
519 // @implementations we've seen.
520 if (isInstance) {
521 if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
522 return method;
523 } else {
524 if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
525 return method;
526 }
527 }
528
529 // Check qualifiers.
530 for (ObjCObjectType::qual_iterator
531 i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
532 if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
533 return method;
534
535 return 0;
536}
537
Fariborz Jahanian61478062011-03-09 20:18:06 +0000538/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
539/// list of a qualified objective pointer type.
540ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
541 const ObjCObjectPointerType *OPT,
542 bool Instance)
543{
544 ObjCMethodDecl *MD = 0;
545 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
546 E = OPT->qual_end(); I != E; ++I) {
547 ObjCProtocolDecl *PROTO = (*I);
548 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
549 return MD;
550 }
551 }
552 return 0;
553}
554
Chris Lattner7f816522010-04-11 07:45:24 +0000555/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
556/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000557ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000558HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000559 Expr *BaseExpr, SourceLocation OpLoc,
560 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000561 SourceLocation MemberLoc,
562 SourceLocation SuperLoc, QualType SuperType,
563 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000564 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
565 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000566
567 if (MemberName.getNameKind() != DeclarationName::Identifier) {
568 Diag(MemberLoc, diag::err_invalid_property_name)
569 << MemberName << QualType(OPT, 0);
570 return ExprError();
571 }
572
Chris Lattner7f816522010-04-11 07:45:24 +0000573 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregorb3029962011-11-14 22:10:01 +0000574 SourceRange BaseRange = Super? SourceRange(SuperLoc)
575 : BaseExpr->getSourceRange();
576 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
577 PDiag(diag::err_property_not_found_forward_class)
578 << MemberName << BaseRange))
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000579 return ExprError();
Douglas Gregorb3029962011-11-14 22:10:01 +0000580
Chris Lattner7f816522010-04-11 07:45:24 +0000581 // Search for a declared property first.
582 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
583 // Check whether we can reference this property.
584 if (DiagnoseUseOfDecl(PD, MemberLoc))
585 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000586
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000587 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +0000588 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000589 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000590 MemberLoc,
591 SuperLoc, SuperType));
592 else
John McCall3c3b7f92011-10-25 17:37:35 +0000593 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000594 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000595 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000596 }
597 // Check protocols on qualified interfaces.
598 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
599 E = OPT->qual_end(); I != E; ++I)
600 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
601 // Check whether we can reference this property.
602 if (DiagnoseUseOfDecl(PD, MemberLoc))
603 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000604
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000605 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +0000606 return Owned(new (Context) ObjCPropertyRefExpr(PD,
607 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000608 VK_LValue,
609 OK_ObjCProperty,
610 MemberLoc,
611 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000612 else
John McCall3c3b7f92011-10-25 17:37:35 +0000613 return Owned(new (Context) ObjCPropertyRefExpr(PD,
614 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000615 VK_LValue,
616 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000617 MemberLoc,
618 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000619 }
620 // If that failed, look for an "implicit" property by seeing if the nullary
621 // selector is implemented.
622
623 // FIXME: The logic for looking up nullary and unary selectors should be
624 // shared with the code in ActOnInstanceMessage.
625
626 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
627 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000628
629 // May be founf in property's qualified list.
630 if (!Getter)
631 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000632
633 // If this reference is in an @implementation, check for 'private' methods.
634 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000635 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000636
637 // Look through local category implementations associated with the class.
638 if (!Getter)
639 Getter = IFace->getCategoryInstanceMethod(Sel);
640 if (Getter) {
641 // Check if we can reference this property.
642 if (DiagnoseUseOfDecl(Getter, MemberLoc))
643 return ExprError();
644 }
645 // If we found a getter then this may be a valid dot-reference, we
646 // will look for the matching setter, in case it is needed.
647 Selector SetterSel =
648 SelectorTable::constructSetterName(PP.getIdentifierTable(),
649 PP.getSelectorTable(), Member);
650 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000651
652 // May be founf in property's qualified list.
653 if (!Setter)
654 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
655
Chris Lattner7f816522010-04-11 07:45:24 +0000656 if (!Setter) {
657 // If this reference is in an @implementation, also check for 'private'
658 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000659 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000660 }
661 // Look through local category implementations associated with the class.
662 if (!Setter)
663 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000664
Chris Lattner7f816522010-04-11 07:45:24 +0000665 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
666 return ExprError();
667
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000668 if (Getter || Setter) {
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000669 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000670 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +0000671 Context.PseudoObjectTy,
672 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +0000673 MemberLoc,
674 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000675 else
John McCall12f78a62010-12-02 01:19:52 +0000676 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +0000677 Context.PseudoObjectTy,
678 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +0000679 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000680
Chris Lattner7f816522010-04-11 07:45:24 +0000681 }
682
683 // Attempt to correct for typos in property names.
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000684 DeclFilterCCC<ObjCPropertyDecl> Validator;
685 if (TypoCorrection Corrected = CorrectTypo(
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000686 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000687 NULL, Validator, IFace, false, OPT)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000688 ObjCPropertyDecl *Property =
689 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000690 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +0000691 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000692 << MemberName << QualType(OPT, 0) << TypoResult
693 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000694 Diag(Property->getLocation(), diag::note_previous_decl)
695 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000696 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
697 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000698 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000699 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000700 ObjCInterfaceDecl *ClassDeclared;
701 if (ObjCIvarDecl *Ivar =
702 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
703 QualType T = Ivar->getType();
704 if (const ObjCObjectPointerType * OBJPT =
705 T->getAsObjCInterfacePointerType()) {
Douglas Gregorb3029962011-11-14 22:10:01 +0000706 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
707 PDiag(diag::err_property_not_as_forward_class)
708 << MemberName << BaseExpr->getSourceRange()))
709 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000710 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000711 Diag(MemberLoc,
712 diag::err_ivar_access_using_property_syntax_suggest)
713 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
714 << FixItHint::CreateReplacement(OpLoc, "->");
715 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000716 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000717
Chris Lattner7f816522010-04-11 07:45:24 +0000718 Diag(MemberLoc, diag::err_property_not_found)
719 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000720 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000721 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000722 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000723 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000724}
725
726
727
John McCall60d7b3a2010-08-24 06:29:42 +0000728ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000729ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
730 IdentifierInfo &propertyName,
731 SourceLocation receiverNameLoc,
732 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000734 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000735 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
736 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000737
738 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000739 if (IFace == 0) {
740 // If the "receiver" is 'super' in a method, handle it as an expression-like
741 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000742 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000743 IsSuper = true;
744
Eli Friedmanb942cb22012-02-03 22:47:37 +0000745 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000746 if (CurMethod->isInstanceMethod()) {
747 QualType T =
748 Context.getObjCInterfaceType(CurMethod->getClassInterface());
749 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000750
751 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000752 /*BaseExpr*/0,
753 SourceLocation()/*OpLoc*/,
754 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000755 propertyNameLoc,
756 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000757 }
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Chris Lattnereb483eb2010-04-11 08:28:14 +0000759 // Otherwise, if this is a class method, try dispatching to our
760 // superclass.
761 IFace = CurMethod->getClassInterface()->getSuperClass();
762 }
John McCall26743b22011-02-03 09:00:02 +0000763 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000764
765 if (IFace == 0) {
766 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
767 return ExprError();
768 }
769 }
770
771 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000772 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000773 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000774
775 // If this reference is in an @implementation, check for 'private' methods.
776 if (!Getter)
777 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
778 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000779 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000780 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000781
782 if (Getter) {
783 // FIXME: refactor/share with ActOnMemberReference().
784 // Check if we can reference this property.
785 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
786 return ExprError();
787 }
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Steve Naroff61f72cb2009-03-09 21:12:44 +0000789 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000790 Selector SetterSel =
791 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000792 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000794 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000795 if (!Setter) {
796 // If this reference is in an @implementation, also check for 'private'
797 // methods.
798 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
799 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000800 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000801 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000802 }
803 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000804 if (!Setter)
805 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000806
807 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
808 return ExprError();
809
810 if (Getter || Setter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000811 if (IsSuper)
812 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +0000813 Context.PseudoObjectTy,
814 VK_LValue, OK_ObjCProperty,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000815 propertyNameLoc,
816 receiverNameLoc,
817 Context.getObjCInterfaceType(IFace)));
818
John McCall12f78a62010-12-02 01:19:52 +0000819 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +0000820 Context.PseudoObjectTy,
821 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +0000822 propertyNameLoc,
823 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000824 }
825 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
826 << &propertyName << Context.getObjCInterfaceType(IFace));
827}
828
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000829namespace {
830
831class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
832 public:
833 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
834 // Determine whether "super" is acceptable in the current context.
835 if (Method && Method->getClassInterface())
836 WantObjCSuper = Method->getClassInterface()->getSuperClass();
837 }
838
839 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
840 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
841 candidate.isKeyword("super");
842 }
843};
844
845}
846
Douglas Gregor47bd5432010-04-14 02:46:37 +0000847Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000848 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000849 SourceLocation NameLoc,
850 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000851 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000852 ParsedType &ReceiverType) {
853 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000854
Douglas Gregor47bd5432010-04-14 02:46:37 +0000855 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000856 // messaging super. If the identifier is "super" and there is a
857 // trailing dot, it's an instance message.
858 if (IsSuper && S->isInObjcMethodScope())
859 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000860
861 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
862 LookupName(Result, S);
863
864 switch (Result.getResultKind()) {
865 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000866 // Normal name lookup didn't find anything. If we're in an
867 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000868 // FIXME: This is a hack. Ivar lookup should be part of normal
869 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000870 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidisccc9e762011-11-09 00:22:48 +0000871 if (!Method->getClassInterface()) {
872 // Fall back: let the parser try to parse it as an instance message.
873 return ObjCInstanceMessage;
874 }
875
Douglas Gregored464422010-04-19 20:09:36 +0000876 ObjCInterfaceDecl *ClassDeclared;
877 if (Method->getClassInterface()->lookupInstanceVariable(Name,
878 ClassDeclared))
879 return ObjCInstanceMessage;
880 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000881
Douglas Gregor47bd5432010-04-14 02:46:37 +0000882 // Break out; we'll perform typo correction below.
883 break;
884
885 case LookupResult::NotFoundInCurrentInstantiation:
886 case LookupResult::FoundOverloaded:
887 case LookupResult::FoundUnresolvedValue:
888 case LookupResult::Ambiguous:
889 Result.suppressDiagnostics();
890 return ObjCInstanceMessage;
891
892 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000893 // If the identifier is a class or not, and there is a trailing dot,
894 // it's an instance message.
895 if (HasTrailingDot)
896 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000897 // We found something. If it's a type, then we have a class
898 // message. Otherwise, it's an instance message.
899 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000900 QualType T;
901 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
902 T = Context.getObjCInterfaceType(Class);
903 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
904 T = Context.getTypeDeclType(Type);
905 else
906 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000907
Douglas Gregor1569f952010-04-21 20:38:13 +0000908 // We have a class message, and T is the type we're
909 // messaging. Build source-location information for it.
910 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000911 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000912 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000913 }
914 }
915
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000916 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000917 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
918 Result.getLookupKind(), S, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000919 Validator)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000920 if (Corrected.isKeyword()) {
921 // If we've found the keyword "super" (the only keyword that would be
922 // returned by CorrectTypo), this is a send to super.
Douglas Gregoraaf87162010-04-14 20:04:41 +0000923 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000924 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000925 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000926 return ObjCSuperMessage;
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000927 } else if (ObjCInterfaceDecl *Class =
928 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
929 // If we found a declaration, correct when it refers to an Objective-C
930 // class.
931 Diag(NameLoc, diag::err_unknown_receiver_suggest)
932 << Name << Corrected.getCorrection()
933 << FixItHint::CreateReplacement(SourceRange(NameLoc),
934 Class->getNameAsString());
935 Diag(Class->getLocation(), diag::note_previous_decl)
936 << Corrected.getCorrection();
937
938 QualType T = Context.getObjCInterfaceType(Class);
939 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
940 ReceiverType = CreateParsedType(T, TSInfo);
941 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000942 }
943 }
944
945 // Fall back: let the parser try to parse it as an instance message.
946 return ObjCInstanceMessage;
947}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000948
John McCall60d7b3a2010-08-24 06:29:42 +0000949ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000950 SourceLocation SuperLoc,
951 Selector Sel,
952 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +0000953 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000954 SourceLocation RBracLoc,
955 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000956 // Determine whether we are inside a method or not.
Eli Friedmanb942cb22012-02-03 22:47:37 +0000957 ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc);
Douglas Gregorf95861a2010-04-21 20:01:04 +0000958 if (!Method) {
959 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
960 return ExprError();
961 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000962
Douglas Gregorf95861a2010-04-21 20:01:04 +0000963 ObjCInterfaceDecl *Class = Method->getClassInterface();
964 if (!Class) {
965 Diag(SuperLoc, diag::error_no_super_class_message)
966 << Method->getDeclName();
967 return ExprError();
968 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000969
Douglas Gregorf95861a2010-04-21 20:01:04 +0000970 ObjCInterfaceDecl *Super = Class->getSuperClass();
971 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000972 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000973 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
974 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000975 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000976 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000977
Douglas Gregorf95861a2010-04-21 20:01:04 +0000978 // We are in a method whose class has a superclass, so 'super'
979 // is acting as a keyword.
980 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +0000981 if (Sel.getMethodFamily() == OMF_dealloc)
982 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +0000983 if (Sel.getMethodFamily() == OMF_finalize)
984 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +0000985
Douglas Gregorf95861a2010-04-21 20:01:04 +0000986 // Since we are in an instance method, this is an instance
987 // message to the superclass instance.
988 QualType SuperTy = Context.getObjCInterfaceType(Super);
989 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +0000990 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000991 Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +0000992 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000993 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000994
995 // Since we are in a class method, this is a class message to
996 // the superclass.
997 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
998 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000999 SuperLoc, Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001000 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001001}
1002
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001003
1004ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1005 bool isSuperReceiver,
1006 SourceLocation Loc,
1007 Selector Sel,
1008 ObjCMethodDecl *Method,
1009 MultiExprArg Args) {
1010 TypeSourceInfo *receiverTypeInfo = 0;
1011 if (!ReceiverType.isNull())
1012 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1013
1014 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1015 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1016 Sel, Method, Loc, Loc, Loc, Args,
1017 /*isImplicit=*/true);
1018
1019}
1020
Douglas Gregor2725ca82010-04-21 19:57:20 +00001021/// \brief Build an Objective-C class message expression.
1022///
1023/// This routine takes care of both normal class messages and
1024/// class messages to the superclass.
1025///
1026/// \param ReceiverTypeInfo Type source information that describes the
1027/// receiver of this message. This may be NULL, in which case we are
1028/// sending to the superclass and \p SuperLoc must be a valid source
1029/// location.
1030
1031/// \param ReceiverType The type of the object receiving the
1032/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1033/// type as that refers to. For a superclass send, this is the type of
1034/// the superclass.
1035///
1036/// \param SuperLoc The location of the "super" keyword in a
1037/// superclass message.
1038///
1039/// \param Sel The selector to which the message is being sent.
1040///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001041/// \param Method The method that this class message is invoking, if
1042/// already known.
1043///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001044/// \param LBracLoc The location of the opening square bracket ']'.
1045///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001046/// \param RBrac The location of the closing square bracket ']'.
1047///
1048/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001049ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001050 QualType ReceiverType,
1051 SourceLocation SuperLoc,
1052 Selector Sel,
1053 ObjCMethodDecl *Method,
1054 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001055 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001056 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001057 MultiExprArg ArgsIn,
1058 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001059 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001060 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001061 if (LBracLoc.isInvalid()) {
1062 Diag(Loc, diag::err_missing_open_square_message_send)
1063 << FixItHint::CreateInsertion(Loc, "[");
1064 LBracLoc = Loc;
1065 }
1066
Douglas Gregor92e986e2010-04-22 16:44:27 +00001067 if (ReceiverType->isDependentType()) {
1068 // If the receiver type is dependent, we can't type-check anything
1069 // at this point. Build a dependent expression.
1070 unsigned NumArgs = ArgsIn.size();
1071 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1072 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001073 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1074 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001075 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001076 makeArrayRef(Args, NumArgs),RBracLoc,
1077 isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001078 }
Chris Lattner15faee12010-04-12 05:38:43 +00001079
Douglas Gregor2725ca82010-04-21 19:57:20 +00001080 // Find the class to which we are sending this message.
1081 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001082 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1083 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001084 Diag(Loc, diag::err_invalid_receiver_class_message)
1085 << ReceiverType;
1086 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001087 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001088 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001089 // objc++ diagnoses during typename annotation.
1090 if (!getLangOptions().CPlusPlus)
1091 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001092 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001093 if (!Method) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001094 SourceRange TypeRange
1095 = SuperLoc.isValid()? SourceRange(SuperLoc)
1096 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
1097 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
1098 (getLangOptions().ObjCAutoRefCount
1099 ? PDiag(diag::err_arc_receiver_forward_class)
1100 : PDiag(diag::warn_receiver_forward_class))
1101 << TypeRange)) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001102 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001103 Method = LookupFactoryMethodInGlobalPool(Sel,
1104 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001105 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001106 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1107 << Method->getDeclName();
1108 }
1109 if (!Method)
1110 Method = Class->lookupClassMethod(Sel);
1111
1112 // If we have an implementation in scope, check "private" methods.
1113 if (!Method)
1114 Method = LookupPrivateClassMethod(Sel, Class);
1115
1116 if (Method && DiagnoseUseOfDecl(Method, Loc))
1117 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001118 }
Mike Stump1eb44332009-09-09 15:08:12 +00001119
Douglas Gregor2725ca82010-04-21 19:57:20 +00001120 // Check the argument types and determine the result type.
1121 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001122 ExprValueKind VK = VK_RValue;
1123
Douglas Gregor2725ca82010-04-21 19:57:20 +00001124 unsigned NumArgs = ArgsIn.size();
1125 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001126 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1127 SuperLoc.isValid(), LBracLoc, RBracLoc,
1128 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001129 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001130
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001131 if (Method && !Method->getResultType()->isVoidType() &&
1132 RequireCompleteType(LBracLoc, Method->getResultType(),
1133 diag::err_illegal_message_expr_incomplete_type))
1134 return ExprError();
1135
Douglas Gregor2725ca82010-04-21 19:57:20 +00001136 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001137 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001138 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001139 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001140 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001141 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001142 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001143 RBracLoc, isImplicit);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001144 else
John McCallf89e55a2010-11-18 06:31:45 +00001145 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001146 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001147 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001148 RBracLoc, isImplicit);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001149 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001150}
1151
Douglas Gregor2725ca82010-04-21 19:57:20 +00001152// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001153// ArgExprs is optional - if it is present, the number of expressions
1154// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001155ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001156 ParsedType Receiver,
1157 Selector Sel,
1158 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001159 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor77328d12010-09-15 23:19:31 +00001160 SourceLocation RBracLoc,
1161 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001162 TypeSourceInfo *ReceiverTypeInfo;
1163 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1164 if (ReceiverType.isNull())
1165 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001166
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Douglas Gregor2725ca82010-04-21 19:57:20 +00001168 if (!ReceiverTypeInfo)
1169 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1170
1171 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001172 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001173 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001174}
1175
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001176ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
1177 QualType ReceiverType,
1178 SourceLocation Loc,
1179 Selector Sel,
1180 ObjCMethodDecl *Method,
1181 MultiExprArg Args) {
1182 return BuildInstanceMessage(Receiver, ReceiverType,
1183 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
1184 Sel, Method, Loc, Loc, Loc, Args,
1185 /*isImplicit=*/true);
1186}
1187
Douglas Gregor2725ca82010-04-21 19:57:20 +00001188/// \brief Build an Objective-C instance message expression.
1189///
1190/// This routine takes care of both normal instance messages and
1191/// instance messages to the superclass instance.
1192///
1193/// \param Receiver The expression that computes the object that will
1194/// receive this message. This may be empty, in which case we are
1195/// sending to the superclass instance and \p SuperLoc must be a valid
1196/// source location.
1197///
1198/// \param ReceiverType The (static) type of the object receiving the
1199/// message. When a \p Receiver expression is provided, this is the
1200/// same type as that expression. For a superclass instance send, this
1201/// is a pointer to the type of the superclass.
1202///
1203/// \param SuperLoc The location of the "super" keyword in a
1204/// superclass instance message.
1205///
1206/// \param Sel The selector to which the message is being sent.
1207///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001208/// \param Method The method that this instance message is invoking, if
1209/// already known.
1210///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001211/// \param LBracLoc The location of the opening square bracket ']'.
1212///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001213/// \param RBrac The location of the closing square bracket ']'.
1214///
1215/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001216ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001217 QualType ReceiverType,
1218 SourceLocation SuperLoc,
1219 Selector Sel,
1220 ObjCMethodDecl *Method,
1221 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001222 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001223 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001224 MultiExprArg ArgsIn,
1225 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001226 // The location of the receiver.
1227 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1228
1229 if (LBracLoc.isInvalid()) {
1230 Diag(Loc, diag::err_missing_open_square_message_send)
1231 << FixItHint::CreateInsertion(Loc, "[");
1232 LBracLoc = Loc;
1233 }
1234
Douglas Gregor2725ca82010-04-21 19:57:20 +00001235 // If we have a receiver expression, perform appropriate promotions
1236 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001237 if (Receiver) {
John McCall5acb0c92011-10-17 18:40:02 +00001238 if (Receiver->hasPlaceholderType()) {
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00001239 ExprResult Result;
1240 if (Receiver->getType() == Context.UnknownAnyTy)
1241 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
1242 else
1243 Result = CheckPlaceholderExpr(Receiver);
1244 if (Result.isInvalid()) return ExprError();
1245 Receiver = Result.take();
John McCall5acb0c92011-10-17 18:40:02 +00001246 }
1247
Douglas Gregor92e986e2010-04-22 16:44:27 +00001248 if (Receiver->isTypeDependent()) {
1249 // If the receiver is type-dependent, we can't type-check anything
1250 // at this point. Build a dependent expression.
1251 unsigned NumArgs = ArgsIn.size();
1252 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1253 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1254 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001255 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001256 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001257 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001258 RBracLoc, isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001259 }
1260
Douglas Gregor2725ca82010-04-21 19:57:20 +00001261 // If necessary, apply function/array conversion to the receiver.
1262 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001263 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1264 if (Result.isInvalid())
1265 return ExprError();
1266 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001267 ReceiverType = Receiver->getType();
1268 }
1269
Douglas Gregorf49bb082010-04-22 17:01:48 +00001270 if (!Method) {
1271 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001272 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001273 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001274 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1275 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001276 SourceRange(LBracLoc, RBracLoc),
1277 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001278 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001279 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001280 SourceRange(LBracLoc, RBracLoc),
1281 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001282 } else if (ReceiverType->isObjCClassType() ||
1283 ReceiverType->isObjCQualifiedClassType()) {
1284 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001285 // We allow sending a message to a qualified Class ("Class<foo>"), which
1286 // is ok as long as one of the protocols implements the selector (if not, warn).
1287 if (const ObjCObjectPointerType *QClassTy
1288 = ReceiverType->getAsObjCQualifiedClassType()) {
1289 // Search protocols for class methods.
1290 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1291 if (!Method) {
1292 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1293 // warn if instance method found for a Class message.
1294 if (Method) {
1295 Diag(Loc, diag::warn_instance_method_on_class_found)
1296 << Method->getSelector() << Sel;
1297 Diag(Method->getLocation(), diag::note_method_declared_at);
1298 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001299 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001300 } else {
1301 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1302 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1303 // First check the public methods in the class interface.
1304 Method = ClassDecl->lookupClassMethod(Sel);
1305
1306 if (!Method)
1307 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1308 }
1309 if (Method && DiagnoseUseOfDecl(Method, Loc))
1310 return ExprError();
1311 }
1312 if (!Method) {
1313 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00001314 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001315 Method = LookupFactoryMethodInGlobalPool(Sel,
1316 SourceRange(LBracLoc, RBracLoc),
1317 true);
1318 if (!Method) {
1319 // If no class (factory) method was found, check if an _instance_
1320 // method of the same name exists in the root class only.
1321 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001322 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001323 true);
1324 if (Method)
1325 if (const ObjCInterfaceDecl *ID =
1326 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1327 if (ID->getSuperClass())
1328 Diag(Loc, diag::warn_root_inst_method_not_found)
1329 << Sel << SourceRange(LBracLoc, RBracLoc);
1330 }
1331 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001332 }
1333 }
1334 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001335 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001336 ObjCInterfaceDecl* ClassDecl = 0;
1337
1338 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1339 // long as one of the protocols implements the selector (if not, warn).
1340 if (const ObjCObjectPointerType *QIdTy
1341 = ReceiverType->getAsObjCQualifiedIdType()) {
1342 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001343 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1344 if (!Method)
1345 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001346 } else if (const ObjCObjectPointerType *OCIType
1347 = ReceiverType->getAsObjCInterfacePointerType()) {
1348 // We allow sending a message to a pointer to an interface (an object).
1349 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001350
Douglas Gregorb3029962011-11-14 22:10:01 +00001351 // Try to complete the type. Under ARC, this is a hard error from which
1352 // we don't try to recover.
1353 const ObjCInterfaceDecl *forwardClass = 0;
1354 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
1355 getLangOptions().ObjCAutoRefCount
1356 ? PDiag(diag::err_arc_receiver_forward_instance)
1357 << (Receiver ? Receiver->getSourceRange()
1358 : SourceRange(SuperLoc))
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00001359 : PDiag(diag::warn_receiver_forward_instance)
1360 << (Receiver ? Receiver->getSourceRange()
1361 : SourceRange(SuperLoc)))) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001362 if (getLangOptions().ObjCAutoRefCount)
1363 return ExprError();
1364
1365 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00001366 Diag(Receiver ? Receiver->getLocStart()
1367 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00001368 Method = 0;
1369 } else {
1370 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCallf85e1932011-06-15 23:02:42 +00001371 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001372
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001373 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001374 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001375 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1376
Douglas Gregorf49bb082010-04-22 17:01:48 +00001377 if (!Method) {
1378 // If we have implementations in scope, check "private" methods.
1379 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1380
John McCallf85e1932011-06-15 23:02:42 +00001381 if (!Method && getLangOptions().ObjCAutoRefCount) {
1382 Diag(Loc, diag::err_arc_may_not_respond)
1383 << OCIType->getPointeeType() << Sel;
1384 return ExprError();
1385 }
1386
Douglas Gregorc737acb2011-09-27 16:10:05 +00001387 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001388 // If we still haven't found a method, look in the global pool. This
1389 // behavior isn't very desirable, however we need it for GCC
1390 // compatibility. FIXME: should we deviate??
1391 if (OCIType->qual_empty()) {
1392 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001393 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001394 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001395 Diag(Loc, diag::warn_maynot_respond)
1396 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1397 }
1398 }
1399 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001400 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001401 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001402 } else if (!getLangOptions().ObjCAutoRefCount &&
1403 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001404 (ReceiverType->isPointerType() ||
1405 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001406 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001407 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001408 Diag(Loc, diag::warn_bad_receiver_type)
1409 << ReceiverType
1410 << Receiver->getSourceRange();
1411 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001412 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00001413 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00001414 else {
1415 // TODO: specialized warning on null receivers?
1416 bool IsNull = Receiver->isNullPointerConstant(Context,
1417 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001418 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1419 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001420 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001421 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00001422 } else {
John Wiegley429bb272011-04-08 18:41:53 +00001423 ExprResult ReceiverRes;
1424 if (getLangOptions().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00001425 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00001426 if (ReceiverRes.isUsable()) {
1427 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00001428 return BuildInstanceMessage(Receiver,
1429 ReceiverType,
1430 SuperLoc,
1431 Sel,
1432 Method,
1433 LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001434 SelectorLocs,
John Wiegley429bb272011-04-08 18:41:53 +00001435 RBracLoc,
1436 move(ArgsIn));
1437 } else {
1438 // Reject other random receiver types (e.g. structs).
1439 Diag(Loc, diag::err_bad_receiver_type)
1440 << ReceiverType << Receiver->getSourceRange();
1441 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001442 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001443 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001444 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001445 }
Mike Stump1eb44332009-09-09 15:08:12 +00001446
Douglas Gregor2725ca82010-04-21 19:57:20 +00001447 // Check the message arguments.
1448 unsigned NumArgs = ArgsIn.size();
1449 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1450 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001451 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001452 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1453 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001454 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1455 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001456 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001457 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001458
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001459 if (Method && !Method->getResultType()->isVoidType() &&
1460 RequireCompleteType(LBracLoc, Method->getResultType(),
1461 diag::err_illegal_message_expr_incomplete_type))
1462 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001463
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001464 SourceLocation SelLoc = SelectorLocs.front();
1465
John McCallf85e1932011-06-15 23:02:42 +00001466 // In ARC, forbid the user from sending messages to
1467 // retain/release/autorelease/dealloc/retainCount explicitly.
1468 if (getLangOptions().ObjCAutoRefCount) {
1469 ObjCMethodFamily family =
1470 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1471 switch (family) {
1472 case OMF_init:
1473 if (Method)
1474 checkInitMethod(Method, ReceiverType);
1475
1476 case OMF_None:
1477 case OMF_alloc:
1478 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00001479 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00001480 case OMF_mutableCopy:
1481 case OMF_new:
1482 case OMF_self:
1483 break;
1484
1485 case OMF_dealloc:
1486 case OMF_retain:
1487 case OMF_release:
1488 case OMF_autorelease:
1489 case OMF_retainCount:
1490 Diag(Loc, diag::err_arc_illegal_explicit_message)
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001491 << Sel << SelLoc;
John McCallf85e1932011-06-15 23:02:42 +00001492 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001493
1494 case OMF_performSelector:
1495 if (Method && NumArgs >= 1) {
1496 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1497 Selector ArgSel = SelExp->getSelector();
1498 ObjCMethodDecl *SelMethod =
1499 LookupInstanceMethodInGlobalPool(ArgSel,
1500 SelExp->getSourceRange());
1501 if (!SelMethod)
1502 SelMethod =
1503 LookupFactoryMethodInGlobalPool(ArgSel,
1504 SelExp->getSourceRange());
1505 if (SelMethod) {
1506 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1507 switch (SelFamily) {
1508 case OMF_alloc:
1509 case OMF_copy:
1510 case OMF_mutableCopy:
1511 case OMF_new:
1512 case OMF_self:
1513 case OMF_init:
1514 // Issue error, unless ns_returns_not_retained.
1515 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1516 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001517 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001518 diag::err_arc_perform_selector_retains);
1519 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1520 }
1521 break;
1522 default:
1523 // +0 call. OK. unless ns_returns_retained.
1524 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1525 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001526 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001527 diag::err_arc_perform_selector_retains);
1528 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1529 }
1530 break;
1531 }
1532 }
1533 } else {
1534 // error (may leak).
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001535 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001536 Diag(Args[0]->getExprLoc(), diag::note_used_here);
1537 }
1538 }
1539 break;
John McCallf85e1932011-06-15 23:02:42 +00001540 }
1541 }
1542
Douglas Gregor2725ca82010-04-21 19:57:20 +00001543 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001544 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001545 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001546 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001547 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001548 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001549 makeArrayRef(Args, NumArgs), RBracLoc,
1550 isImplicit);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001551 else
John McCallf89e55a2010-11-18 06:31:45 +00001552 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001553 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001554 makeArrayRef(Args, NumArgs), RBracLoc,
1555 isImplicit);
John McCallf85e1932011-06-15 23:02:42 +00001556
1557 if (getLangOptions().ObjCAutoRefCount) {
1558 // In ARC, annotate delegate init calls.
1559 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00001560 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00001561 // Only consider init calls *directly* in init implementations,
1562 // not within blocks.
1563 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1564 if (method && method->getMethodFamily() == OMF_init) {
1565 // The implicit assignment to self means we also don't want to
1566 // consume the result.
1567 Result->setDelegateInitCall(true);
1568 return Owned(Result);
1569 }
1570 }
1571
1572 // In ARC, check for message sends which are likely to introduce
1573 // retain cycles.
1574 checkRetainCycles(Result);
1575 }
1576
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001577 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001578}
1579
1580// ActOnInstanceMessage - used for both unary and keyword messages.
1581// ArgExprs is optional - if it is present, the number of expressions
1582// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001583ExprResult Sema::ActOnInstanceMessage(Scope *S,
1584 Expr *Receiver,
1585 Selector Sel,
1586 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001587 ArrayRef<SourceLocation> SelectorLocs,
John McCall60d7b3a2010-08-24 06:29:42 +00001588 SourceLocation RBracLoc,
1589 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001590 if (!Receiver)
1591 return ExprError();
1592
John McCall9ae2f072010-08-23 23:25:46 +00001593 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001594 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001595 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001596}
Chris Lattnereca7be62008-04-07 05:30:13 +00001597
John McCallf85e1932011-06-15 23:02:42 +00001598enum ARCConversionTypeClass {
John McCall2cf031d2011-10-01 01:01:08 +00001599 /// int, void, struct A
John McCallf85e1932011-06-15 23:02:42 +00001600 ACTC_none,
John McCall2cf031d2011-10-01 01:01:08 +00001601
1602 /// id, void (^)()
John McCallf85e1932011-06-15 23:02:42 +00001603 ACTC_retainable,
John McCall2cf031d2011-10-01 01:01:08 +00001604
1605 /// id*, id***, void (^*)(),
1606 ACTC_indirectRetainable,
1607
1608 /// void* might be a normal C type, or it might a CF type.
1609 ACTC_voidPtr,
1610
1611 /// struct A*
1612 ACTC_coreFoundation
John McCallf85e1932011-06-15 23:02:42 +00001613};
John McCall2cf031d2011-10-01 01:01:08 +00001614static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
1615 return (ACTC == ACTC_retainable ||
1616 ACTC == ACTC_coreFoundation ||
1617 ACTC == ACTC_voidPtr);
1618}
1619static bool isAnyCLike(ARCConversionTypeClass ACTC) {
1620 return ACTC == ACTC_none ||
1621 ACTC == ACTC_voidPtr ||
1622 ACTC == ACTC_coreFoundation;
1623}
1624
John McCallf85e1932011-06-15 23:02:42 +00001625static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCall2cf031d2011-10-01 01:01:08 +00001626 bool isIndirect = false;
John McCallf85e1932011-06-15 23:02:42 +00001627
1628 // Ignore an outermost reference type.
John McCall2cf031d2011-10-01 01:01:08 +00001629 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCallf85e1932011-06-15 23:02:42 +00001630 type = ref->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00001631 isIndirect = true;
1632 }
John McCallf85e1932011-06-15 23:02:42 +00001633
1634 // Drill through pointers and arrays recursively.
1635 while (true) {
1636 if (const PointerType *ptr = type->getAs<PointerType>()) {
1637 type = ptr->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00001638
1639 // The first level of pointer may be the innermost pointer on a CF type.
1640 if (!isIndirect) {
1641 if (type->isVoidType()) return ACTC_voidPtr;
1642 if (type->isRecordType()) return ACTC_coreFoundation;
1643 }
John McCallf85e1932011-06-15 23:02:42 +00001644 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1645 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1646 } else {
1647 break;
1648 }
John McCall2cf031d2011-10-01 01:01:08 +00001649 isIndirect = true;
John McCallf85e1932011-06-15 23:02:42 +00001650 }
1651
John McCall2cf031d2011-10-01 01:01:08 +00001652 if (isIndirect) {
1653 if (type->isObjCARCBridgableType())
1654 return ACTC_indirectRetainable;
1655 return ACTC_none;
1656 }
1657
1658 if (type->isObjCARCBridgableType())
1659 return ACTC_retainable;
1660
1661 return ACTC_none;
John McCallf85e1932011-06-15 23:02:42 +00001662}
1663
1664namespace {
John McCall2cf031d2011-10-01 01:01:08 +00001665 /// A result from the cast checker.
1666 enum ACCResult {
1667 /// Cannot be casted.
1668 ACC_invalid,
1669
1670 /// Can be safely retained or not retained.
1671 ACC_bottom,
1672
1673 /// Can be casted at +0.
1674 ACC_plusZero,
1675
1676 /// Can be casted at +1.
1677 ACC_plusOne
1678 };
1679 ACCResult merge(ACCResult left, ACCResult right) {
1680 if (left == right) return left;
1681 if (left == ACC_bottom) return right;
1682 if (right == ACC_bottom) return left;
1683 return ACC_invalid;
1684 }
1685
1686 /// A checker which white-lists certain expressions whose conversion
1687 /// to or from retainable type would otherwise be forbidden in ARC.
1688 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
1689 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
1690
John McCallf85e1932011-06-15 23:02:42 +00001691 ASTContext &Context;
John McCall2cf031d2011-10-01 01:01:08 +00001692 ARCConversionTypeClass SourceClass;
1693 ARCConversionTypeClass TargetClass;
1694
1695 static bool isCFType(QualType type) {
1696 // Someday this can use ns_bridged. For now, it has to do this.
1697 return type->isCARCBridgableType();
John McCallf85e1932011-06-15 23:02:42 +00001698 }
John McCall2cf031d2011-10-01 01:01:08 +00001699
1700 public:
1701 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
1702 ARCConversionTypeClass target)
1703 : Context(Context), SourceClass(source), TargetClass(target) {}
1704
1705 using super::Visit;
1706 ACCResult Visit(Expr *e) {
1707 return super::Visit(e->IgnoreParens());
1708 }
1709
1710 ACCResult VisitStmt(Stmt *s) {
1711 return ACC_invalid;
1712 }
1713
1714 /// Null pointer constants can be casted however you please.
1715 ACCResult VisitExpr(Expr *e) {
1716 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1717 return ACC_bottom;
1718 return ACC_invalid;
1719 }
1720
1721 /// Objective-C string literals can be safely casted.
1722 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
1723 // If we're casting to any retainable type, go ahead. Global
1724 // strings are immune to retains, so this is bottom.
1725 if (isAnyRetainable(TargetClass)) return ACC_bottom;
1726
1727 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00001728 }
1729
John McCall2cf031d2011-10-01 01:01:08 +00001730 /// Look through certain implicit and explicit casts.
1731 ACCResult VisitCastExpr(CastExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00001732 switch (e->getCastKind()) {
1733 case CK_NullToPointer:
John McCall2cf031d2011-10-01 01:01:08 +00001734 return ACC_bottom;
1735
John McCallf85e1932011-06-15 23:02:42 +00001736 case CK_NoOp:
1737 case CK_LValueToRValue:
1738 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00001739 case CK_CPointerToObjCPointerCast:
1740 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00001741 case CK_AnyPointerToBlockPointerCast:
1742 return Visit(e->getSubExpr());
John McCall2cf031d2011-10-01 01:01:08 +00001743
John McCallf85e1932011-06-15 23:02:42 +00001744 default:
John McCall2cf031d2011-10-01 01:01:08 +00001745 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00001746 }
1747 }
John McCall2cf031d2011-10-01 01:01:08 +00001748
1749 /// Look through unary extension.
1750 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00001751 return Visit(e->getSubExpr());
1752 }
John McCall2cf031d2011-10-01 01:01:08 +00001753
1754 /// Ignore the LHS of a comma operator.
1755 ACCResult VisitBinComma(BinaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00001756 return Visit(e->getRHS());
1757 }
John McCall2cf031d2011-10-01 01:01:08 +00001758
1759 /// Conditional operators are okay if both sides are okay.
1760 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
1761 ACCResult left = Visit(e->getTrueExpr());
1762 if (left == ACC_invalid) return ACC_invalid;
1763 return merge(left, Visit(e->getFalseExpr()));
John McCallf85e1932011-06-15 23:02:42 +00001764 }
John McCall2cf031d2011-10-01 01:01:08 +00001765
John McCall4b9c2d22011-11-06 09:01:30 +00001766 /// Look through pseudo-objects.
1767 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
1768 // If we're getting here, we should always have a result.
1769 return Visit(e->getResultExpr());
1770 }
1771
John McCall2cf031d2011-10-01 01:01:08 +00001772 /// Statement expressions are okay if their result expression is okay.
1773 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00001774 return Visit(e->getSubStmt()->body_back());
1775 }
John McCallf85e1932011-06-15 23:02:42 +00001776
John McCall2cf031d2011-10-01 01:01:08 +00001777 /// Some declaration references are okay.
1778 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
1779 // References to global constants from system headers are okay.
1780 // These are things like 'kCFStringTransformToLatin'. They are
1781 // can also be assumed to be immune to retains.
1782 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
1783 if (isAnyRetainable(TargetClass) &&
1784 isAnyRetainable(SourceClass) &&
1785 var &&
1786 var->getStorageClass() == SC_Extern &&
1787 var->getType().isConstQualified() &&
1788 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
1789 return ACC_bottom;
1790 }
1791
1792 // Nothing else.
1793 return ACC_invalid;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001794 }
John McCall2cf031d2011-10-01 01:01:08 +00001795
1796 /// Some calls are okay.
1797 ACCResult VisitCallExpr(CallExpr *e) {
1798 if (FunctionDecl *fn = e->getDirectCallee())
1799 if (ACCResult result = checkCallToFunction(fn))
1800 return result;
1801
1802 return super::VisitCallExpr(e);
1803 }
1804
1805 ACCResult checkCallToFunction(FunctionDecl *fn) {
1806 // Require a CF*Ref return type.
1807 if (!isCFType(fn->getResultType()))
1808 return ACC_invalid;
1809
1810 if (!isAnyRetainable(TargetClass))
1811 return ACC_invalid;
1812
1813 // Honor an explicit 'not retained' attribute.
1814 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
1815 return ACC_plusZero;
1816
1817 // Honor an explicit 'retained' attribute, except that for
1818 // now we're not going to permit implicit handling of +1 results,
1819 // because it's a bit frightening.
1820 if (fn->hasAttr<CFReturnsRetainedAttr>())
1821 return ACC_invalid; // ACC_plusOne if we start accepting this
1822
1823 // Recognize this specific builtin function, which is used by CFSTR.
1824 unsigned builtinID = fn->getBuiltinID();
1825 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
1826 return ACC_bottom;
1827
1828 // Otherwise, don't do anything implicit with an unaudited function.
1829 if (!fn->hasAttr<CFAuditedTransferAttr>())
1830 return ACC_invalid;
1831
1832 // Otherwise, it's +0 unless it follows the create convention.
1833 if (ento::coreFoundation::followsCreateRule(fn))
1834 return ACC_invalid; // ACC_plusOne if we start accepting this
1835
1836 return ACC_plusZero;
1837 }
1838
1839 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
1840 return checkCallToMethod(e->getMethodDecl());
1841 }
1842
1843 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
1844 ObjCMethodDecl *method;
1845 if (e->isExplicitProperty())
1846 method = e->getExplicitProperty()->getGetterMethodDecl();
1847 else
1848 method = e->getImplicitPropertyGetter();
1849 return checkCallToMethod(method);
1850 }
1851
1852 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
1853 if (!method) return ACC_invalid;
1854
1855 // Check for message sends to functions returning CF types. We
1856 // just obey the Cocoa conventions with these, even though the
1857 // return type is CF.
1858 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
1859 return ACC_invalid;
1860
1861 // If the method is explicitly marked not-retained, it's +0.
1862 if (method->hasAttr<CFReturnsNotRetainedAttr>())
1863 return ACC_plusZero;
1864
1865 // If the method is explicitly marked as returning retained, or its
1866 // selector follows a +1 Cocoa convention, treat it as +1.
1867 if (method->hasAttr<CFReturnsRetainedAttr>())
1868 return ACC_plusOne;
1869
1870 switch (method->getSelector().getMethodFamily()) {
1871 case OMF_alloc:
1872 case OMF_copy:
1873 case OMF_mutableCopy:
1874 case OMF_new:
1875 return ACC_plusOne;
1876
1877 default:
1878 // Otherwise, treat it as +0.
1879 return ACC_plusZero;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001880 }
1881 }
John McCall2cf031d2011-10-01 01:01:08 +00001882 };
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001883}
1884
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001885static bool
1886KnownName(Sema &S, const char *name) {
1887 LookupResult R(S, &S.Context.Idents.get(name), SourceLocation(),
1888 Sema::LookupOrdinaryName);
1889 return S.LookupName(R, S.TUScope, false);
1890}
1891
John McCall5acb0c92011-10-17 18:40:02 +00001892static void
1893diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
1894 QualType castType, ARCConversionTypeClass castACTC,
1895 Expr *castExpr, ARCConversionTypeClass exprACTC,
1896 Sema::CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00001897 SourceLocation loc =
John McCall2cf031d2011-10-01 01:01:08 +00001898 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00001899
John McCall5acb0c92011-10-17 18:40:02 +00001900 if (S.makeUnavailableInSystemHeader(loc,
John McCall2cf031d2011-10-01 01:01:08 +00001901 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCallf85e1932011-06-15 23:02:42 +00001902 return;
John McCall5acb0c92011-10-17 18:40:02 +00001903
1904 QualType castExprType = castExpr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001905
John McCall71c482c2011-06-17 06:50:50 +00001906 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00001907 switch (exprACTC) {
John McCall2cf031d2011-10-01 01:01:08 +00001908 case ACTC_none:
1909 case ACTC_coreFoundation:
1910 case ACTC_voidPtr:
1911 srcKind = (castExprType->isPointerType() ? 1 : 0);
1912 break;
1913 case ACTC_retainable:
1914 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1915 break;
1916 case ACTC_indirectRetainable:
1917 srcKind = 4;
1918 break;
John McCallf85e1932011-06-15 23:02:42 +00001919 }
1920
John McCall5acb0c92011-10-17 18:40:02 +00001921 // Check whether this could be fixed with a bridge cast.
1922 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
1923 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCallf85e1932011-06-15 23:02:42 +00001924
John McCall5acb0c92011-10-17 18:40:02 +00001925 // Bridge from an ARC type to a CF type.
1926 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001927
John McCall5acb0c92011-10-17 18:40:02 +00001928 S.Diag(loc, diag::err_arc_cast_requires_bridge)
1929 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
1930 << 2 // of C pointer type
1931 << castExprType
1932 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
1933 << castType
1934 << castRange
1935 << castExpr->getSourceRange();
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001936 bool br = KnownName(S, "CFBridgingRelease");
John McCall5acb0c92011-10-17 18:40:02 +00001937 S.Diag(noteLoc, diag::note_arc_bridge)
1938 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1939 FixItHint::CreateInsertion(afterLParen, "__bridge "));
1940 S.Diag(noteLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001941 << castExprType << br
John McCall5acb0c92011-10-17 18:40:02 +00001942 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001943 FixItHint::CreateInsertion(afterLParen,
1944 br ? "CFBridgingRelease " : "__bridge_transfer "));
John McCall5acb0c92011-10-17 18:40:02 +00001945
1946 return;
1947 }
1948
1949 // Bridge from a CF type to an ARC type.
1950 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001951 bool br = KnownName(S, "CFBridgingRetain");
John McCall5acb0c92011-10-17 18:40:02 +00001952 S.Diag(loc, diag::err_arc_cast_requires_bridge)
1953 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
1954 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
1955 << castExprType
1956 << 2 // to C pointer type
1957 << castType
1958 << castRange
1959 << castExpr->getSourceRange();
1960
1961 S.Diag(noteLoc, diag::note_arc_bridge)
1962 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1963 FixItHint::CreateInsertion(afterLParen, "__bridge "));
1964 S.Diag(noteLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001965 << castType << br
John McCall5acb0c92011-10-17 18:40:02 +00001966 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001967 FixItHint::CreateInsertion(afterLParen,
1968 br ? "CFBridgingRetain " : "__bridge_retained"));
John McCall5acb0c92011-10-17 18:40:02 +00001969
1970 return;
John McCallf85e1932011-06-15 23:02:42 +00001971 }
1972
John McCall5acb0c92011-10-17 18:40:02 +00001973 S.Diag(loc, diag::err_arc_mismatched_cast)
1974 << (CCK != Sema::CCK_ImplicitConversion)
1975 << srcKind << castExprType << castType
John McCallf85e1932011-06-15 23:02:42 +00001976 << castRange << castExpr->getSourceRange();
1977}
1978
John McCall5acb0c92011-10-17 18:40:02 +00001979Sema::ARCConversionResult
1980Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
1981 Expr *&castExpr, CheckedConversionKind CCK) {
1982 QualType castExprType = castExpr->getType();
1983
1984 // For the purposes of the classification, we assume reference types
1985 // will bind to temporaries.
1986 QualType effCastType = castType;
1987 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
1988 effCastType = ref->getPointeeType();
1989
1990 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1991 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00001992 if (exprACTC == castACTC) {
1993 // check for viablity and report error if casting an rvalue to a
1994 // life-time qualifier.
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00001995 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00001996 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00001997 (castType != castExprType)) {
1998 const Type *DT = castType.getTypePtr();
1999 QualType QDT = castType;
2000 // We desugar some types but not others. We ignore those
2001 // that cannot happen in a cast; i.e. auto, and those which
2002 // should not be de-sugared; i.e typedef.
2003 if (const ParenType *PT = dyn_cast<ParenType>(DT))
2004 QDT = PT->desugar();
2005 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
2006 QDT = TP->desugar();
2007 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
2008 QDT = AT->desugar();
2009 if (QDT != castType &&
2010 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
2011 SourceLocation loc =
2012 (castRange.isValid() ? castRange.getBegin()
2013 : castExpr->getExprLoc());
2014 Diag(loc, diag::err_arc_nolifetime_behavior);
2015 }
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002016 }
2017 return ACR_okay;
2018 }
2019
John McCall5acb0c92011-10-17 18:40:02 +00002020 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
2021
2022 // Allow all of these types to be cast to integer types (but not
2023 // vice-versa).
2024 if (castACTC == ACTC_none && castType->isIntegralType(Context))
2025 return ACR_okay;
2026
2027 // Allow casts between pointers to lifetime types (e.g., __strong id*)
2028 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
2029 // must be explicit.
2030 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
2031 return ACR_okay;
2032 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
2033 CCK != CCK_ImplicitConversion)
2034 return ACR_okay;
2035
2036 switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
2037 // For invalid casts, fall through.
2038 case ACC_invalid:
2039 break;
2040
2041 // Do nothing for both bottom and +0.
2042 case ACC_bottom:
2043 case ACC_plusZero:
2044 return ACR_okay;
2045
2046 // If the result is +1, consume it here.
2047 case ACC_plusOne:
2048 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
2049 CK_ARCConsumeObject, castExpr,
2050 0, VK_RValue);
2051 ExprNeedsCleanups = true;
2052 return ACR_okay;
2053 }
2054
2055 // If this is a non-implicit cast from id or block type to a
2056 // CoreFoundation type, delay complaining in case the cast is used
2057 // in an acceptable context.
2058 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
2059 CCK != CCK_ImplicitConversion)
2060 return ACR_unbridged;
2061
2062 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2063 castExpr, exprACTC, CCK);
2064 return ACR_okay;
2065}
2066
2067/// Given that we saw an expression with the ARCUnbridgedCastTy
2068/// placeholder type, complain bitterly.
2069void Sema::diagnoseARCUnbridgedCast(Expr *e) {
2070 // We expect the spurious ImplicitCastExpr to already have been stripped.
2071 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2072 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
2073
2074 SourceRange castRange;
2075 QualType castType;
2076 CheckedConversionKind CCK;
2077
2078 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
2079 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
2080 castType = cast->getTypeAsWritten();
2081 CCK = CCK_CStyleCast;
2082 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
2083 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
2084 castType = cast->getTypeAsWritten();
2085 CCK = CCK_OtherCast;
2086 } else {
2087 castType = cast->getType();
2088 CCK = CCK_ImplicitConversion;
2089 }
2090
2091 ARCConversionTypeClass castACTC =
2092 classifyTypeForARCConversion(castType.getNonReferenceType());
2093
2094 Expr *castExpr = realCast->getSubExpr();
2095 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
2096
2097 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2098 castExpr, ACTC_retainable, CCK);
2099}
2100
2101/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
2102/// type, remove the placeholder cast.
2103Expr *Sema::stripARCUnbridgedCast(Expr *e) {
2104 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2105
2106 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
2107 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
2108 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
2109 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
2110 assert(uo->getOpcode() == UO_Extension);
2111 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
2112 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
2113 sub->getValueKind(), sub->getObjectKind(),
2114 uo->getOperatorLoc());
2115 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
2116 assert(!gse->isResultDependent());
2117
2118 unsigned n = gse->getNumAssocs();
2119 SmallVector<Expr*, 4> subExprs(n);
2120 SmallVector<TypeSourceInfo*, 4> subTypes(n);
2121 for (unsigned i = 0; i != n; ++i) {
2122 subTypes[i] = gse->getAssocTypeSourceInfo(i);
2123 Expr *sub = gse->getAssocExpr(i);
2124 if (i == gse->getResultIndex())
2125 sub = stripARCUnbridgedCast(sub);
2126 subExprs[i] = sub;
2127 }
2128
2129 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
2130 gse->getControllingExpr(),
2131 subTypes.data(), subExprs.data(),
2132 n, gse->getDefaultLoc(),
2133 gse->getRParenLoc(),
2134 gse->containsUnexpandedParameterPack(),
2135 gse->getResultIndex());
2136 } else {
2137 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
2138 return cast<ImplicitCastExpr>(e)->getSubExpr();
2139 }
2140}
2141
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00002142bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
2143 QualType exprType) {
2144 QualType canCastType =
2145 Context.getCanonicalType(castType).getUnqualifiedType();
2146 QualType canExprType =
2147 Context.getCanonicalType(exprType).getUnqualifiedType();
2148 if (isa<ObjCObjectPointerType>(canCastType) &&
2149 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
2150 canExprType->isObjCObjectPointerType()) {
2151 if (const ObjCObjectPointerType *ObjT =
2152 canExprType->getAs<ObjCObjectPointerType>())
2153 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
2154 return false;
2155 }
2156 return true;
2157}
2158
John McCall7e5e5f42011-07-07 06:58:02 +00002159/// Look for an ObjCReclaimReturnedObject cast and destroy it.
2160static Expr *maybeUndoReclaimObject(Expr *e) {
2161 // For now, we just undo operands that are *immediately* reclaim
2162 // expressions, which prevents the vast majority of potential
2163 // problems here. To catch them all, we'd need to rebuild arbitrary
2164 // value-propagating subexpressions --- we can't reliably rebuild
2165 // in-place because of expression sharing.
2166 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00002167 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00002168 return ice->getSubExpr();
2169
2170 return e;
2171}
2172
John McCallf85e1932011-06-15 23:02:42 +00002173ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
2174 ObjCBridgeCastKind Kind,
2175 SourceLocation BridgeKeywordLoc,
2176 TypeSourceInfo *TSInfo,
2177 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00002178 ExprResult SubResult = UsualUnaryConversions(SubExpr);
2179 if (SubResult.isInvalid()) return ExprError();
2180 SubExpr = SubResult.take();
2181
John McCallf85e1932011-06-15 23:02:42 +00002182 QualType T = TSInfo->getType();
2183 QualType FromType = SubExpr->getType();
2184
John McCall1d9b3b22011-09-09 05:25:32 +00002185 CastKind CK;
2186
John McCallf85e1932011-06-15 23:02:42 +00002187 bool MustConsume = false;
2188 if (T->isDependentType() || SubExpr->isTypeDependent()) {
2189 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00002190 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00002191 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
2192 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00002193 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
2194 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00002195 switch (Kind) {
2196 case OBC_Bridge:
2197 break;
2198
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002199 case OBC_BridgeRetained: {
2200 bool br = KnownName(*this, "CFBridgingRelease");
John McCallf85e1932011-06-15 23:02:42 +00002201 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2202 << 2
2203 << FromType
2204 << (T->isBlockPointerType()? 1 : 0)
2205 << T
2206 << SubExpr->getSourceRange()
2207 << Kind;
2208 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2209 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
2210 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002211 << FromType << br
John McCallf85e1932011-06-15 23:02:42 +00002212 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002213 br ? "CFBridgingRelease "
2214 : "__bridge_transfer ");
John McCallf85e1932011-06-15 23:02:42 +00002215
2216 Kind = OBC_Bridge;
2217 break;
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002218 }
John McCallf85e1932011-06-15 23:02:42 +00002219
2220 case OBC_BridgeTransfer:
2221 // We must consume the Objective-C object produced by the cast.
2222 MustConsume = true;
2223 break;
2224 }
2225 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
2226 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00002227 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00002228 switch (Kind) {
2229 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00002230 // Reclaiming a value that's going to be __bridge-casted to CF
2231 // is very dangerous, so we don't do it.
2232 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00002233 break;
2234
2235 case OBC_BridgeRetained:
2236 // Produce the object before casting it.
2237 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00002238 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00002239 SubExpr, 0, VK_RValue);
2240 break;
2241
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002242 case OBC_BridgeTransfer: {
2243 bool br = KnownName(*this, "CFBridgingRetain");
John McCallf85e1932011-06-15 23:02:42 +00002244 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2245 << (FromType->isBlockPointerType()? 1 : 0)
2246 << FromType
2247 << 2
2248 << T
2249 << SubExpr->getSourceRange()
2250 << Kind;
2251
2252 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2253 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
2254 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002255 << T << br
2256 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2257 br ? "CFBridgingRetain " : "__bridge_retained");
John McCallf85e1932011-06-15 23:02:42 +00002258
2259 Kind = OBC_Bridge;
2260 break;
2261 }
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002262 }
John McCallf85e1932011-06-15 23:02:42 +00002263 } else {
2264 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
2265 << FromType << T << Kind
2266 << SubExpr->getSourceRange()
2267 << TSInfo->getTypeLoc().getSourceRange();
2268 return ExprError();
2269 }
2270
John McCall1d9b3b22011-09-09 05:25:32 +00002271 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00002272 BridgeKeywordLoc,
2273 TSInfo, SubExpr);
2274
2275 if (MustConsume) {
2276 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00002277 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00002278 0, VK_RValue);
2279 }
2280
2281 return Result;
2282}
2283
2284ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
2285 SourceLocation LParenLoc,
2286 ObjCBridgeCastKind Kind,
2287 SourceLocation BridgeKeywordLoc,
2288 ParsedType Type,
2289 SourceLocation RParenLoc,
2290 Expr *SubExpr) {
2291 TypeSourceInfo *TSInfo = 0;
2292 QualType T = GetTypeFromParser(Type, &TSInfo);
2293 if (!TSInfo)
2294 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
2295 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
2296 SubExpr);
2297}