blob: e9742a988ff92360c020c4f9300286daca1a5ec3 [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.
Chris Lattner39c28bb2009-02-18 06:48:40 +000046 llvm::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'.
240ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
241 // Ignore block scopes: we can capture through them.
242 DeclContext *DC = CurContext;
243 while (true) {
244 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
245 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
246 else break;
247 }
248
249 // If we're not in an ObjC method, error out. Note that, unlike the
250 // C++ case, we don't require an instance method --- class methods
251 // still have a 'self', and we really do still need to capture it!
252 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
253 if (!method)
254 return 0;
255
256 ImplicitParamDecl *self = method->getSelfDecl();
257 assert(self && "capturing 'self' in non-definition?");
258
259 // Mark that we're closing on 'this' in all the block scopes, if applicable.
260 for (unsigned idx = FunctionScopes.size() - 1;
261 isa<BlockScopeInfo>(FunctionScopes[idx]);
John McCall6b5a61b2011-02-07 10:33:21 +0000262 --idx) {
263 BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
264 unsigned &captureIndex = blockScope->CaptureMap[self];
265 if (captureIndex) break;
266
267 bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
Eli Friedmanb69b42c2012-01-11 02:36:31 +0000268 blockScope->AddCapture(self, /*byref*/ false, nested, /*copy*/ 0);
John McCall6b5a61b2011-02-07 10:33:21 +0000269 captureIndex = blockScope->Captures.size(); // +1
270 }
John McCall26743b22011-02-03 09:00:02 +0000271
272 return method;
273}
274
Douglas Gregor5c16d632011-09-09 20:05:21 +0000275static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
276 if (T == Context.getObjCInstanceType())
277 return Context.getObjCIdType();
278
279 return T;
280}
281
Douglas Gregor926df6c2011-06-11 01:09:30 +0000282QualType Sema::getMessageSendResultType(QualType ReceiverType,
283 ObjCMethodDecl *Method,
284 bool isClassMessage, bool isSuperMessage) {
285 assert(Method && "Must have a method");
286 if (!Method->hasRelatedResultType())
287 return Method->getSendResultType();
288
289 // If a method has a related return type:
290 // - if the method found is an instance method, but the message send
291 // was a class message send, T is the declared return type of the method
292 // found
293 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor5c16d632011-09-09 20:05:21 +0000294 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000295
296 // - if the receiver is super, T is a pointer to the class of the
297 // enclosing method definition
298 if (isSuperMessage) {
299 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
300 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
301 return Context.getObjCObjectPointerType(
302 Context.getObjCInterfaceType(Class));
303 }
304
305 // - if the receiver is the name of a class U, T is a pointer to U
306 if (ReceiverType->getAs<ObjCInterfaceType>() ||
307 ReceiverType->isObjCQualifiedInterfaceType())
308 return Context.getObjCObjectPointerType(ReceiverType);
309 // - if the receiver is of type Class or qualified Class type,
310 // T is the declared return type of the method.
311 if (ReceiverType->isObjCClassType() ||
312 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor5c16d632011-09-09 20:05:21 +0000313 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000314
315 // - if the receiver is id, qualified id, Class, or qualified Class, T
316 // is the receiver type, otherwise
317 // - T is the type of the receiver expression.
318 return ReceiverType;
319}
John McCall26743b22011-02-03 09:00:02 +0000320
Douglas Gregor926df6c2011-06-11 01:09:30 +0000321void Sema::EmitRelatedResultTypeNote(const Expr *E) {
322 E = E->IgnoreParenImpCasts();
323 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
324 if (!MsgSend)
325 return;
326
327 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
328 if (!Method)
329 return;
330
331 if (!Method->hasRelatedResultType())
332 return;
333
334 if (Context.hasSameUnqualifiedType(Method->getResultType()
335 .getNonReferenceType(),
336 MsgSend->getType()))
337 return;
338
Douglas Gregore97179c2011-09-08 01:46:34 +0000339 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
340 Context.getObjCInstanceType()))
341 return;
342
Douglas Gregor926df6c2011-06-11 01:09:30 +0000343 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
344 << Method->isInstanceMethod() << Method->getSelector()
345 << MsgSend->getType();
346}
347
348bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
349 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000350 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000351 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000352 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000353 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000354 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000355 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000356 for (unsigned i = 0; i != NumArgs; i++) {
357 if (Args[i]->isTypeDependent())
358 continue;
359
John Wiegley429bb272011-04-08 18:41:53 +0000360 ExprResult Result = DefaultArgumentPromotion(Args[i]);
361 if (Result.isInvalid())
362 return true;
363 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000364 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000365
John McCallf85e1932011-06-15 23:02:42 +0000366 unsigned DiagID;
367 if (getLangOptions().ObjCAutoRefCount)
368 DiagID = diag::err_arc_method_not_found;
369 else
370 DiagID = isClassMessage ? diag::warn_class_method_not_found
371 : diag::warn_inst_method_not_found;
John McCall819e7452011-08-31 20:57:36 +0000372 if (!getLangOptions().DebuggerSupport)
373 Diag(lbrac, DiagID)
374 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +0000375
376 // In debuggers, we want to use __unknown_anytype for these
377 // results so that clients can cast them.
378 if (getLangOptions().DebuggerSupport) {
379 ReturnType = Context.UnknownAnyTy;
380 } else {
381 ReturnType = Context.getObjCIdType();
382 }
John McCallf89e55a2010-11-18 06:31:45 +0000383 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000384 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000385 }
Mike Stump1eb44332009-09-09 15:08:12 +0000386
Douglas Gregor926df6c2011-06-11 01:09:30 +0000387 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
388 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000389 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000391 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000392 // Method might have more arguments than selector indicates. This is due
393 // to addition of c-style arguments in method.
394 if (Method->param_size() > Sel.getNumArgs())
395 NumNamedArgs = Method->param_size();
396 // FIXME. This need be cleaned up.
397 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000398 Diag(lbrac, diag::err_typecheck_call_too_few_args)
399 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000400 return false;
401 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000402
Chris Lattner312531a2009-04-12 08:11:20 +0000403 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000404 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000405 // We can't do any type-checking on a type-dependent argument.
406 if (Args[i]->isTypeDependent())
407 continue;
408
Chris Lattner85a932e2008-01-04 22:32:30 +0000409 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000410
John McCall5acb0c92011-10-17 18:40:02 +0000411 ParmVarDecl *param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000412 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000413
John McCall5acb0c92011-10-17 18:40:02 +0000414 // Strip the unbridged-cast placeholder expression off unless it's
415 // a consumed argument.
416 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
417 !param->hasAttr<CFConsumedAttr>())
418 argExpr = stripARCUnbridgedCast(argExpr);
419
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000420 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall5acb0c92011-10-17 18:40:02 +0000421 param->getType(),
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000422 PDiag(diag::err_call_incomplete_argument)
423 << argExpr->getSourceRange()))
424 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000425
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000426 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall5acb0c92011-10-17 18:40:02 +0000427 param);
John McCall3fa5cae2010-10-26 07:05:15 +0000428 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000429 if (ArgE.isInvalid())
430 IsError = true;
431 else
432 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000433 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000434
435 // Promote additional arguments to variadic methods.
436 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000437 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
438 if (Args[i]->isTypeDependent())
439 continue;
440
John Wiegley429bb272011-04-08 18:41:53 +0000441 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
442 IsError |= Arg.isInvalid();
443 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000444 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000445 } else {
446 // Check for extra arguments to non-variadic methods.
447 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000448 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000449 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000450 << 2 /*method*/ << NumNamedArgs << NumArgs
451 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000452 << SourceRange(Args[NumNamedArgs]->getLocStart(),
453 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000454 }
455 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000456 // diagnose nonnull arguments.
457 for (specific_attr_iterator<NonNullAttr>
458 i = Method->specific_attr_begin<NonNullAttr>(),
459 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
460 CheckNonNullArguments(*i, Args, lbrac);
461 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000462
Douglas Gregor2725ca82010-04-21 19:57:20 +0000463 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000464 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000465}
466
Douglas Gregorc737acb2011-09-27 16:10:05 +0000467bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000468 // 'self' is objc 'self' in an objc method only.
John McCall4b9c2d22011-11-06 09:01:30 +0000469 ObjCMethodDecl *method =
470 dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
471 if (!method) return false;
472
John McCallf85e1932011-06-15 23:02:42 +0000473 receiver = receiver->IgnoreParenLValueCasts();
474 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCall4b9c2d22011-11-06 09:01:30 +0000475 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregorc737acb2011-09-27 16:10:05 +0000476 return true;
477 return false;
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000478}
479
Steve Narofff1afaf62009-02-26 15:55:06 +0000480// Helper method for ActOnClassMethod/ActOnInstanceMethod.
481// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000482// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000483// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000484ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000485 ObjCInterfaceDecl *ClassDecl) {
486 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000487 // lookup in class and all superclasses
488 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000489 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000490 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Steve Naroff5609ec02009-03-08 18:56:13 +0000492 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000493 if (!Method)
494 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000495
Steve Naroff5609ec02009-03-08 18:56:13 +0000496 // Before we give up, check if the selector is an instance method.
497 // But only in the root. This matches gcc's behaviour and what the
498 // runtime expects.
499 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000500 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000501 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000502 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000503 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000504 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
505 }
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Steve Naroff5609ec02009-03-08 18:56:13 +0000507 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000508 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000509 return Method;
510}
511
512ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
513 ObjCInterfaceDecl *ClassDecl) {
Douglas Gregor2e5c15b2011-12-15 05:27:12 +0000514 if (!ClassDecl->hasDefinition())
515 return 0;
516
Steve Naroff5609ec02009-03-08 18:56:13 +0000517 ObjCMethodDecl *Method = 0;
518 while (ClassDecl && !Method) {
519 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000520 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000521 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000522
Steve Naroff5609ec02009-03-08 18:56:13 +0000523 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000524 if (!Method)
525 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000526 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000527 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000528 return Method;
529}
530
John McCall3c3b7f92011-10-25 17:37:35 +0000531/// LookupMethodInType - Look up a method in an ObjCObjectType.
532ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
533 bool isInstance) {
534 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
535 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
536 // Look it up in the main interface (and categories, etc.)
537 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
538 return method;
539
540 // Okay, look for "private" methods declared in any
541 // @implementations we've seen.
542 if (isInstance) {
543 if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
544 return method;
545 } else {
546 if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
547 return method;
548 }
549 }
550
551 // Check qualifiers.
552 for (ObjCObjectType::qual_iterator
553 i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
554 if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
555 return method;
556
557 return 0;
558}
559
Fariborz Jahanian61478062011-03-09 20:18:06 +0000560/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
561/// list of a qualified objective pointer type.
562ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
563 const ObjCObjectPointerType *OPT,
564 bool Instance)
565{
566 ObjCMethodDecl *MD = 0;
567 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
568 E = OPT->qual_end(); I != E; ++I) {
569 ObjCProtocolDecl *PROTO = (*I);
570 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
571 return MD;
572 }
573 }
574 return 0;
575}
576
Chris Lattner7f816522010-04-11 07:45:24 +0000577/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
578/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000579ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000580HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000581 Expr *BaseExpr, SourceLocation OpLoc,
582 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000583 SourceLocation MemberLoc,
584 SourceLocation SuperLoc, QualType SuperType,
585 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000586 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
587 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000588
589 if (MemberName.getNameKind() != DeclarationName::Identifier) {
590 Diag(MemberLoc, diag::err_invalid_property_name)
591 << MemberName << QualType(OPT, 0);
592 return ExprError();
593 }
594
Chris Lattner7f816522010-04-11 07:45:24 +0000595 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregorb3029962011-11-14 22:10:01 +0000596 SourceRange BaseRange = Super? SourceRange(SuperLoc)
597 : BaseExpr->getSourceRange();
598 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
599 PDiag(diag::err_property_not_found_forward_class)
600 << MemberName << BaseRange))
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000601 return ExprError();
Douglas Gregorb3029962011-11-14 22:10:01 +0000602
Chris Lattner7f816522010-04-11 07:45:24 +0000603 // Search for a declared property first.
604 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
605 // Check whether we can reference this property.
606 if (DiagnoseUseOfDecl(PD, MemberLoc))
607 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000608
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000609 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +0000610 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000611 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000612 MemberLoc,
613 SuperLoc, SuperType));
614 else
John McCall3c3b7f92011-10-25 17:37:35 +0000615 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000616 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000617 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000618 }
619 // Check protocols on qualified interfaces.
620 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
621 E = OPT->qual_end(); I != E; ++I)
622 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
623 // Check whether we can reference this property.
624 if (DiagnoseUseOfDecl(PD, MemberLoc))
625 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000626
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000627 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +0000628 return Owned(new (Context) ObjCPropertyRefExpr(PD,
629 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000630 VK_LValue,
631 OK_ObjCProperty,
632 MemberLoc,
633 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000634 else
John McCall3c3b7f92011-10-25 17:37:35 +0000635 return Owned(new (Context) ObjCPropertyRefExpr(PD,
636 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000637 VK_LValue,
638 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000639 MemberLoc,
640 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000641 }
642 // If that failed, look for an "implicit" property by seeing if the nullary
643 // selector is implemented.
644
645 // FIXME: The logic for looking up nullary and unary selectors should be
646 // shared with the code in ActOnInstanceMessage.
647
648 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
649 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000650
651 // May be founf in property's qualified list.
652 if (!Getter)
653 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000654
655 // If this reference is in an @implementation, check for 'private' methods.
656 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000657 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000658
659 // Look through local category implementations associated with the class.
660 if (!Getter)
661 Getter = IFace->getCategoryInstanceMethod(Sel);
662 if (Getter) {
663 // Check if we can reference this property.
664 if (DiagnoseUseOfDecl(Getter, MemberLoc))
665 return ExprError();
666 }
667 // If we found a getter then this may be a valid dot-reference, we
668 // will look for the matching setter, in case it is needed.
669 Selector SetterSel =
670 SelectorTable::constructSetterName(PP.getIdentifierTable(),
671 PP.getSelectorTable(), Member);
672 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000673
674 // May be founf in property's qualified list.
675 if (!Setter)
676 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
677
Chris Lattner7f816522010-04-11 07:45:24 +0000678 if (!Setter) {
679 // If this reference is in an @implementation, also check for 'private'
680 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000681 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000682 }
683 // Look through local category implementations associated with the class.
684 if (!Setter)
685 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000686
Chris Lattner7f816522010-04-11 07:45:24 +0000687 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
688 return ExprError();
689
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000690 if (Getter || Setter) {
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000691 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000692 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +0000693 Context.PseudoObjectTy,
694 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +0000695 MemberLoc,
696 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000697 else
John McCall12f78a62010-12-02 01:19:52 +0000698 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +0000699 Context.PseudoObjectTy,
700 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +0000701 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000702
Chris Lattner7f816522010-04-11 07:45:24 +0000703 }
704
705 // Attempt to correct for typos in property names.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000706 TypoCorrection Corrected = CorrectTypo(
707 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
708 NULL, IFace, false, CTC_NoKeywords, OPT);
709 if (ObjCPropertyDecl *Property =
710 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>()) {
711 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +0000712 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000713 << MemberName << QualType(OPT, 0) << TypoResult
714 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000715 Diag(Property->getLocation(), diag::note_previous_decl)
716 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000717 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
718 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000719 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000720 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000721 ObjCInterfaceDecl *ClassDeclared;
722 if (ObjCIvarDecl *Ivar =
723 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
724 QualType T = Ivar->getType();
725 if (const ObjCObjectPointerType * OBJPT =
726 T->getAsObjCInterfacePointerType()) {
Douglas Gregorb3029962011-11-14 22:10:01 +0000727 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
728 PDiag(diag::err_property_not_as_forward_class)
729 << MemberName << BaseExpr->getSourceRange()))
730 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000731 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000732 Diag(MemberLoc,
733 diag::err_ivar_access_using_property_syntax_suggest)
734 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
735 << FixItHint::CreateReplacement(OpLoc, "->");
736 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000737 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000738
Chris Lattner7f816522010-04-11 07:45:24 +0000739 Diag(MemberLoc, diag::err_property_not_found)
740 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000741 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000742 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000743 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000744 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000745}
746
747
748
John McCall60d7b3a2010-08-24 06:29:42 +0000749ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000750ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
751 IdentifierInfo &propertyName,
752 SourceLocation receiverNameLoc,
753 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000755 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000756 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
757 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000758
759 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000760 if (IFace == 0) {
761 // If the "receiver" is 'super' in a method, handle it as an expression-like
762 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000763 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000764 IsSuper = true;
765
John McCall26743b22011-02-03 09:00:02 +0000766 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000767 if (CurMethod->isInstanceMethod()) {
768 QualType T =
769 Context.getObjCInterfaceType(CurMethod->getClassInterface());
770 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000771
772 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000773 /*BaseExpr*/0,
774 SourceLocation()/*OpLoc*/,
775 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000776 propertyNameLoc,
777 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000778 }
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Chris Lattnereb483eb2010-04-11 08:28:14 +0000780 // Otherwise, if this is a class method, try dispatching to our
781 // superclass.
782 IFace = CurMethod->getClassInterface()->getSuperClass();
783 }
John McCall26743b22011-02-03 09:00:02 +0000784 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000785
786 if (IFace == 0) {
787 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
788 return ExprError();
789 }
790 }
791
792 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000793 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000794 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000795
796 // If this reference is in an @implementation, check for 'private' methods.
797 if (!Getter)
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 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000802
803 if (Getter) {
804 // FIXME: refactor/share with ActOnMemberReference().
805 // Check if we can reference this property.
806 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
807 return ExprError();
808 }
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Steve Naroff61f72cb2009-03-09 21:12:44 +0000810 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000811 Selector SetterSel =
812 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000813 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000814
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000815 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000816 if (!Setter) {
817 // If this reference is in an @implementation, also check for 'private'
818 // methods.
819 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
820 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000821 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000822 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000823 }
824 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000825 if (!Setter)
826 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000827
828 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
829 return ExprError();
830
831 if (Getter || Setter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000832 if (IsSuper)
833 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +0000834 Context.PseudoObjectTy,
835 VK_LValue, OK_ObjCProperty,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000836 propertyNameLoc,
837 receiverNameLoc,
838 Context.getObjCInterfaceType(IFace)));
839
John McCall12f78a62010-12-02 01:19:52 +0000840 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +0000841 Context.PseudoObjectTy,
842 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +0000843 propertyNameLoc,
844 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000845 }
846 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
847 << &propertyName << Context.getObjCInterfaceType(IFace));
848}
849
Douglas Gregor47bd5432010-04-14 02:46:37 +0000850Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000851 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000852 SourceLocation NameLoc,
853 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000854 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000855 ParsedType &ReceiverType) {
856 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000857
Douglas Gregor47bd5432010-04-14 02:46:37 +0000858 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000859 // messaging super. If the identifier is "super" and there is a
860 // trailing dot, it's an instance message.
861 if (IsSuper && S->isInObjcMethodScope())
862 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000863
864 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
865 LookupName(Result, S);
866
867 switch (Result.getResultKind()) {
868 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000869 // Normal name lookup didn't find anything. If we're in an
870 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000871 // FIXME: This is a hack. Ivar lookup should be part of normal
872 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000873 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidisccc9e762011-11-09 00:22:48 +0000874 if (!Method->getClassInterface()) {
875 // Fall back: let the parser try to parse it as an instance message.
876 return ObjCInstanceMessage;
877 }
878
Douglas Gregored464422010-04-19 20:09:36 +0000879 ObjCInterfaceDecl *ClassDeclared;
880 if (Method->getClassInterface()->lookupInstanceVariable(Name,
881 ClassDeclared))
882 return ObjCInstanceMessage;
883 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000884
Douglas Gregor47bd5432010-04-14 02:46:37 +0000885 // Break out; we'll perform typo correction below.
886 break;
887
888 case LookupResult::NotFoundInCurrentInstantiation:
889 case LookupResult::FoundOverloaded:
890 case LookupResult::FoundUnresolvedValue:
891 case LookupResult::Ambiguous:
892 Result.suppressDiagnostics();
893 return ObjCInstanceMessage;
894
895 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000896 // If the identifier is a class or not, and there is a trailing dot,
897 // it's an instance message.
898 if (HasTrailingDot)
899 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000900 // We found something. If it's a type, then we have a class
901 // message. Otherwise, it's an instance message.
902 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000903 QualType T;
904 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
905 T = Context.getObjCInterfaceType(Class);
906 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
907 T = Context.getTypeDeclType(Type);
908 else
909 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000910
Douglas Gregor1569f952010-04-21 20:38:13 +0000911 // We have a class message, and T is the type we're
912 // messaging. Build source-location information for it.
913 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000914 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000915 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000916 }
917 }
918
Douglas Gregoraaf87162010-04-14 20:04:41 +0000919 // Determine our typo-correction context.
920 CorrectTypoContext CTC = CTC_Expression;
921 if (ObjCMethodDecl *Method = getCurMethodDecl())
922 if (Method->getClassInterface() &&
923 Method->getClassInterface()->getSuperClass())
924 CTC = CTC_ObjCMessageReceiver;
925
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000926 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
927 Result.getLookupKind(), S, NULL,
928 NULL, false, CTC)) {
929 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000930 // If we found a declaration, correct when it refers to an Objective-C
931 // class.
Douglas Gregor1569f952010-04-21 20:38:13 +0000932 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000933 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000934 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000935 << FixItHint::CreateReplacement(SourceRange(NameLoc),
936 ND->getNameAsString());
937 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000938 << Corrected.getCorrection();
Douglas Gregor47bd5432010-04-14 02:46:37 +0000939
Douglas Gregor1569f952010-04-21 20:38:13 +0000940 QualType T = Context.getObjCInterfaceType(Class);
941 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000942 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000943 return ObjCClassMessage;
944 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000945 } else if (Corrected.isKeyword() &&
946 Corrected.getCorrectionAsIdentifierInfo()->isStr("super")) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000947 // If we've found the keyword "super", this is a send to super.
948 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000949 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000950 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000951 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000952 }
953 }
954
955 // Fall back: let the parser try to parse it as an instance message.
956 return ObjCInstanceMessage;
957}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000958
John McCall60d7b3a2010-08-24 06:29:42 +0000959ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000960 SourceLocation SuperLoc,
961 Selector Sel,
962 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +0000963 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000964 SourceLocation RBracLoc,
965 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000966 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000967 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000968 if (!Method) {
969 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
970 return ExprError();
971 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000972
Douglas Gregorf95861a2010-04-21 20:01:04 +0000973 ObjCInterfaceDecl *Class = Method->getClassInterface();
974 if (!Class) {
975 Diag(SuperLoc, diag::error_no_super_class_message)
976 << Method->getDeclName();
977 return ExprError();
978 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000979
Douglas Gregorf95861a2010-04-21 20:01:04 +0000980 ObjCInterfaceDecl *Super = Class->getSuperClass();
981 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000982 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000983 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
984 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000985 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000986 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000987
Douglas Gregorf95861a2010-04-21 20:01:04 +0000988 // We are in a method whose class has a superclass, so 'super'
989 // is acting as a keyword.
990 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +0000991 if (Sel.getMethodFamily() == OMF_dealloc)
992 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +0000993 if (Sel.getMethodFamily() == OMF_finalize)
994 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +0000995
Douglas Gregorf95861a2010-04-21 20:01:04 +0000996 // Since we are in an instance method, this is an instance
997 // message to the superclass instance.
998 QualType SuperTy = Context.getObjCInterfaceType(Super);
999 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +00001000 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001001 Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001002 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001003 }
Douglas Gregorf95861a2010-04-21 20:01:04 +00001004
1005 // Since we are in a class method, this is a class message to
1006 // the superclass.
1007 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1008 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001009 SuperLoc, Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001010 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001011}
1012
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001013
1014ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1015 bool isSuperReceiver,
1016 SourceLocation Loc,
1017 Selector Sel,
1018 ObjCMethodDecl *Method,
1019 MultiExprArg Args) {
1020 TypeSourceInfo *receiverTypeInfo = 0;
1021 if (!ReceiverType.isNull())
1022 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1023
1024 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1025 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1026 Sel, Method, Loc, Loc, Loc, Args,
1027 /*isImplicit=*/true);
1028
1029}
1030
Douglas Gregor2725ca82010-04-21 19:57:20 +00001031/// \brief Build an Objective-C class message expression.
1032///
1033/// This routine takes care of both normal class messages and
1034/// class messages to the superclass.
1035///
1036/// \param ReceiverTypeInfo Type source information that describes the
1037/// receiver of this message. This may be NULL, in which case we are
1038/// sending to the superclass and \p SuperLoc must be a valid source
1039/// location.
1040
1041/// \param ReceiverType The type of the object receiving the
1042/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1043/// type as that refers to. For a superclass send, this is the type of
1044/// the superclass.
1045///
1046/// \param SuperLoc The location of the "super" keyword in a
1047/// superclass message.
1048///
1049/// \param Sel The selector to which the message is being sent.
1050///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001051/// \param Method The method that this class message is invoking, if
1052/// already known.
1053///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001054/// \param LBracLoc The location of the opening square bracket ']'.
1055///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001056/// \param RBrac The location of the closing square bracket ']'.
1057///
1058/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001059ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001060 QualType ReceiverType,
1061 SourceLocation SuperLoc,
1062 Selector Sel,
1063 ObjCMethodDecl *Method,
1064 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001065 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001066 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001067 MultiExprArg ArgsIn,
1068 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001069 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001070 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001071 if (LBracLoc.isInvalid()) {
1072 Diag(Loc, diag::err_missing_open_square_message_send)
1073 << FixItHint::CreateInsertion(Loc, "[");
1074 LBracLoc = Loc;
1075 }
1076
Douglas Gregor92e986e2010-04-22 16:44:27 +00001077 if (ReceiverType->isDependentType()) {
1078 // If the receiver type is dependent, we can't type-check anything
1079 // at this point. Build a dependent expression.
1080 unsigned NumArgs = ArgsIn.size();
1081 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1082 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001083 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1084 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001085 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001086 makeArrayRef(Args, NumArgs),RBracLoc,
1087 isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001088 }
Chris Lattner15faee12010-04-12 05:38:43 +00001089
Douglas Gregor2725ca82010-04-21 19:57:20 +00001090 // Find the class to which we are sending this message.
1091 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001092 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1093 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001094 Diag(Loc, diag::err_invalid_receiver_class_message)
1095 << ReceiverType;
1096 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001097 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001098 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001099 // objc++ diagnoses during typename annotation.
1100 if (!getLangOptions().CPlusPlus)
1101 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001102 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001103 if (!Method) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001104 SourceRange TypeRange
1105 = SuperLoc.isValid()? SourceRange(SuperLoc)
1106 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
1107 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
1108 (getLangOptions().ObjCAutoRefCount
1109 ? PDiag(diag::err_arc_receiver_forward_class)
1110 : PDiag(diag::warn_receiver_forward_class))
1111 << TypeRange)) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001112 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001113 Method = LookupFactoryMethodInGlobalPool(Sel,
1114 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001115 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001116 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1117 << Method->getDeclName();
1118 }
1119 if (!Method)
1120 Method = Class->lookupClassMethod(Sel);
1121
1122 // If we have an implementation in scope, check "private" methods.
1123 if (!Method)
1124 Method = LookupPrivateClassMethod(Sel, Class);
1125
1126 if (Method && DiagnoseUseOfDecl(Method, Loc))
1127 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001128 }
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Douglas Gregor2725ca82010-04-21 19:57:20 +00001130 // Check the argument types and determine the result type.
1131 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001132 ExprValueKind VK = VK_RValue;
1133
Douglas Gregor2725ca82010-04-21 19:57:20 +00001134 unsigned NumArgs = ArgsIn.size();
1135 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001136 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1137 SuperLoc.isValid(), LBracLoc, RBracLoc,
1138 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001139 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001140
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001141 if (Method && !Method->getResultType()->isVoidType() &&
1142 RequireCompleteType(LBracLoc, Method->getResultType(),
1143 diag::err_illegal_message_expr_incomplete_type))
1144 return ExprError();
1145
Douglas Gregor2725ca82010-04-21 19:57:20 +00001146 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001147 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001148 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001149 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001150 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001151 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001152 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001153 RBracLoc, isImplicit);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001154 else
John McCallf89e55a2010-11-18 06:31:45 +00001155 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001156 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001157 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001158 RBracLoc, isImplicit);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001159 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001160}
1161
Douglas Gregor2725ca82010-04-21 19:57:20 +00001162// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001163// ArgExprs is optional - if it is present, the number of expressions
1164// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001165ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001166 ParsedType Receiver,
1167 Selector Sel,
1168 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001169 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor77328d12010-09-15 23:19:31 +00001170 SourceLocation RBracLoc,
1171 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001172 TypeSourceInfo *ReceiverTypeInfo;
1173 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1174 if (ReceiverType.isNull())
1175 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001176
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Douglas Gregor2725ca82010-04-21 19:57:20 +00001178 if (!ReceiverTypeInfo)
1179 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1180
1181 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001182 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001183 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001184}
1185
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001186ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
1187 QualType ReceiverType,
1188 SourceLocation Loc,
1189 Selector Sel,
1190 ObjCMethodDecl *Method,
1191 MultiExprArg Args) {
1192 return BuildInstanceMessage(Receiver, ReceiverType,
1193 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
1194 Sel, Method, Loc, Loc, Loc, Args,
1195 /*isImplicit=*/true);
1196}
1197
Douglas Gregor2725ca82010-04-21 19:57:20 +00001198/// \brief Build an Objective-C instance message expression.
1199///
1200/// This routine takes care of both normal instance messages and
1201/// instance messages to the superclass instance.
1202///
1203/// \param Receiver The expression that computes the object that will
1204/// receive this message. This may be empty, in which case we are
1205/// sending to the superclass instance and \p SuperLoc must be a valid
1206/// source location.
1207///
1208/// \param ReceiverType The (static) type of the object receiving the
1209/// message. When a \p Receiver expression is provided, this is the
1210/// same type as that expression. For a superclass instance send, this
1211/// is a pointer to the type of the superclass.
1212///
1213/// \param SuperLoc The location of the "super" keyword in a
1214/// superclass instance message.
1215///
1216/// \param Sel The selector to which the message is being sent.
1217///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001218/// \param Method The method that this instance message is invoking, if
1219/// already known.
1220///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001221/// \param LBracLoc The location of the opening square bracket ']'.
1222///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001223/// \param RBrac The location of the closing square bracket ']'.
1224///
1225/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001226ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001227 QualType ReceiverType,
1228 SourceLocation SuperLoc,
1229 Selector Sel,
1230 ObjCMethodDecl *Method,
1231 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001232 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001233 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001234 MultiExprArg ArgsIn,
1235 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001236 // The location of the receiver.
1237 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1238
1239 if (LBracLoc.isInvalid()) {
1240 Diag(Loc, diag::err_missing_open_square_message_send)
1241 << FixItHint::CreateInsertion(Loc, "[");
1242 LBracLoc = Loc;
1243 }
1244
Douglas Gregor2725ca82010-04-21 19:57:20 +00001245 // If we have a receiver expression, perform appropriate promotions
1246 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001247 if (Receiver) {
John McCall5acb0c92011-10-17 18:40:02 +00001248 if (Receiver->hasPlaceholderType()) {
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00001249 ExprResult Result;
1250 if (Receiver->getType() == Context.UnknownAnyTy)
1251 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
1252 else
1253 Result = CheckPlaceholderExpr(Receiver);
1254 if (Result.isInvalid()) return ExprError();
1255 Receiver = Result.take();
John McCall5acb0c92011-10-17 18:40:02 +00001256 }
1257
Douglas Gregor92e986e2010-04-22 16:44:27 +00001258 if (Receiver->isTypeDependent()) {
1259 // If the receiver is type-dependent, we can't type-check anything
1260 // at this point. Build a dependent expression.
1261 unsigned NumArgs = ArgsIn.size();
1262 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1263 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1264 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001265 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001266 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001267 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001268 RBracLoc, isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001269 }
1270
Douglas Gregor2725ca82010-04-21 19:57:20 +00001271 // If necessary, apply function/array conversion to the receiver.
1272 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001273 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1274 if (Result.isInvalid())
1275 return ExprError();
1276 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001277 ReceiverType = Receiver->getType();
1278 }
1279
Douglas Gregorf49bb082010-04-22 17:01:48 +00001280 if (!Method) {
1281 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001282 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001283 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001284 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1285 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001286 SourceRange(LBracLoc, RBracLoc),
1287 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001288 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001289 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001290 SourceRange(LBracLoc, RBracLoc),
1291 receiverIsId);
Fariborz Jahanianb76a97e2011-12-07 00:30:00 +00001292 if (Method)
1293 DiagnoseAvailabilityOfDecl(Method, Loc, 0);
1294
Douglas Gregorf49bb082010-04-22 17:01:48 +00001295 } else if (ReceiverType->isObjCClassType() ||
1296 ReceiverType->isObjCQualifiedClassType()) {
1297 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001298 // We allow sending a message to a qualified Class ("Class<foo>"), which
1299 // is ok as long as one of the protocols implements the selector (if not, warn).
1300 if (const ObjCObjectPointerType *QClassTy
1301 = ReceiverType->getAsObjCQualifiedClassType()) {
1302 // Search protocols for class methods.
1303 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1304 if (!Method) {
1305 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1306 // warn if instance method found for a Class message.
1307 if (Method) {
1308 Diag(Loc, diag::warn_instance_method_on_class_found)
1309 << Method->getSelector() << Sel;
1310 Diag(Method->getLocation(), diag::note_method_declared_at);
1311 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001312 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001313 } else {
1314 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1315 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1316 // First check the public methods in the class interface.
1317 Method = ClassDecl->lookupClassMethod(Sel);
1318
1319 if (!Method)
1320 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1321 }
1322 if (Method && DiagnoseUseOfDecl(Method, Loc))
1323 return ExprError();
1324 }
1325 if (!Method) {
1326 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00001327 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001328 Method = LookupFactoryMethodInGlobalPool(Sel,
1329 SourceRange(LBracLoc, RBracLoc),
1330 true);
1331 if (!Method) {
1332 // If no class (factory) method was found, check if an _instance_
1333 // method of the same name exists in the root class only.
1334 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001335 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001336 true);
1337 if (Method)
1338 if (const ObjCInterfaceDecl *ID =
1339 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1340 if (ID->getSuperClass())
1341 Diag(Loc, diag::warn_root_inst_method_not_found)
1342 << Sel << SourceRange(LBracLoc, RBracLoc);
1343 }
1344 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001345 }
1346 }
1347 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001348 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001349 ObjCInterfaceDecl* ClassDecl = 0;
1350
1351 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1352 // long as one of the protocols implements the selector (if not, warn).
1353 if (const ObjCObjectPointerType *QIdTy
1354 = ReceiverType->getAsObjCQualifiedIdType()) {
1355 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001356 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1357 if (!Method)
1358 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001359 } else if (const ObjCObjectPointerType *OCIType
1360 = ReceiverType->getAsObjCInterfacePointerType()) {
1361 // We allow sending a message to a pointer to an interface (an object).
1362 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001363
Douglas Gregorb3029962011-11-14 22:10:01 +00001364 // Try to complete the type. Under ARC, this is a hard error from which
1365 // we don't try to recover.
1366 const ObjCInterfaceDecl *forwardClass = 0;
1367 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
1368 getLangOptions().ObjCAutoRefCount
1369 ? PDiag(diag::err_arc_receiver_forward_instance)
1370 << (Receiver ? Receiver->getSourceRange()
1371 : SourceRange(SuperLoc))
1372 : PDiag())) {
1373 if (getLangOptions().ObjCAutoRefCount)
1374 return ExprError();
1375
1376 forwardClass = OCIType->getInterfaceDecl();
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00001377 Method = 0;
1378 } else {
1379 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCallf85e1932011-06-15 23:02:42 +00001380 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001381
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001382 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001383 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001384 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1385
Douglas Gregorf49bb082010-04-22 17:01:48 +00001386 if (!Method) {
1387 // If we have implementations in scope, check "private" methods.
1388 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1389
John McCallf85e1932011-06-15 23:02:42 +00001390 if (!Method && getLangOptions().ObjCAutoRefCount) {
1391 Diag(Loc, diag::err_arc_may_not_respond)
1392 << OCIType->getPointeeType() << Sel;
1393 return ExprError();
1394 }
1395
Douglas Gregorc737acb2011-09-27 16:10:05 +00001396 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001397 // If we still haven't found a method, look in the global pool. This
1398 // behavior isn't very desirable, however we need it for GCC
1399 // compatibility. FIXME: should we deviate??
1400 if (OCIType->qual_empty()) {
1401 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001402 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001403 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001404 Diag(Loc, diag::warn_maynot_respond)
1405 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1406 }
1407 }
1408 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001409 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001410 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001411 } else if (!getLangOptions().ObjCAutoRefCount &&
1412 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001413 (ReceiverType->isPointerType() ||
1414 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001415 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001416 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001417 Diag(Loc, diag::warn_bad_receiver_type)
1418 << ReceiverType
1419 << Receiver->getSourceRange();
1420 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001421 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00001422 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00001423 else {
1424 // TODO: specialized warning on null receivers?
1425 bool IsNull = Receiver->isNullPointerConstant(Context,
1426 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001427 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1428 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001429 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001430 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00001431 } else {
John Wiegley429bb272011-04-08 18:41:53 +00001432 ExprResult ReceiverRes;
1433 if (getLangOptions().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00001434 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00001435 if (ReceiverRes.isUsable()) {
1436 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00001437 return BuildInstanceMessage(Receiver,
1438 ReceiverType,
1439 SuperLoc,
1440 Sel,
1441 Method,
1442 LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001443 SelectorLocs,
John Wiegley429bb272011-04-08 18:41:53 +00001444 RBracLoc,
1445 move(ArgsIn));
1446 } else {
1447 // Reject other random receiver types (e.g. structs).
1448 Diag(Loc, diag::err_bad_receiver_type)
1449 << ReceiverType << Receiver->getSourceRange();
1450 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001451 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001452 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001453 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001454 }
Mike Stump1eb44332009-09-09 15:08:12 +00001455
Douglas Gregor2725ca82010-04-21 19:57:20 +00001456 // Check the message arguments.
1457 unsigned NumArgs = ArgsIn.size();
1458 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1459 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001460 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001461 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1462 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001463 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1464 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001465 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001466 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001467
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001468 if (Method && !Method->getResultType()->isVoidType() &&
1469 RequireCompleteType(LBracLoc, Method->getResultType(),
1470 diag::err_illegal_message_expr_incomplete_type))
1471 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001472
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001473 SourceLocation SelLoc = SelectorLocs.front();
1474
John McCallf85e1932011-06-15 23:02:42 +00001475 // In ARC, forbid the user from sending messages to
1476 // retain/release/autorelease/dealloc/retainCount explicitly.
1477 if (getLangOptions().ObjCAutoRefCount) {
1478 ObjCMethodFamily family =
1479 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1480 switch (family) {
1481 case OMF_init:
1482 if (Method)
1483 checkInitMethod(Method, ReceiverType);
1484
1485 case OMF_None:
1486 case OMF_alloc:
1487 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00001488 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00001489 case OMF_mutableCopy:
1490 case OMF_new:
1491 case OMF_self:
1492 break;
1493
1494 case OMF_dealloc:
1495 case OMF_retain:
1496 case OMF_release:
1497 case OMF_autorelease:
1498 case OMF_retainCount:
1499 Diag(Loc, diag::err_arc_illegal_explicit_message)
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001500 << Sel << SelLoc;
John McCallf85e1932011-06-15 23:02:42 +00001501 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001502
1503 case OMF_performSelector:
1504 if (Method && NumArgs >= 1) {
1505 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1506 Selector ArgSel = SelExp->getSelector();
1507 ObjCMethodDecl *SelMethod =
1508 LookupInstanceMethodInGlobalPool(ArgSel,
1509 SelExp->getSourceRange());
1510 if (!SelMethod)
1511 SelMethod =
1512 LookupFactoryMethodInGlobalPool(ArgSel,
1513 SelExp->getSourceRange());
1514 if (SelMethod) {
1515 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1516 switch (SelFamily) {
1517 case OMF_alloc:
1518 case OMF_copy:
1519 case OMF_mutableCopy:
1520 case OMF_new:
1521 case OMF_self:
1522 case OMF_init:
1523 // Issue error, unless ns_returns_not_retained.
1524 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
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 default:
1532 // +0 call. OK. unless ns_returns_retained.
1533 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1534 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001535 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001536 diag::err_arc_perform_selector_retains);
1537 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1538 }
1539 break;
1540 }
1541 }
1542 } else {
1543 // error (may leak).
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001544 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001545 Diag(Args[0]->getExprLoc(), diag::note_used_here);
1546 }
1547 }
1548 break;
John McCallf85e1932011-06-15 23:02:42 +00001549 }
1550 }
1551
Douglas Gregor2725ca82010-04-21 19:57:20 +00001552 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001553 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001554 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001555 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001556 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001557 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001558 makeArrayRef(Args, NumArgs), RBracLoc,
1559 isImplicit);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001560 else
John McCallf89e55a2010-11-18 06:31:45 +00001561 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001562 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001563 makeArrayRef(Args, NumArgs), RBracLoc,
1564 isImplicit);
John McCallf85e1932011-06-15 23:02:42 +00001565
1566 if (getLangOptions().ObjCAutoRefCount) {
1567 // In ARC, annotate delegate init calls.
1568 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00001569 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00001570 // Only consider init calls *directly* in init implementations,
1571 // not within blocks.
1572 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1573 if (method && method->getMethodFamily() == OMF_init) {
1574 // The implicit assignment to self means we also don't want to
1575 // consume the result.
1576 Result->setDelegateInitCall(true);
1577 return Owned(Result);
1578 }
1579 }
1580
1581 // In ARC, check for message sends which are likely to introduce
1582 // retain cycles.
1583 checkRetainCycles(Result);
1584 }
1585
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001586 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001587}
1588
1589// ActOnInstanceMessage - used for both unary and keyword messages.
1590// ArgExprs is optional - if it is present, the number of expressions
1591// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001592ExprResult Sema::ActOnInstanceMessage(Scope *S,
1593 Expr *Receiver,
1594 Selector Sel,
1595 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001596 ArrayRef<SourceLocation> SelectorLocs,
John McCall60d7b3a2010-08-24 06:29:42 +00001597 SourceLocation RBracLoc,
1598 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001599 if (!Receiver)
1600 return ExprError();
1601
John McCall9ae2f072010-08-23 23:25:46 +00001602 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001603 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001604 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001605}
Chris Lattnereca7be62008-04-07 05:30:13 +00001606
John McCallf85e1932011-06-15 23:02:42 +00001607enum ARCConversionTypeClass {
John McCall2cf031d2011-10-01 01:01:08 +00001608 /// int, void, struct A
John McCallf85e1932011-06-15 23:02:42 +00001609 ACTC_none,
John McCall2cf031d2011-10-01 01:01:08 +00001610
1611 /// id, void (^)()
John McCallf85e1932011-06-15 23:02:42 +00001612 ACTC_retainable,
John McCall2cf031d2011-10-01 01:01:08 +00001613
1614 /// id*, id***, void (^*)(),
1615 ACTC_indirectRetainable,
1616
1617 /// void* might be a normal C type, or it might a CF type.
1618 ACTC_voidPtr,
1619
1620 /// struct A*
1621 ACTC_coreFoundation
John McCallf85e1932011-06-15 23:02:42 +00001622};
John McCall2cf031d2011-10-01 01:01:08 +00001623static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
1624 return (ACTC == ACTC_retainable ||
1625 ACTC == ACTC_coreFoundation ||
1626 ACTC == ACTC_voidPtr);
1627}
1628static bool isAnyCLike(ARCConversionTypeClass ACTC) {
1629 return ACTC == ACTC_none ||
1630 ACTC == ACTC_voidPtr ||
1631 ACTC == ACTC_coreFoundation;
1632}
1633
John McCallf85e1932011-06-15 23:02:42 +00001634static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCall2cf031d2011-10-01 01:01:08 +00001635 bool isIndirect = false;
John McCallf85e1932011-06-15 23:02:42 +00001636
1637 // Ignore an outermost reference type.
John McCall2cf031d2011-10-01 01:01:08 +00001638 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCallf85e1932011-06-15 23:02:42 +00001639 type = ref->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00001640 isIndirect = true;
1641 }
John McCallf85e1932011-06-15 23:02:42 +00001642
1643 // Drill through pointers and arrays recursively.
1644 while (true) {
1645 if (const PointerType *ptr = type->getAs<PointerType>()) {
1646 type = ptr->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00001647
1648 // The first level of pointer may be the innermost pointer on a CF type.
1649 if (!isIndirect) {
1650 if (type->isVoidType()) return ACTC_voidPtr;
1651 if (type->isRecordType()) return ACTC_coreFoundation;
1652 }
John McCallf85e1932011-06-15 23:02:42 +00001653 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1654 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1655 } else {
1656 break;
1657 }
John McCall2cf031d2011-10-01 01:01:08 +00001658 isIndirect = true;
John McCallf85e1932011-06-15 23:02:42 +00001659 }
1660
John McCall2cf031d2011-10-01 01:01:08 +00001661 if (isIndirect) {
1662 if (type->isObjCARCBridgableType())
1663 return ACTC_indirectRetainable;
1664 return ACTC_none;
1665 }
1666
1667 if (type->isObjCARCBridgableType())
1668 return ACTC_retainable;
1669
1670 return ACTC_none;
John McCallf85e1932011-06-15 23:02:42 +00001671}
1672
1673namespace {
John McCall2cf031d2011-10-01 01:01:08 +00001674 /// A result from the cast checker.
1675 enum ACCResult {
1676 /// Cannot be casted.
1677 ACC_invalid,
1678
1679 /// Can be safely retained or not retained.
1680 ACC_bottom,
1681
1682 /// Can be casted at +0.
1683 ACC_plusZero,
1684
1685 /// Can be casted at +1.
1686 ACC_plusOne
1687 };
1688 ACCResult merge(ACCResult left, ACCResult right) {
1689 if (left == right) return left;
1690 if (left == ACC_bottom) return right;
1691 if (right == ACC_bottom) return left;
1692 return ACC_invalid;
1693 }
1694
1695 /// A checker which white-lists certain expressions whose conversion
1696 /// to or from retainable type would otherwise be forbidden in ARC.
1697 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
1698 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
1699
John McCallf85e1932011-06-15 23:02:42 +00001700 ASTContext &Context;
John McCall2cf031d2011-10-01 01:01:08 +00001701 ARCConversionTypeClass SourceClass;
1702 ARCConversionTypeClass TargetClass;
1703
1704 static bool isCFType(QualType type) {
1705 // Someday this can use ns_bridged. For now, it has to do this.
1706 return type->isCARCBridgableType();
John McCallf85e1932011-06-15 23:02:42 +00001707 }
John McCall2cf031d2011-10-01 01:01:08 +00001708
1709 public:
1710 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
1711 ARCConversionTypeClass target)
1712 : Context(Context), SourceClass(source), TargetClass(target) {}
1713
1714 using super::Visit;
1715 ACCResult Visit(Expr *e) {
1716 return super::Visit(e->IgnoreParens());
1717 }
1718
1719 ACCResult VisitStmt(Stmt *s) {
1720 return ACC_invalid;
1721 }
1722
1723 /// Null pointer constants can be casted however you please.
1724 ACCResult VisitExpr(Expr *e) {
1725 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1726 return ACC_bottom;
1727 return ACC_invalid;
1728 }
1729
1730 /// Objective-C string literals can be safely casted.
1731 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
1732 // If we're casting to any retainable type, go ahead. Global
1733 // strings are immune to retains, so this is bottom.
1734 if (isAnyRetainable(TargetClass)) return ACC_bottom;
1735
1736 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00001737 }
1738
John McCall2cf031d2011-10-01 01:01:08 +00001739 /// Look through certain implicit and explicit casts.
1740 ACCResult VisitCastExpr(CastExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00001741 switch (e->getCastKind()) {
1742 case CK_NullToPointer:
John McCall2cf031d2011-10-01 01:01:08 +00001743 return ACC_bottom;
1744
John McCallf85e1932011-06-15 23:02:42 +00001745 case CK_NoOp:
1746 case CK_LValueToRValue:
1747 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00001748 case CK_CPointerToObjCPointerCast:
1749 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00001750 case CK_AnyPointerToBlockPointerCast:
1751 return Visit(e->getSubExpr());
John McCall2cf031d2011-10-01 01:01:08 +00001752
John McCallf85e1932011-06-15 23:02:42 +00001753 default:
John McCall2cf031d2011-10-01 01:01:08 +00001754 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00001755 }
1756 }
John McCall2cf031d2011-10-01 01:01:08 +00001757
1758 /// Look through unary extension.
1759 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00001760 return Visit(e->getSubExpr());
1761 }
John McCall2cf031d2011-10-01 01:01:08 +00001762
1763 /// Ignore the LHS of a comma operator.
1764 ACCResult VisitBinComma(BinaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00001765 return Visit(e->getRHS());
1766 }
John McCall2cf031d2011-10-01 01:01:08 +00001767
1768 /// Conditional operators are okay if both sides are okay.
1769 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
1770 ACCResult left = Visit(e->getTrueExpr());
1771 if (left == ACC_invalid) return ACC_invalid;
1772 return merge(left, Visit(e->getFalseExpr()));
John McCallf85e1932011-06-15 23:02:42 +00001773 }
John McCall2cf031d2011-10-01 01:01:08 +00001774
John McCall4b9c2d22011-11-06 09:01:30 +00001775 /// Look through pseudo-objects.
1776 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
1777 // If we're getting here, we should always have a result.
1778 return Visit(e->getResultExpr());
1779 }
1780
John McCall2cf031d2011-10-01 01:01:08 +00001781 /// Statement expressions are okay if their result expression is okay.
1782 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00001783 return Visit(e->getSubStmt()->body_back());
1784 }
John McCallf85e1932011-06-15 23:02:42 +00001785
John McCall2cf031d2011-10-01 01:01:08 +00001786 /// Some declaration references are okay.
1787 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
1788 // References to global constants from system headers are okay.
1789 // These are things like 'kCFStringTransformToLatin'. They are
1790 // can also be assumed to be immune to retains.
1791 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
1792 if (isAnyRetainable(TargetClass) &&
1793 isAnyRetainable(SourceClass) &&
1794 var &&
1795 var->getStorageClass() == SC_Extern &&
1796 var->getType().isConstQualified() &&
1797 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
1798 return ACC_bottom;
1799 }
1800
1801 // Nothing else.
1802 return ACC_invalid;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001803 }
John McCall2cf031d2011-10-01 01:01:08 +00001804
1805 /// Some calls are okay.
1806 ACCResult VisitCallExpr(CallExpr *e) {
1807 if (FunctionDecl *fn = e->getDirectCallee())
1808 if (ACCResult result = checkCallToFunction(fn))
1809 return result;
1810
1811 return super::VisitCallExpr(e);
1812 }
1813
1814 ACCResult checkCallToFunction(FunctionDecl *fn) {
1815 // Require a CF*Ref return type.
1816 if (!isCFType(fn->getResultType()))
1817 return ACC_invalid;
1818
1819 if (!isAnyRetainable(TargetClass))
1820 return ACC_invalid;
1821
1822 // Honor an explicit 'not retained' attribute.
1823 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
1824 return ACC_plusZero;
1825
1826 // Honor an explicit 'retained' attribute, except that for
1827 // now we're not going to permit implicit handling of +1 results,
1828 // because it's a bit frightening.
1829 if (fn->hasAttr<CFReturnsRetainedAttr>())
1830 return ACC_invalid; // ACC_plusOne if we start accepting this
1831
1832 // Recognize this specific builtin function, which is used by CFSTR.
1833 unsigned builtinID = fn->getBuiltinID();
1834 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
1835 return ACC_bottom;
1836
1837 // Otherwise, don't do anything implicit with an unaudited function.
1838 if (!fn->hasAttr<CFAuditedTransferAttr>())
1839 return ACC_invalid;
1840
1841 // Otherwise, it's +0 unless it follows the create convention.
1842 if (ento::coreFoundation::followsCreateRule(fn))
1843 return ACC_invalid; // ACC_plusOne if we start accepting this
1844
1845 return ACC_plusZero;
1846 }
1847
1848 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
1849 return checkCallToMethod(e->getMethodDecl());
1850 }
1851
1852 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
1853 ObjCMethodDecl *method;
1854 if (e->isExplicitProperty())
1855 method = e->getExplicitProperty()->getGetterMethodDecl();
1856 else
1857 method = e->getImplicitPropertyGetter();
1858 return checkCallToMethod(method);
1859 }
1860
1861 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
1862 if (!method) return ACC_invalid;
1863
1864 // Check for message sends to functions returning CF types. We
1865 // just obey the Cocoa conventions with these, even though the
1866 // return type is CF.
1867 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
1868 return ACC_invalid;
1869
1870 // If the method is explicitly marked not-retained, it's +0.
1871 if (method->hasAttr<CFReturnsNotRetainedAttr>())
1872 return ACC_plusZero;
1873
1874 // If the method is explicitly marked as returning retained, or its
1875 // selector follows a +1 Cocoa convention, treat it as +1.
1876 if (method->hasAttr<CFReturnsRetainedAttr>())
1877 return ACC_plusOne;
1878
1879 switch (method->getSelector().getMethodFamily()) {
1880 case OMF_alloc:
1881 case OMF_copy:
1882 case OMF_mutableCopy:
1883 case OMF_new:
1884 return ACC_plusOne;
1885
1886 default:
1887 // Otherwise, treat it as +0.
1888 return ACC_plusZero;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001889 }
1890 }
John McCall2cf031d2011-10-01 01:01:08 +00001891 };
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001892}
1893
John McCall5acb0c92011-10-17 18:40:02 +00001894static void
1895diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
1896 QualType castType, ARCConversionTypeClass castACTC,
1897 Expr *castExpr, ARCConversionTypeClass exprACTC,
1898 Sema::CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00001899 SourceLocation loc =
John McCall2cf031d2011-10-01 01:01:08 +00001900 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00001901
John McCall5acb0c92011-10-17 18:40:02 +00001902 if (S.makeUnavailableInSystemHeader(loc,
John McCall2cf031d2011-10-01 01:01:08 +00001903 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCallf85e1932011-06-15 23:02:42 +00001904 return;
John McCall5acb0c92011-10-17 18:40:02 +00001905
1906 QualType castExprType = castExpr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001907
John McCall71c482c2011-06-17 06:50:50 +00001908 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00001909 switch (exprACTC) {
John McCall2cf031d2011-10-01 01:01:08 +00001910 case ACTC_none:
1911 case ACTC_coreFoundation:
1912 case ACTC_voidPtr:
1913 srcKind = (castExprType->isPointerType() ? 1 : 0);
1914 break;
1915 case ACTC_retainable:
1916 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1917 break;
1918 case ACTC_indirectRetainable:
1919 srcKind = 4;
1920 break;
John McCallf85e1932011-06-15 23:02:42 +00001921 }
1922
John McCall5acb0c92011-10-17 18:40:02 +00001923 // Check whether this could be fixed with a bridge cast.
1924 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
1925 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCallf85e1932011-06-15 23:02:42 +00001926
John McCall5acb0c92011-10-17 18:40:02 +00001927 // Bridge from an ARC type to a CF type.
1928 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
1929 S.Diag(loc, diag::err_arc_cast_requires_bridge)
1930 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
1931 << 2 // of C pointer type
1932 << castExprType
1933 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
1934 << castType
1935 << castRange
1936 << castExpr->getSourceRange();
1937
1938 S.Diag(noteLoc, diag::note_arc_bridge)
1939 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1940 FixItHint::CreateInsertion(afterLParen, "__bridge "));
1941 S.Diag(noteLoc, diag::note_arc_bridge_transfer)
1942 << castExprType
1943 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1944 FixItHint::CreateInsertion(afterLParen, "__bridge_transfer "));
1945
1946 return;
1947 }
1948
1949 // Bridge from a CF type to an ARC type.
1950 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
1951 S.Diag(loc, diag::err_arc_cast_requires_bridge)
1952 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
1953 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
1954 << castExprType
1955 << 2 // to C pointer type
1956 << castType
1957 << castRange
1958 << castExpr->getSourceRange();
1959
1960 S.Diag(noteLoc, diag::note_arc_bridge)
1961 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1962 FixItHint::CreateInsertion(afterLParen, "__bridge "));
1963 S.Diag(noteLoc, diag::note_arc_bridge_retained)
1964 << castType
1965 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1966 FixItHint::CreateInsertion(afterLParen, "__bridge_retained "));
1967
1968 return;
John McCallf85e1932011-06-15 23:02:42 +00001969 }
1970
John McCall5acb0c92011-10-17 18:40:02 +00001971 S.Diag(loc, diag::err_arc_mismatched_cast)
1972 << (CCK != Sema::CCK_ImplicitConversion)
1973 << srcKind << castExprType << castType
John McCallf85e1932011-06-15 23:02:42 +00001974 << castRange << castExpr->getSourceRange();
1975}
1976
John McCall5acb0c92011-10-17 18:40:02 +00001977Sema::ARCConversionResult
1978Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
1979 Expr *&castExpr, CheckedConversionKind CCK) {
1980 QualType castExprType = castExpr->getType();
1981
1982 // For the purposes of the classification, we assume reference types
1983 // will bind to temporaries.
1984 QualType effCastType = castType;
1985 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
1986 effCastType = ref->getPointeeType();
1987
1988 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1989 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00001990 if (exprACTC == castACTC) {
1991 // check for viablity and report error if casting an rvalue to a
1992 // life-time qualifier.
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00001993 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00001994 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00001995 (castType != castExprType)) {
1996 const Type *DT = castType.getTypePtr();
1997 QualType QDT = castType;
1998 // We desugar some types but not others. We ignore those
1999 // that cannot happen in a cast; i.e. auto, and those which
2000 // should not be de-sugared; i.e typedef.
2001 if (const ParenType *PT = dyn_cast<ParenType>(DT))
2002 QDT = PT->desugar();
2003 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
2004 QDT = TP->desugar();
2005 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
2006 QDT = AT->desugar();
2007 if (QDT != castType &&
2008 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
2009 SourceLocation loc =
2010 (castRange.isValid() ? castRange.getBegin()
2011 : castExpr->getExprLoc());
2012 Diag(loc, diag::err_arc_nolifetime_behavior);
2013 }
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002014 }
2015 return ACR_okay;
2016 }
2017
John McCall5acb0c92011-10-17 18:40:02 +00002018 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
2019
2020 // Allow all of these types to be cast to integer types (but not
2021 // vice-versa).
2022 if (castACTC == ACTC_none && castType->isIntegralType(Context))
2023 return ACR_okay;
2024
2025 // Allow casts between pointers to lifetime types (e.g., __strong id*)
2026 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
2027 // must be explicit.
2028 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
2029 return ACR_okay;
2030 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
2031 CCK != CCK_ImplicitConversion)
2032 return ACR_okay;
2033
2034 switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
2035 // For invalid casts, fall through.
2036 case ACC_invalid:
2037 break;
2038
2039 // Do nothing for both bottom and +0.
2040 case ACC_bottom:
2041 case ACC_plusZero:
2042 return ACR_okay;
2043
2044 // If the result is +1, consume it here.
2045 case ACC_plusOne:
2046 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
2047 CK_ARCConsumeObject, castExpr,
2048 0, VK_RValue);
2049 ExprNeedsCleanups = true;
2050 return ACR_okay;
2051 }
2052
2053 // If this is a non-implicit cast from id or block type to a
2054 // CoreFoundation type, delay complaining in case the cast is used
2055 // in an acceptable context.
2056 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
2057 CCK != CCK_ImplicitConversion)
2058 return ACR_unbridged;
2059
2060 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2061 castExpr, exprACTC, CCK);
2062 return ACR_okay;
2063}
2064
2065/// Given that we saw an expression with the ARCUnbridgedCastTy
2066/// placeholder type, complain bitterly.
2067void Sema::diagnoseARCUnbridgedCast(Expr *e) {
2068 // We expect the spurious ImplicitCastExpr to already have been stripped.
2069 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2070 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
2071
2072 SourceRange castRange;
2073 QualType castType;
2074 CheckedConversionKind CCK;
2075
2076 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
2077 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
2078 castType = cast->getTypeAsWritten();
2079 CCK = CCK_CStyleCast;
2080 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
2081 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
2082 castType = cast->getTypeAsWritten();
2083 CCK = CCK_OtherCast;
2084 } else {
2085 castType = cast->getType();
2086 CCK = CCK_ImplicitConversion;
2087 }
2088
2089 ARCConversionTypeClass castACTC =
2090 classifyTypeForARCConversion(castType.getNonReferenceType());
2091
2092 Expr *castExpr = realCast->getSubExpr();
2093 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
2094
2095 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2096 castExpr, ACTC_retainable, CCK);
2097}
2098
2099/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
2100/// type, remove the placeholder cast.
2101Expr *Sema::stripARCUnbridgedCast(Expr *e) {
2102 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2103
2104 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
2105 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
2106 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
2107 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
2108 assert(uo->getOpcode() == UO_Extension);
2109 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
2110 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
2111 sub->getValueKind(), sub->getObjectKind(),
2112 uo->getOperatorLoc());
2113 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
2114 assert(!gse->isResultDependent());
2115
2116 unsigned n = gse->getNumAssocs();
2117 SmallVector<Expr*, 4> subExprs(n);
2118 SmallVector<TypeSourceInfo*, 4> subTypes(n);
2119 for (unsigned i = 0; i != n; ++i) {
2120 subTypes[i] = gse->getAssocTypeSourceInfo(i);
2121 Expr *sub = gse->getAssocExpr(i);
2122 if (i == gse->getResultIndex())
2123 sub = stripARCUnbridgedCast(sub);
2124 subExprs[i] = sub;
2125 }
2126
2127 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
2128 gse->getControllingExpr(),
2129 subTypes.data(), subExprs.data(),
2130 n, gse->getDefaultLoc(),
2131 gse->getRParenLoc(),
2132 gse->containsUnexpandedParameterPack(),
2133 gse->getResultIndex());
2134 } else {
2135 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
2136 return cast<ImplicitCastExpr>(e)->getSubExpr();
2137 }
2138}
2139
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00002140bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
2141 QualType exprType) {
2142 QualType canCastType =
2143 Context.getCanonicalType(castType).getUnqualifiedType();
2144 QualType canExprType =
2145 Context.getCanonicalType(exprType).getUnqualifiedType();
2146 if (isa<ObjCObjectPointerType>(canCastType) &&
2147 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
2148 canExprType->isObjCObjectPointerType()) {
2149 if (const ObjCObjectPointerType *ObjT =
2150 canExprType->getAs<ObjCObjectPointerType>())
2151 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
2152 return false;
2153 }
2154 return true;
2155}
2156
John McCall7e5e5f42011-07-07 06:58:02 +00002157/// Look for an ObjCReclaimReturnedObject cast and destroy it.
2158static Expr *maybeUndoReclaimObject(Expr *e) {
2159 // For now, we just undo operands that are *immediately* reclaim
2160 // expressions, which prevents the vast majority of potential
2161 // problems here. To catch them all, we'd need to rebuild arbitrary
2162 // value-propagating subexpressions --- we can't reliably rebuild
2163 // in-place because of expression sharing.
2164 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00002165 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00002166 return ice->getSubExpr();
2167
2168 return e;
2169}
2170
John McCallf85e1932011-06-15 23:02:42 +00002171ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
2172 ObjCBridgeCastKind Kind,
2173 SourceLocation BridgeKeywordLoc,
2174 TypeSourceInfo *TSInfo,
2175 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00002176 ExprResult SubResult = UsualUnaryConversions(SubExpr);
2177 if (SubResult.isInvalid()) return ExprError();
2178 SubExpr = SubResult.take();
2179
John McCallf85e1932011-06-15 23:02:42 +00002180 QualType T = TSInfo->getType();
2181 QualType FromType = SubExpr->getType();
2182
John McCall1d9b3b22011-09-09 05:25:32 +00002183 CastKind CK;
2184
John McCallf85e1932011-06-15 23:02:42 +00002185 bool MustConsume = false;
2186 if (T->isDependentType() || SubExpr->isTypeDependent()) {
2187 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00002188 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00002189 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
2190 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00002191 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
2192 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00002193 switch (Kind) {
2194 case OBC_Bridge:
2195 break;
2196
2197 case OBC_BridgeRetained:
2198 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2199 << 2
2200 << FromType
2201 << (T->isBlockPointerType()? 1 : 0)
2202 << T
2203 << SubExpr->getSourceRange()
2204 << Kind;
2205 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2206 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
2207 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
2208 << FromType
2209 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2210 "__bridge_transfer ");
2211
2212 Kind = OBC_Bridge;
2213 break;
2214
2215 case OBC_BridgeTransfer:
2216 // We must consume the Objective-C object produced by the cast.
2217 MustConsume = true;
2218 break;
2219 }
2220 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
2221 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00002222 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00002223 switch (Kind) {
2224 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00002225 // Reclaiming a value that's going to be __bridge-casted to CF
2226 // is very dangerous, so we don't do it.
2227 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00002228 break;
2229
2230 case OBC_BridgeRetained:
2231 // Produce the object before casting it.
2232 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00002233 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00002234 SubExpr, 0, VK_RValue);
2235 break;
2236
2237 case OBC_BridgeTransfer:
2238 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2239 << (FromType->isBlockPointerType()? 1 : 0)
2240 << FromType
2241 << 2
2242 << T
2243 << SubExpr->getSourceRange()
2244 << Kind;
2245
2246 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2247 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
2248 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
2249 << T
2250 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
2251
2252 Kind = OBC_Bridge;
2253 break;
2254 }
2255 } else {
2256 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
2257 << FromType << T << Kind
2258 << SubExpr->getSourceRange()
2259 << TSInfo->getTypeLoc().getSourceRange();
2260 return ExprError();
2261 }
2262
John McCall1d9b3b22011-09-09 05:25:32 +00002263 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00002264 BridgeKeywordLoc,
2265 TSInfo, SubExpr);
2266
2267 if (MustConsume) {
2268 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00002269 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00002270 0, VK_RValue);
2271 }
2272
2273 return Result;
2274}
2275
2276ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
2277 SourceLocation LParenLoc,
2278 ObjCBridgeCastKind Kind,
2279 SourceLocation BridgeKeywordLoc,
2280 ParsedType Type,
2281 SourceLocation RParenLoc,
2282 Expr *SubExpr) {
2283 TypeSourceInfo *TSInfo = 0;
2284 QualType T = GetTypeFromParser(Type, &TSInfo);
2285 if (!TSInfo)
2286 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
2287 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
2288 SubExpr);
2289}