blob: 7e2180fe0efe45e76361790b6cb7b4173c700e60 [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]);
Douglas Gregor93962e52012-02-01 01:18:43 +0000268 blockScope->AddCapture(self, /*byref*/ false, nested, self->getLocation(),
269 /*copy*/ 0);
John McCall6b5a61b2011-02-07 10:33:21 +0000270 captureIndex = blockScope->Captures.size(); // +1
271 }
John McCall26743b22011-02-03 09:00:02 +0000272
273 return method;
274}
275
Douglas Gregor5c16d632011-09-09 20:05:21 +0000276static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
277 if (T == Context.getObjCInstanceType())
278 return Context.getObjCIdType();
279
280 return T;
281}
282
Douglas Gregor926df6c2011-06-11 01:09:30 +0000283QualType Sema::getMessageSendResultType(QualType ReceiverType,
284 ObjCMethodDecl *Method,
285 bool isClassMessage, bool isSuperMessage) {
286 assert(Method && "Must have a method");
287 if (!Method->hasRelatedResultType())
288 return Method->getSendResultType();
289
290 // If a method has a related return type:
291 // - if the method found is an instance method, but the message send
292 // was a class message send, T is the declared return type of the method
293 // found
294 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor5c16d632011-09-09 20:05:21 +0000295 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000296
297 // - if the receiver is super, T is a pointer to the class of the
298 // enclosing method definition
299 if (isSuperMessage) {
300 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
301 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
302 return Context.getObjCObjectPointerType(
303 Context.getObjCInterfaceType(Class));
304 }
305
306 // - if the receiver is the name of a class U, T is a pointer to U
307 if (ReceiverType->getAs<ObjCInterfaceType>() ||
308 ReceiverType->isObjCQualifiedInterfaceType())
309 return Context.getObjCObjectPointerType(ReceiverType);
310 // - if the receiver is of type Class or qualified Class type,
311 // T is the declared return type of the method.
312 if (ReceiverType->isObjCClassType() ||
313 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor5c16d632011-09-09 20:05:21 +0000314 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000315
316 // - if the receiver is id, qualified id, Class, or qualified Class, T
317 // is the receiver type, otherwise
318 // - T is the type of the receiver expression.
319 return ReceiverType;
320}
John McCall26743b22011-02-03 09:00:02 +0000321
Douglas Gregor926df6c2011-06-11 01:09:30 +0000322void Sema::EmitRelatedResultTypeNote(const Expr *E) {
323 E = E->IgnoreParenImpCasts();
324 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
325 if (!MsgSend)
326 return;
327
328 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
329 if (!Method)
330 return;
331
332 if (!Method->hasRelatedResultType())
333 return;
334
335 if (Context.hasSameUnqualifiedType(Method->getResultType()
336 .getNonReferenceType(),
337 MsgSend->getType()))
338 return;
339
Douglas Gregore97179c2011-09-08 01:46:34 +0000340 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
341 Context.getObjCInstanceType()))
342 return;
343
Douglas Gregor926df6c2011-06-11 01:09:30 +0000344 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
345 << Method->isInstanceMethod() << Method->getSelector()
346 << MsgSend->getType();
347}
348
349bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
350 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000351 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000352 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000353 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000354 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000355 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000356 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000357 for (unsigned i = 0; i != NumArgs; i++) {
358 if (Args[i]->isTypeDependent())
359 continue;
360
John Wiegley429bb272011-04-08 18:41:53 +0000361 ExprResult Result = DefaultArgumentPromotion(Args[i]);
362 if (Result.isInvalid())
363 return true;
364 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000365 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000366
John McCallf85e1932011-06-15 23:02:42 +0000367 unsigned DiagID;
368 if (getLangOptions().ObjCAutoRefCount)
369 DiagID = diag::err_arc_method_not_found;
370 else
371 DiagID = isClassMessage ? diag::warn_class_method_not_found
372 : diag::warn_inst_method_not_found;
John McCall819e7452011-08-31 20:57:36 +0000373 if (!getLangOptions().DebuggerSupport)
374 Diag(lbrac, DiagID)
375 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +0000376
377 // In debuggers, we want to use __unknown_anytype for these
378 // results so that clients can cast them.
379 if (getLangOptions().DebuggerSupport) {
380 ReturnType = Context.UnknownAnyTy;
381 } else {
382 ReturnType = Context.getObjCIdType();
383 }
John McCallf89e55a2010-11-18 06:31:45 +0000384 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000385 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000386 }
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Douglas Gregor926df6c2011-06-11 01:09:30 +0000388 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
389 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000390 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000391
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000392 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000393 // Method might have more arguments than selector indicates. This is due
394 // to addition of c-style arguments in method.
395 if (Method->param_size() > Sel.getNumArgs())
396 NumNamedArgs = Method->param_size();
397 // FIXME. This need be cleaned up.
398 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000399 Diag(lbrac, diag::err_typecheck_call_too_few_args)
400 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000401 return false;
402 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000403
Chris Lattner312531a2009-04-12 08:11:20 +0000404 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000405 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000406 // We can't do any type-checking on a type-dependent argument.
407 if (Args[i]->isTypeDependent())
408 continue;
409
Chris Lattner85a932e2008-01-04 22:32:30 +0000410 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000411
John McCall5acb0c92011-10-17 18:40:02 +0000412 ParmVarDecl *param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000413 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000414
John McCall5acb0c92011-10-17 18:40:02 +0000415 // Strip the unbridged-cast placeholder expression off unless it's
416 // a consumed argument.
417 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
418 !param->hasAttr<CFConsumedAttr>())
419 argExpr = stripARCUnbridgedCast(argExpr);
420
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000421 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
John McCall5acb0c92011-10-17 18:40:02 +0000422 param->getType(),
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000423 PDiag(diag::err_call_incomplete_argument)
424 << argExpr->getSourceRange()))
425 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000426
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000427 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
John McCall5acb0c92011-10-17 18:40:02 +0000428 param);
John McCall3fa5cae2010-10-26 07:05:15 +0000429 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000430 if (ArgE.isInvalid())
431 IsError = true;
432 else
433 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000434 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000435
436 // Promote additional arguments to variadic methods.
437 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000438 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
439 if (Args[i]->isTypeDependent())
440 continue;
441
John Wiegley429bb272011-04-08 18:41:53 +0000442 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
443 IsError |= Arg.isInvalid();
444 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000445 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000446 } else {
447 // Check for extra arguments to non-variadic methods.
448 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000449 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000450 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000451 << 2 /*method*/ << NumNamedArgs << NumArgs
452 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000453 << SourceRange(Args[NumNamedArgs]->getLocStart(),
454 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000455 }
456 }
457
Douglas Gregor2725ca82010-04-21 19:57:20 +0000458 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Jean-Daniel Dupas29c3f812012-01-17 20:03:31 +0000459
460 // Do additional checkings on method.
461 IsError |= CheckObjCMethodCall(Method, lbrac, Args, NumArgs);
462
Chris Lattner312531a2009-04-12 08:11:20 +0000463 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000464}
465
Douglas Gregorc737acb2011-09-27 16:10:05 +0000466bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000467 // 'self' is objc 'self' in an objc method only.
John McCall4b9c2d22011-11-06 09:01:30 +0000468 ObjCMethodDecl *method =
469 dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
470 if (!method) return false;
471
John McCallf85e1932011-06-15 23:02:42 +0000472 receiver = receiver->IgnoreParenLValueCasts();
473 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCall4b9c2d22011-11-06 09:01:30 +0000474 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregorc737acb2011-09-27 16:10:05 +0000475 return true;
476 return false;
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000477}
478
Steve Narofff1afaf62009-02-26 15:55:06 +0000479// Helper method for ActOnClassMethod/ActOnInstanceMethod.
480// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000481// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000482// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000483ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000484 ObjCInterfaceDecl *ClassDecl) {
485 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000486 // lookup in class and all superclasses
487 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000488 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000489 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000490
Steve Naroff5609ec02009-03-08 18:56:13 +0000491 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000492 if (!Method)
493 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Steve Naroff5609ec02009-03-08 18:56:13 +0000495 // Before we give up, check if the selector is an instance method.
496 // But only in the root. This matches gcc's behaviour and what the
497 // runtime expects.
498 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000499 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000500 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000501 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000502 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000503 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
504 }
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Steve Naroff5609ec02009-03-08 18:56:13 +0000506 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000507 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000508 return Method;
509}
510
511ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
512 ObjCInterfaceDecl *ClassDecl) {
Douglas Gregor2e5c15b2011-12-15 05:27:12 +0000513 if (!ClassDecl->hasDefinition())
514 return 0;
515
Steve Naroff5609ec02009-03-08 18:56:13 +0000516 ObjCMethodDecl *Method = 0;
517 while (ClassDecl && !Method) {
518 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000519 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000520 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Steve Naroff5609ec02009-03-08 18:56:13 +0000522 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000523 if (!Method)
524 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000525 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000526 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000527 return Method;
528}
529
John McCall3c3b7f92011-10-25 17:37:35 +0000530/// LookupMethodInType - Look up a method in an ObjCObjectType.
531ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
532 bool isInstance) {
533 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
534 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
535 // Look it up in the main interface (and categories, etc.)
536 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
537 return method;
538
539 // Okay, look for "private" methods declared in any
540 // @implementations we've seen.
541 if (isInstance) {
542 if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
543 return method;
544 } else {
545 if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
546 return method;
547 }
548 }
549
550 // Check qualifiers.
551 for (ObjCObjectType::qual_iterator
552 i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
553 if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
554 return method;
555
556 return 0;
557}
558
Fariborz Jahanian61478062011-03-09 20:18:06 +0000559/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
560/// list of a qualified objective pointer type.
561ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
562 const ObjCObjectPointerType *OPT,
563 bool Instance)
564{
565 ObjCMethodDecl *MD = 0;
566 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
567 E = OPT->qual_end(); I != E; ++I) {
568 ObjCProtocolDecl *PROTO = (*I);
569 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
570 return MD;
571 }
572 }
573 return 0;
574}
575
Chris Lattner7f816522010-04-11 07:45:24 +0000576/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
577/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000578ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000579HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000580 Expr *BaseExpr, SourceLocation OpLoc,
581 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000582 SourceLocation MemberLoc,
583 SourceLocation SuperLoc, QualType SuperType,
584 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000585 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
586 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000587
588 if (MemberName.getNameKind() != DeclarationName::Identifier) {
589 Diag(MemberLoc, diag::err_invalid_property_name)
590 << MemberName << QualType(OPT, 0);
591 return ExprError();
592 }
593
Chris Lattner7f816522010-04-11 07:45:24 +0000594 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregorb3029962011-11-14 22:10:01 +0000595 SourceRange BaseRange = Super? SourceRange(SuperLoc)
596 : BaseExpr->getSourceRange();
597 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
598 PDiag(diag::err_property_not_found_forward_class)
599 << MemberName << BaseRange))
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000600 return ExprError();
Douglas Gregorb3029962011-11-14 22:10:01 +0000601
Chris Lattner7f816522010-04-11 07:45:24 +0000602 // Search for a declared property first.
603 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
604 // Check whether we can reference this property.
605 if (DiagnoseUseOfDecl(PD, MemberLoc))
606 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000607
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000608 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +0000609 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000610 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000611 MemberLoc,
612 SuperLoc, SuperType));
613 else
John McCall3c3b7f92011-10-25 17:37:35 +0000614 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000615 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000616 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000617 }
618 // Check protocols on qualified interfaces.
619 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
620 E = OPT->qual_end(); I != E; ++I)
621 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
622 // Check whether we can reference this property.
623 if (DiagnoseUseOfDecl(PD, MemberLoc))
624 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000625
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000626 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +0000627 return Owned(new (Context) ObjCPropertyRefExpr(PD,
628 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000629 VK_LValue,
630 OK_ObjCProperty,
631 MemberLoc,
632 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000633 else
John McCall3c3b7f92011-10-25 17:37:35 +0000634 return Owned(new (Context) ObjCPropertyRefExpr(PD,
635 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000636 VK_LValue,
637 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000638 MemberLoc,
639 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000640 }
641 // If that failed, look for an "implicit" property by seeing if the nullary
642 // selector is implemented.
643
644 // FIXME: The logic for looking up nullary and unary selectors should be
645 // shared with the code in ActOnInstanceMessage.
646
647 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
648 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000649
650 // May be founf in property's qualified list.
651 if (!Getter)
652 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000653
654 // If this reference is in an @implementation, check for 'private' methods.
655 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000656 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000657
658 // Look through local category implementations associated with the class.
659 if (!Getter)
660 Getter = IFace->getCategoryInstanceMethod(Sel);
661 if (Getter) {
662 // Check if we can reference this property.
663 if (DiagnoseUseOfDecl(Getter, MemberLoc))
664 return ExprError();
665 }
666 // If we found a getter then this may be a valid dot-reference, we
667 // will look for the matching setter, in case it is needed.
668 Selector SetterSel =
669 SelectorTable::constructSetterName(PP.getIdentifierTable(),
670 PP.getSelectorTable(), Member);
671 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000672
673 // May be founf in property's qualified list.
674 if (!Setter)
675 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
676
Chris Lattner7f816522010-04-11 07:45:24 +0000677 if (!Setter) {
678 // If this reference is in an @implementation, also check for 'private'
679 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000680 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000681 }
682 // Look through local category implementations associated with the class.
683 if (!Setter)
684 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000685
Chris Lattner7f816522010-04-11 07:45:24 +0000686 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
687 return ExprError();
688
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000689 if (Getter || Setter) {
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000690 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000691 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +0000692 Context.PseudoObjectTy,
693 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +0000694 MemberLoc,
695 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000696 else
John McCall12f78a62010-12-02 01:19:52 +0000697 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +0000698 Context.PseudoObjectTy,
699 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +0000700 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000701
Chris Lattner7f816522010-04-11 07:45:24 +0000702 }
703
704 // Attempt to correct for typos in property names.
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000705 DeclFilterCCC<ObjCPropertyDecl> Validator;
706 if (TypoCorrection Corrected = CorrectTypo(
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000707 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000708 NULL, Validator, IFace, false, OPT)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000709 ObjCPropertyDecl *Property =
710 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>();
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000711 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
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000850namespace {
851
852class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback {
853 public:
854 ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) {
855 // Determine whether "super" is acceptable in the current context.
856 if (Method && Method->getClassInterface())
857 WantObjCSuper = Method->getClassInterface()->getSuperClass();
858 }
859
860 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
861 return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() ||
862 candidate.isKeyword("super");
863 }
864};
865
866}
867
Douglas Gregor47bd5432010-04-14 02:46:37 +0000868Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000869 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000870 SourceLocation NameLoc,
871 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000872 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000873 ParsedType &ReceiverType) {
874 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000875
Douglas Gregor47bd5432010-04-14 02:46:37 +0000876 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000877 // messaging super. If the identifier is "super" and there is a
878 // trailing dot, it's an instance message.
879 if (IsSuper && S->isInObjcMethodScope())
880 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000881
882 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
883 LookupName(Result, S);
884
885 switch (Result.getResultKind()) {
886 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000887 // Normal name lookup didn't find anything. If we're in an
888 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000889 // FIXME: This is a hack. Ivar lookup should be part of normal
890 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000891 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidisccc9e762011-11-09 00:22:48 +0000892 if (!Method->getClassInterface()) {
893 // Fall back: let the parser try to parse it as an instance message.
894 return ObjCInstanceMessage;
895 }
896
Douglas Gregored464422010-04-19 20:09:36 +0000897 ObjCInterfaceDecl *ClassDeclared;
898 if (Method->getClassInterface()->lookupInstanceVariable(Name,
899 ClassDeclared))
900 return ObjCInstanceMessage;
901 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000902
Douglas Gregor47bd5432010-04-14 02:46:37 +0000903 // Break out; we'll perform typo correction below.
904 break;
905
906 case LookupResult::NotFoundInCurrentInstantiation:
907 case LookupResult::FoundOverloaded:
908 case LookupResult::FoundUnresolvedValue:
909 case LookupResult::Ambiguous:
910 Result.suppressDiagnostics();
911 return ObjCInstanceMessage;
912
913 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000914 // If the identifier is a class or not, and there is a trailing dot,
915 // it's an instance message.
916 if (HasTrailingDot)
917 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000918 // We found something. If it's a type, then we have a class
919 // message. Otherwise, it's an instance message.
920 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000921 QualType T;
922 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
923 T = Context.getObjCInterfaceType(Class);
924 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
925 T = Context.getTypeDeclType(Type);
926 else
927 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000928
Douglas Gregor1569f952010-04-21 20:38:13 +0000929 // We have a class message, and T is the type we're
930 // messaging. Build source-location information for it.
931 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000932 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000933 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000934 }
935 }
936
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000937 ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl());
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000938 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
939 Result.getLookupKind(), S, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000940 Validator)) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000941 if (Corrected.isKeyword()) {
942 // If we've found the keyword "super" (the only keyword that would be
943 // returned by CorrectTypo), this is a send to super.
Douglas Gregoraaf87162010-04-14 20:04:41 +0000944 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000945 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000946 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000947 return ObjCSuperMessage;
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000948 } else if (ObjCInterfaceDecl *Class =
949 Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
950 // If we found a declaration, correct when it refers to an Objective-C
951 // class.
952 Diag(NameLoc, diag::err_unknown_receiver_suggest)
953 << Name << Corrected.getCorrection()
954 << FixItHint::CreateReplacement(SourceRange(NameLoc),
955 Class->getNameAsString());
956 Diag(Class->getLocation(), diag::note_previous_decl)
957 << Corrected.getCorrection();
958
959 QualType T = Context.getObjCInterfaceType(Class);
960 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
961 ReceiverType = CreateParsedType(T, TSInfo);
962 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000963 }
964 }
965
966 // Fall back: let the parser try to parse it as an instance message.
967 return ObjCInstanceMessage;
968}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000969
John McCall60d7b3a2010-08-24 06:29:42 +0000970ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000971 SourceLocation SuperLoc,
972 Selector Sel,
973 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +0000974 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000975 SourceLocation RBracLoc,
976 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000977 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000978 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000979 if (!Method) {
980 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
981 return ExprError();
982 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000983
Douglas Gregorf95861a2010-04-21 20:01:04 +0000984 ObjCInterfaceDecl *Class = Method->getClassInterface();
985 if (!Class) {
986 Diag(SuperLoc, diag::error_no_super_class_message)
987 << Method->getDeclName();
988 return ExprError();
989 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000990
Douglas Gregorf95861a2010-04-21 20:01:04 +0000991 ObjCInterfaceDecl *Super = Class->getSuperClass();
992 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000993 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000994 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
995 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000996 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000997 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000998
Douglas Gregorf95861a2010-04-21 20:01:04 +0000999 // We are in a method whose class has a superclass, so 'super'
1000 // is acting as a keyword.
1001 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +00001002 if (Sel.getMethodFamily() == OMF_dealloc)
1003 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +00001004 if (Sel.getMethodFamily() == OMF_finalize)
1005 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +00001006
Douglas Gregorf95861a2010-04-21 20:01:04 +00001007 // Since we are in an instance method, this is an instance
1008 // message to the superclass instance.
1009 QualType SuperTy = Context.getObjCInterfaceType(Super);
1010 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +00001011 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001012 Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001013 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001014 }
Douglas Gregorf95861a2010-04-21 20:01:04 +00001015
1016 // Since we are in a class method, this is a class message to
1017 // the superclass.
1018 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1019 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001020 SuperLoc, Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001021 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001022}
1023
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001024
1025ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType,
1026 bool isSuperReceiver,
1027 SourceLocation Loc,
1028 Selector Sel,
1029 ObjCMethodDecl *Method,
1030 MultiExprArg Args) {
1031 TypeSourceInfo *receiverTypeInfo = 0;
1032 if (!ReceiverType.isNull())
1033 receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType);
1034
1035 return BuildClassMessage(receiverTypeInfo, ReceiverType,
1036 /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(),
1037 Sel, Method, Loc, Loc, Loc, Args,
1038 /*isImplicit=*/true);
1039
1040}
1041
Douglas Gregor2725ca82010-04-21 19:57:20 +00001042/// \brief Build an Objective-C class message expression.
1043///
1044/// This routine takes care of both normal class messages and
1045/// class messages to the superclass.
1046///
1047/// \param ReceiverTypeInfo Type source information that describes the
1048/// receiver of this message. This may be NULL, in which case we are
1049/// sending to the superclass and \p SuperLoc must be a valid source
1050/// location.
1051
1052/// \param ReceiverType The type of the object receiving the
1053/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1054/// type as that refers to. For a superclass send, this is the type of
1055/// the superclass.
1056///
1057/// \param SuperLoc The location of the "super" keyword in a
1058/// superclass message.
1059///
1060/// \param Sel The selector to which the message is being sent.
1061///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001062/// \param Method The method that this class message is invoking, if
1063/// already known.
1064///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001065/// \param LBracLoc The location of the opening square bracket ']'.
1066///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001067/// \param RBrac The location of the closing square bracket ']'.
1068///
1069/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001070ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001071 QualType ReceiverType,
1072 SourceLocation SuperLoc,
1073 Selector Sel,
1074 ObjCMethodDecl *Method,
1075 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001076 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001077 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001078 MultiExprArg ArgsIn,
1079 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001080 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001081 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001082 if (LBracLoc.isInvalid()) {
1083 Diag(Loc, diag::err_missing_open_square_message_send)
1084 << FixItHint::CreateInsertion(Loc, "[");
1085 LBracLoc = Loc;
1086 }
1087
Douglas Gregor92e986e2010-04-22 16:44:27 +00001088 if (ReceiverType->isDependentType()) {
1089 // If the receiver type is dependent, we can't type-check anything
1090 // at this point. Build a dependent expression.
1091 unsigned NumArgs = ArgsIn.size();
1092 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1093 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001094 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1095 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001096 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001097 makeArrayRef(Args, NumArgs),RBracLoc,
1098 isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001099 }
Chris Lattner15faee12010-04-12 05:38:43 +00001100
Douglas Gregor2725ca82010-04-21 19:57:20 +00001101 // Find the class to which we are sending this message.
1102 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001103 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1104 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001105 Diag(Loc, diag::err_invalid_receiver_class_message)
1106 << ReceiverType;
1107 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001108 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001109 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001110 // objc++ diagnoses during typename annotation.
1111 if (!getLangOptions().CPlusPlus)
1112 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001113 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001114 if (!Method) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001115 SourceRange TypeRange
1116 = SuperLoc.isValid()? SourceRange(SuperLoc)
1117 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
1118 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
1119 (getLangOptions().ObjCAutoRefCount
1120 ? PDiag(diag::err_arc_receiver_forward_class)
1121 : PDiag(diag::warn_receiver_forward_class))
1122 << TypeRange)) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001123 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001124 Method = LookupFactoryMethodInGlobalPool(Sel,
1125 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001126 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001127 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1128 << Method->getDeclName();
1129 }
1130 if (!Method)
1131 Method = Class->lookupClassMethod(Sel);
1132
1133 // If we have an implementation in scope, check "private" methods.
1134 if (!Method)
1135 Method = LookupPrivateClassMethod(Sel, Class);
1136
1137 if (Method && DiagnoseUseOfDecl(Method, Loc))
1138 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001139 }
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Douglas Gregor2725ca82010-04-21 19:57:20 +00001141 // Check the argument types and determine the result type.
1142 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001143 ExprValueKind VK = VK_RValue;
1144
Douglas Gregor2725ca82010-04-21 19:57:20 +00001145 unsigned NumArgs = ArgsIn.size();
1146 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001147 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1148 SuperLoc.isValid(), LBracLoc, RBracLoc,
1149 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001150 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001151
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001152 if (Method && !Method->getResultType()->isVoidType() &&
1153 RequireCompleteType(LBracLoc, Method->getResultType(),
1154 diag::err_illegal_message_expr_incomplete_type))
1155 return ExprError();
1156
Douglas Gregor2725ca82010-04-21 19:57:20 +00001157 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001158 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001159 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001160 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001161 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001162 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001163 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001164 RBracLoc, isImplicit);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001165 else
John McCallf89e55a2010-11-18 06:31:45 +00001166 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001167 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001168 Method, makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001169 RBracLoc, isImplicit);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001170 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001171}
1172
Douglas Gregor2725ca82010-04-21 19:57:20 +00001173// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001174// ArgExprs is optional - if it is present, the number of expressions
1175// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001176ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001177 ParsedType Receiver,
1178 Selector Sel,
1179 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001180 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor77328d12010-09-15 23:19:31 +00001181 SourceLocation RBracLoc,
1182 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001183 TypeSourceInfo *ReceiverTypeInfo;
1184 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1185 if (ReceiverType.isNull())
1186 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001187
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Douglas Gregor2725ca82010-04-21 19:57:20 +00001189 if (!ReceiverTypeInfo)
1190 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1191
1192 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001193 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001194 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001195}
1196
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001197ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver,
1198 QualType ReceiverType,
1199 SourceLocation Loc,
1200 Selector Sel,
1201 ObjCMethodDecl *Method,
1202 MultiExprArg Args) {
1203 return BuildInstanceMessage(Receiver, ReceiverType,
1204 /*SuperLoc=*/!Receiver ? Loc : SourceLocation(),
1205 Sel, Method, Loc, Loc, Loc, Args,
1206 /*isImplicit=*/true);
1207}
1208
Douglas Gregor2725ca82010-04-21 19:57:20 +00001209/// \brief Build an Objective-C instance message expression.
1210///
1211/// This routine takes care of both normal instance messages and
1212/// instance messages to the superclass instance.
1213///
1214/// \param Receiver The expression that computes the object that will
1215/// receive this message. This may be empty, in which case we are
1216/// sending to the superclass instance and \p SuperLoc must be a valid
1217/// source location.
1218///
1219/// \param ReceiverType The (static) type of the object receiving the
1220/// message. When a \p Receiver expression is provided, this is the
1221/// same type as that expression. For a superclass instance send, this
1222/// is a pointer to the type of the superclass.
1223///
1224/// \param SuperLoc The location of the "super" keyword in a
1225/// superclass instance message.
1226///
1227/// \param Sel The selector to which the message is being sent.
1228///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001229/// \param Method The method that this instance message is invoking, if
1230/// already known.
1231///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001232/// \param LBracLoc The location of the opening square bracket ']'.
1233///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001234/// \param RBrac The location of the closing square bracket ']'.
1235///
1236/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001237ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001238 QualType ReceiverType,
1239 SourceLocation SuperLoc,
1240 Selector Sel,
1241 ObjCMethodDecl *Method,
1242 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001243 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001244 SourceLocation RBracLoc,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001245 MultiExprArg ArgsIn,
1246 bool isImplicit) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001247 // The location of the receiver.
1248 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1249
1250 if (LBracLoc.isInvalid()) {
1251 Diag(Loc, diag::err_missing_open_square_message_send)
1252 << FixItHint::CreateInsertion(Loc, "[");
1253 LBracLoc = Loc;
1254 }
1255
Douglas Gregor2725ca82010-04-21 19:57:20 +00001256 // If we have a receiver expression, perform appropriate promotions
1257 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001258 if (Receiver) {
John McCall5acb0c92011-10-17 18:40:02 +00001259 if (Receiver->hasPlaceholderType()) {
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00001260 ExprResult Result;
1261 if (Receiver->getType() == Context.UnknownAnyTy)
1262 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
1263 else
1264 Result = CheckPlaceholderExpr(Receiver);
1265 if (Result.isInvalid()) return ExprError();
1266 Receiver = Result.take();
John McCall5acb0c92011-10-17 18:40:02 +00001267 }
1268
Douglas Gregor92e986e2010-04-22 16:44:27 +00001269 if (Receiver->isTypeDependent()) {
1270 // If the receiver is type-dependent, we can't type-check anything
1271 // at this point. Build a dependent expression.
1272 unsigned NumArgs = ArgsIn.size();
1273 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1274 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1275 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001276 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001277 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001278 makeArrayRef(Args, NumArgs),
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001279 RBracLoc, isImplicit));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001280 }
1281
Douglas Gregor2725ca82010-04-21 19:57:20 +00001282 // If necessary, apply function/array conversion to the receiver.
1283 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001284 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1285 if (Result.isInvalid())
1286 return ExprError();
1287 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001288 ReceiverType = Receiver->getType();
1289 }
1290
Douglas Gregorf49bb082010-04-22 17:01:48 +00001291 if (!Method) {
1292 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001293 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001294 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001295 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1296 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001297 SourceRange(LBracLoc, RBracLoc),
1298 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001299 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001300 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001301 SourceRange(LBracLoc, RBracLoc),
1302 receiverIsId);
Fariborz Jahanianb76a97e2011-12-07 00:30:00 +00001303 if (Method)
1304 DiagnoseAvailabilityOfDecl(Method, Loc, 0);
1305
Douglas Gregorf49bb082010-04-22 17:01:48 +00001306 } else if (ReceiverType->isObjCClassType() ||
1307 ReceiverType->isObjCQualifiedClassType()) {
1308 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001309 // We allow sending a message to a qualified Class ("Class<foo>"), which
1310 // is ok as long as one of the protocols implements the selector (if not, warn).
1311 if (const ObjCObjectPointerType *QClassTy
1312 = ReceiverType->getAsObjCQualifiedClassType()) {
1313 // Search protocols for class methods.
1314 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1315 if (!Method) {
1316 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1317 // warn if instance method found for a Class message.
1318 if (Method) {
1319 Diag(Loc, diag::warn_instance_method_on_class_found)
1320 << Method->getSelector() << Sel;
1321 Diag(Method->getLocation(), diag::note_method_declared_at);
1322 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001323 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001324 } else {
1325 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1326 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1327 // First check the public methods in the class interface.
1328 Method = ClassDecl->lookupClassMethod(Sel);
1329
1330 if (!Method)
1331 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1332 }
1333 if (Method && DiagnoseUseOfDecl(Method, Loc))
1334 return ExprError();
1335 }
1336 if (!Method) {
1337 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00001338 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001339 Method = LookupFactoryMethodInGlobalPool(Sel,
1340 SourceRange(LBracLoc, RBracLoc),
1341 true);
1342 if (!Method) {
1343 // If no class (factory) method was found, check if an _instance_
1344 // method of the same name exists in the root class only.
1345 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001346 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001347 true);
1348 if (Method)
1349 if (const ObjCInterfaceDecl *ID =
1350 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1351 if (ID->getSuperClass())
1352 Diag(Loc, diag::warn_root_inst_method_not_found)
1353 << Sel << SourceRange(LBracLoc, RBracLoc);
1354 }
1355 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001356 }
1357 }
1358 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001359 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001360 ObjCInterfaceDecl* ClassDecl = 0;
1361
1362 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1363 // long as one of the protocols implements the selector (if not, warn).
1364 if (const ObjCObjectPointerType *QIdTy
1365 = ReceiverType->getAsObjCQualifiedIdType()) {
1366 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001367 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1368 if (!Method)
1369 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001370 } else if (const ObjCObjectPointerType *OCIType
1371 = ReceiverType->getAsObjCInterfacePointerType()) {
1372 // We allow sending a message to a pointer to an interface (an object).
1373 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001374
Douglas Gregorb3029962011-11-14 22:10:01 +00001375 // Try to complete the type. Under ARC, this is a hard error from which
1376 // we don't try to recover.
1377 const ObjCInterfaceDecl *forwardClass = 0;
1378 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
1379 getLangOptions().ObjCAutoRefCount
1380 ? PDiag(diag::err_arc_receiver_forward_instance)
1381 << (Receiver ? Receiver->getSourceRange()
1382 : SourceRange(SuperLoc))
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00001383 : PDiag(diag::warn_receiver_forward_instance)
1384 << (Receiver ? Receiver->getSourceRange()
1385 : SourceRange(SuperLoc)))) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001386 if (getLangOptions().ObjCAutoRefCount)
1387 return ExprError();
1388
1389 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian4cc9b102012-02-03 01:02:44 +00001390 Diag(Receiver ? Receiver->getLocStart()
1391 : SuperLoc, diag::note_receiver_is_id);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00001392 Method = 0;
1393 } else {
1394 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCallf85e1932011-06-15 23:02:42 +00001395 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001396
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001397 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001398 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001399 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1400
Douglas Gregorf49bb082010-04-22 17:01:48 +00001401 if (!Method) {
1402 // If we have implementations in scope, check "private" methods.
1403 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1404
John McCallf85e1932011-06-15 23:02:42 +00001405 if (!Method && getLangOptions().ObjCAutoRefCount) {
1406 Diag(Loc, diag::err_arc_may_not_respond)
1407 << OCIType->getPointeeType() << Sel;
1408 return ExprError();
1409 }
1410
Douglas Gregorc737acb2011-09-27 16:10:05 +00001411 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001412 // If we still haven't found a method, look in the global pool. This
1413 // behavior isn't very desirable, however we need it for GCC
1414 // compatibility. FIXME: should we deviate??
1415 if (OCIType->qual_empty()) {
1416 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001417 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001418 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001419 Diag(Loc, diag::warn_maynot_respond)
1420 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1421 }
1422 }
1423 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001424 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001425 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001426 } else if (!getLangOptions().ObjCAutoRefCount &&
1427 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001428 (ReceiverType->isPointerType() ||
1429 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001430 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001431 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001432 Diag(Loc, diag::warn_bad_receiver_type)
1433 << ReceiverType
1434 << Receiver->getSourceRange();
1435 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001436 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00001437 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00001438 else {
1439 // TODO: specialized warning on null receivers?
1440 bool IsNull = Receiver->isNullPointerConstant(Context,
1441 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001442 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1443 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001444 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001445 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00001446 } else {
John Wiegley429bb272011-04-08 18:41:53 +00001447 ExprResult ReceiverRes;
1448 if (getLangOptions().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00001449 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00001450 if (ReceiverRes.isUsable()) {
1451 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00001452 return BuildInstanceMessage(Receiver,
1453 ReceiverType,
1454 SuperLoc,
1455 Sel,
1456 Method,
1457 LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001458 SelectorLocs,
John Wiegley429bb272011-04-08 18:41:53 +00001459 RBracLoc,
1460 move(ArgsIn));
1461 } else {
1462 // Reject other random receiver types (e.g. structs).
1463 Diag(Loc, diag::err_bad_receiver_type)
1464 << ReceiverType << Receiver->getSourceRange();
1465 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001466 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001467 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001468 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001469 }
Mike Stump1eb44332009-09-09 15:08:12 +00001470
Douglas Gregor2725ca82010-04-21 19:57:20 +00001471 // Check the message arguments.
1472 unsigned NumArgs = ArgsIn.size();
1473 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1474 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001475 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001476 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1477 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001478 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1479 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001480 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001481 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001482
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001483 if (Method && !Method->getResultType()->isVoidType() &&
1484 RequireCompleteType(LBracLoc, Method->getResultType(),
1485 diag::err_illegal_message_expr_incomplete_type))
1486 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001487
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001488 SourceLocation SelLoc = SelectorLocs.front();
1489
John McCallf85e1932011-06-15 23:02:42 +00001490 // In ARC, forbid the user from sending messages to
1491 // retain/release/autorelease/dealloc/retainCount explicitly.
1492 if (getLangOptions().ObjCAutoRefCount) {
1493 ObjCMethodFamily family =
1494 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1495 switch (family) {
1496 case OMF_init:
1497 if (Method)
1498 checkInitMethod(Method, ReceiverType);
1499
1500 case OMF_None:
1501 case OMF_alloc:
1502 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00001503 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00001504 case OMF_mutableCopy:
1505 case OMF_new:
1506 case OMF_self:
1507 break;
1508
1509 case OMF_dealloc:
1510 case OMF_retain:
1511 case OMF_release:
1512 case OMF_autorelease:
1513 case OMF_retainCount:
1514 Diag(Loc, diag::err_arc_illegal_explicit_message)
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001515 << Sel << SelLoc;
John McCallf85e1932011-06-15 23:02:42 +00001516 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001517
1518 case OMF_performSelector:
1519 if (Method && NumArgs >= 1) {
1520 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1521 Selector ArgSel = SelExp->getSelector();
1522 ObjCMethodDecl *SelMethod =
1523 LookupInstanceMethodInGlobalPool(ArgSel,
1524 SelExp->getSourceRange());
1525 if (!SelMethod)
1526 SelMethod =
1527 LookupFactoryMethodInGlobalPool(ArgSel,
1528 SelExp->getSourceRange());
1529 if (SelMethod) {
1530 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1531 switch (SelFamily) {
1532 case OMF_alloc:
1533 case OMF_copy:
1534 case OMF_mutableCopy:
1535 case OMF_new:
1536 case OMF_self:
1537 case OMF_init:
1538 // Issue error, unless ns_returns_not_retained.
1539 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1540 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001541 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001542 diag::err_arc_perform_selector_retains);
1543 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1544 }
1545 break;
1546 default:
1547 // +0 call. OK. unless ns_returns_retained.
1548 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1549 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001550 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001551 diag::err_arc_perform_selector_retains);
1552 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1553 }
1554 break;
1555 }
1556 }
1557 } else {
1558 // error (may leak).
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001559 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001560 Diag(Args[0]->getExprLoc(), diag::note_used_here);
1561 }
1562 }
1563 break;
John McCallf85e1932011-06-15 23:02:42 +00001564 }
1565 }
1566
Douglas Gregor2725ca82010-04-21 19:57:20 +00001567 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001568 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001569 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001570 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001571 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001572 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001573 makeArrayRef(Args, NumArgs), RBracLoc,
1574 isImplicit);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001575 else
John McCallf89e55a2010-11-18 06:31:45 +00001576 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001577 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +00001578 makeArrayRef(Args, NumArgs), RBracLoc,
1579 isImplicit);
John McCallf85e1932011-06-15 23:02:42 +00001580
1581 if (getLangOptions().ObjCAutoRefCount) {
1582 // In ARC, annotate delegate init calls.
1583 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00001584 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00001585 // Only consider init calls *directly* in init implementations,
1586 // not within blocks.
1587 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1588 if (method && method->getMethodFamily() == OMF_init) {
1589 // The implicit assignment to self means we also don't want to
1590 // consume the result.
1591 Result->setDelegateInitCall(true);
1592 return Owned(Result);
1593 }
1594 }
1595
1596 // In ARC, check for message sends which are likely to introduce
1597 // retain cycles.
1598 checkRetainCycles(Result);
1599 }
1600
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001601 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001602}
1603
1604// ActOnInstanceMessage - used for both unary and keyword messages.
1605// ArgExprs is optional - if it is present, the number of expressions
1606// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001607ExprResult Sema::ActOnInstanceMessage(Scope *S,
1608 Expr *Receiver,
1609 Selector Sel,
1610 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001611 ArrayRef<SourceLocation> SelectorLocs,
John McCall60d7b3a2010-08-24 06:29:42 +00001612 SourceLocation RBracLoc,
1613 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001614 if (!Receiver)
1615 return ExprError();
1616
John McCall9ae2f072010-08-23 23:25:46 +00001617 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001618 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001619 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001620}
Chris Lattnereca7be62008-04-07 05:30:13 +00001621
John McCallf85e1932011-06-15 23:02:42 +00001622enum ARCConversionTypeClass {
John McCall2cf031d2011-10-01 01:01:08 +00001623 /// int, void, struct A
John McCallf85e1932011-06-15 23:02:42 +00001624 ACTC_none,
John McCall2cf031d2011-10-01 01:01:08 +00001625
1626 /// id, void (^)()
John McCallf85e1932011-06-15 23:02:42 +00001627 ACTC_retainable,
John McCall2cf031d2011-10-01 01:01:08 +00001628
1629 /// id*, id***, void (^*)(),
1630 ACTC_indirectRetainable,
1631
1632 /// void* might be a normal C type, or it might a CF type.
1633 ACTC_voidPtr,
1634
1635 /// struct A*
1636 ACTC_coreFoundation
John McCallf85e1932011-06-15 23:02:42 +00001637};
John McCall2cf031d2011-10-01 01:01:08 +00001638static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
1639 return (ACTC == ACTC_retainable ||
1640 ACTC == ACTC_coreFoundation ||
1641 ACTC == ACTC_voidPtr);
1642}
1643static bool isAnyCLike(ARCConversionTypeClass ACTC) {
1644 return ACTC == ACTC_none ||
1645 ACTC == ACTC_voidPtr ||
1646 ACTC == ACTC_coreFoundation;
1647}
1648
John McCallf85e1932011-06-15 23:02:42 +00001649static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCall2cf031d2011-10-01 01:01:08 +00001650 bool isIndirect = false;
John McCallf85e1932011-06-15 23:02:42 +00001651
1652 // Ignore an outermost reference type.
John McCall2cf031d2011-10-01 01:01:08 +00001653 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCallf85e1932011-06-15 23:02:42 +00001654 type = ref->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00001655 isIndirect = true;
1656 }
John McCallf85e1932011-06-15 23:02:42 +00001657
1658 // Drill through pointers and arrays recursively.
1659 while (true) {
1660 if (const PointerType *ptr = type->getAs<PointerType>()) {
1661 type = ptr->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00001662
1663 // The first level of pointer may be the innermost pointer on a CF type.
1664 if (!isIndirect) {
1665 if (type->isVoidType()) return ACTC_voidPtr;
1666 if (type->isRecordType()) return ACTC_coreFoundation;
1667 }
John McCallf85e1932011-06-15 23:02:42 +00001668 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1669 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1670 } else {
1671 break;
1672 }
John McCall2cf031d2011-10-01 01:01:08 +00001673 isIndirect = true;
John McCallf85e1932011-06-15 23:02:42 +00001674 }
1675
John McCall2cf031d2011-10-01 01:01:08 +00001676 if (isIndirect) {
1677 if (type->isObjCARCBridgableType())
1678 return ACTC_indirectRetainable;
1679 return ACTC_none;
1680 }
1681
1682 if (type->isObjCARCBridgableType())
1683 return ACTC_retainable;
1684
1685 return ACTC_none;
John McCallf85e1932011-06-15 23:02:42 +00001686}
1687
1688namespace {
John McCall2cf031d2011-10-01 01:01:08 +00001689 /// A result from the cast checker.
1690 enum ACCResult {
1691 /// Cannot be casted.
1692 ACC_invalid,
1693
1694 /// Can be safely retained or not retained.
1695 ACC_bottom,
1696
1697 /// Can be casted at +0.
1698 ACC_plusZero,
1699
1700 /// Can be casted at +1.
1701 ACC_plusOne
1702 };
1703 ACCResult merge(ACCResult left, ACCResult right) {
1704 if (left == right) return left;
1705 if (left == ACC_bottom) return right;
1706 if (right == ACC_bottom) return left;
1707 return ACC_invalid;
1708 }
1709
1710 /// A checker which white-lists certain expressions whose conversion
1711 /// to or from retainable type would otherwise be forbidden in ARC.
1712 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
1713 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
1714
John McCallf85e1932011-06-15 23:02:42 +00001715 ASTContext &Context;
John McCall2cf031d2011-10-01 01:01:08 +00001716 ARCConversionTypeClass SourceClass;
1717 ARCConversionTypeClass TargetClass;
1718
1719 static bool isCFType(QualType type) {
1720 // Someday this can use ns_bridged. For now, it has to do this.
1721 return type->isCARCBridgableType();
John McCallf85e1932011-06-15 23:02:42 +00001722 }
John McCall2cf031d2011-10-01 01:01:08 +00001723
1724 public:
1725 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
1726 ARCConversionTypeClass target)
1727 : Context(Context), SourceClass(source), TargetClass(target) {}
1728
1729 using super::Visit;
1730 ACCResult Visit(Expr *e) {
1731 return super::Visit(e->IgnoreParens());
1732 }
1733
1734 ACCResult VisitStmt(Stmt *s) {
1735 return ACC_invalid;
1736 }
1737
1738 /// Null pointer constants can be casted however you please.
1739 ACCResult VisitExpr(Expr *e) {
1740 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1741 return ACC_bottom;
1742 return ACC_invalid;
1743 }
1744
1745 /// Objective-C string literals can be safely casted.
1746 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
1747 // If we're casting to any retainable type, go ahead. Global
1748 // strings are immune to retains, so this is bottom.
1749 if (isAnyRetainable(TargetClass)) return ACC_bottom;
1750
1751 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00001752 }
1753
John McCall2cf031d2011-10-01 01:01:08 +00001754 /// Look through certain implicit and explicit casts.
1755 ACCResult VisitCastExpr(CastExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00001756 switch (e->getCastKind()) {
1757 case CK_NullToPointer:
John McCall2cf031d2011-10-01 01:01:08 +00001758 return ACC_bottom;
1759
John McCallf85e1932011-06-15 23:02:42 +00001760 case CK_NoOp:
1761 case CK_LValueToRValue:
1762 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00001763 case CK_CPointerToObjCPointerCast:
1764 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00001765 case CK_AnyPointerToBlockPointerCast:
1766 return Visit(e->getSubExpr());
John McCall2cf031d2011-10-01 01:01:08 +00001767
John McCallf85e1932011-06-15 23:02:42 +00001768 default:
John McCall2cf031d2011-10-01 01:01:08 +00001769 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00001770 }
1771 }
John McCall2cf031d2011-10-01 01:01:08 +00001772
1773 /// Look through unary extension.
1774 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00001775 return Visit(e->getSubExpr());
1776 }
John McCall2cf031d2011-10-01 01:01:08 +00001777
1778 /// Ignore the LHS of a comma operator.
1779 ACCResult VisitBinComma(BinaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00001780 return Visit(e->getRHS());
1781 }
John McCall2cf031d2011-10-01 01:01:08 +00001782
1783 /// Conditional operators are okay if both sides are okay.
1784 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
1785 ACCResult left = Visit(e->getTrueExpr());
1786 if (left == ACC_invalid) return ACC_invalid;
1787 return merge(left, Visit(e->getFalseExpr()));
John McCallf85e1932011-06-15 23:02:42 +00001788 }
John McCall2cf031d2011-10-01 01:01:08 +00001789
John McCall4b9c2d22011-11-06 09:01:30 +00001790 /// Look through pseudo-objects.
1791 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
1792 // If we're getting here, we should always have a result.
1793 return Visit(e->getResultExpr());
1794 }
1795
John McCall2cf031d2011-10-01 01:01:08 +00001796 /// Statement expressions are okay if their result expression is okay.
1797 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00001798 return Visit(e->getSubStmt()->body_back());
1799 }
John McCallf85e1932011-06-15 23:02:42 +00001800
John McCall2cf031d2011-10-01 01:01:08 +00001801 /// Some declaration references are okay.
1802 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
1803 // References to global constants from system headers are okay.
1804 // These are things like 'kCFStringTransformToLatin'. They are
1805 // can also be assumed to be immune to retains.
1806 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
1807 if (isAnyRetainable(TargetClass) &&
1808 isAnyRetainable(SourceClass) &&
1809 var &&
1810 var->getStorageClass() == SC_Extern &&
1811 var->getType().isConstQualified() &&
1812 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
1813 return ACC_bottom;
1814 }
1815
1816 // Nothing else.
1817 return ACC_invalid;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001818 }
John McCall2cf031d2011-10-01 01:01:08 +00001819
1820 /// Some calls are okay.
1821 ACCResult VisitCallExpr(CallExpr *e) {
1822 if (FunctionDecl *fn = e->getDirectCallee())
1823 if (ACCResult result = checkCallToFunction(fn))
1824 return result;
1825
1826 return super::VisitCallExpr(e);
1827 }
1828
1829 ACCResult checkCallToFunction(FunctionDecl *fn) {
1830 // Require a CF*Ref return type.
1831 if (!isCFType(fn->getResultType()))
1832 return ACC_invalid;
1833
1834 if (!isAnyRetainable(TargetClass))
1835 return ACC_invalid;
1836
1837 // Honor an explicit 'not retained' attribute.
1838 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
1839 return ACC_plusZero;
1840
1841 // Honor an explicit 'retained' attribute, except that for
1842 // now we're not going to permit implicit handling of +1 results,
1843 // because it's a bit frightening.
1844 if (fn->hasAttr<CFReturnsRetainedAttr>())
1845 return ACC_invalid; // ACC_plusOne if we start accepting this
1846
1847 // Recognize this specific builtin function, which is used by CFSTR.
1848 unsigned builtinID = fn->getBuiltinID();
1849 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
1850 return ACC_bottom;
1851
1852 // Otherwise, don't do anything implicit with an unaudited function.
1853 if (!fn->hasAttr<CFAuditedTransferAttr>())
1854 return ACC_invalid;
1855
1856 // Otherwise, it's +0 unless it follows the create convention.
1857 if (ento::coreFoundation::followsCreateRule(fn))
1858 return ACC_invalid; // ACC_plusOne if we start accepting this
1859
1860 return ACC_plusZero;
1861 }
1862
1863 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
1864 return checkCallToMethod(e->getMethodDecl());
1865 }
1866
1867 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
1868 ObjCMethodDecl *method;
1869 if (e->isExplicitProperty())
1870 method = e->getExplicitProperty()->getGetterMethodDecl();
1871 else
1872 method = e->getImplicitPropertyGetter();
1873 return checkCallToMethod(method);
1874 }
1875
1876 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
1877 if (!method) return ACC_invalid;
1878
1879 // Check for message sends to functions returning CF types. We
1880 // just obey the Cocoa conventions with these, even though the
1881 // return type is CF.
1882 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
1883 return ACC_invalid;
1884
1885 // If the method is explicitly marked not-retained, it's +0.
1886 if (method->hasAttr<CFReturnsNotRetainedAttr>())
1887 return ACC_plusZero;
1888
1889 // If the method is explicitly marked as returning retained, or its
1890 // selector follows a +1 Cocoa convention, treat it as +1.
1891 if (method->hasAttr<CFReturnsRetainedAttr>())
1892 return ACC_plusOne;
1893
1894 switch (method->getSelector().getMethodFamily()) {
1895 case OMF_alloc:
1896 case OMF_copy:
1897 case OMF_mutableCopy:
1898 case OMF_new:
1899 return ACC_plusOne;
1900
1901 default:
1902 // Otherwise, treat it as +0.
1903 return ACC_plusZero;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001904 }
1905 }
John McCall2cf031d2011-10-01 01:01:08 +00001906 };
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001907}
1908
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001909static bool
1910KnownName(Sema &S, const char *name) {
1911 LookupResult R(S, &S.Context.Idents.get(name), SourceLocation(),
1912 Sema::LookupOrdinaryName);
1913 return S.LookupName(R, S.TUScope, false);
1914}
1915
John McCall5acb0c92011-10-17 18:40:02 +00001916static void
1917diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
1918 QualType castType, ARCConversionTypeClass castACTC,
1919 Expr *castExpr, ARCConversionTypeClass exprACTC,
1920 Sema::CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00001921 SourceLocation loc =
John McCall2cf031d2011-10-01 01:01:08 +00001922 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00001923
John McCall5acb0c92011-10-17 18:40:02 +00001924 if (S.makeUnavailableInSystemHeader(loc,
John McCall2cf031d2011-10-01 01:01:08 +00001925 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCallf85e1932011-06-15 23:02:42 +00001926 return;
John McCall5acb0c92011-10-17 18:40:02 +00001927
1928 QualType castExprType = castExpr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001929
John McCall71c482c2011-06-17 06:50:50 +00001930 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00001931 switch (exprACTC) {
John McCall2cf031d2011-10-01 01:01:08 +00001932 case ACTC_none:
1933 case ACTC_coreFoundation:
1934 case ACTC_voidPtr:
1935 srcKind = (castExprType->isPointerType() ? 1 : 0);
1936 break;
1937 case ACTC_retainable:
1938 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1939 break;
1940 case ACTC_indirectRetainable:
1941 srcKind = 4;
1942 break;
John McCallf85e1932011-06-15 23:02:42 +00001943 }
1944
John McCall5acb0c92011-10-17 18:40:02 +00001945 // Check whether this could be fixed with a bridge cast.
1946 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
1947 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCallf85e1932011-06-15 23:02:42 +00001948
John McCall5acb0c92011-10-17 18:40:02 +00001949 // Bridge from an ARC type to a CF type.
1950 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001951
John McCall5acb0c92011-10-17 18:40:02 +00001952 S.Diag(loc, diag::err_arc_cast_requires_bridge)
1953 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
1954 << 2 // of C pointer type
1955 << castExprType
1956 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
1957 << castType
1958 << castRange
1959 << castExpr->getSourceRange();
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001960 bool br = KnownName(S, "CFBridgingRelease");
John McCall5acb0c92011-10-17 18:40:02 +00001961 S.Diag(noteLoc, diag::note_arc_bridge)
1962 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1963 FixItHint::CreateInsertion(afterLParen, "__bridge "));
1964 S.Diag(noteLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001965 << castExprType << br
John McCall5acb0c92011-10-17 18:40:02 +00001966 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001967 FixItHint::CreateInsertion(afterLParen,
1968 br ? "CFBridgingRelease " : "__bridge_transfer "));
John McCall5acb0c92011-10-17 18:40:02 +00001969
1970 return;
1971 }
1972
1973 // Bridge from a CF type to an ARC type.
1974 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001975 bool br = KnownName(S, "CFBridgingRetain");
John McCall5acb0c92011-10-17 18:40:02 +00001976 S.Diag(loc, diag::err_arc_cast_requires_bridge)
1977 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
1978 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
1979 << castExprType
1980 << 2 // to C pointer type
1981 << castType
1982 << castRange
1983 << castExpr->getSourceRange();
1984
1985 S.Diag(noteLoc, diag::note_arc_bridge)
1986 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1987 FixItHint::CreateInsertion(afterLParen, "__bridge "));
1988 S.Diag(noteLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001989 << castType << br
John McCall5acb0c92011-10-17 18:40:02 +00001990 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
Fariborz Jahanian52b62362012-02-01 22:56:20 +00001991 FixItHint::CreateInsertion(afterLParen,
1992 br ? "CFBridgingRetain " : "__bridge_retained"));
John McCall5acb0c92011-10-17 18:40:02 +00001993
1994 return;
John McCallf85e1932011-06-15 23:02:42 +00001995 }
1996
John McCall5acb0c92011-10-17 18:40:02 +00001997 S.Diag(loc, diag::err_arc_mismatched_cast)
1998 << (CCK != Sema::CCK_ImplicitConversion)
1999 << srcKind << castExprType << castType
John McCallf85e1932011-06-15 23:02:42 +00002000 << castRange << castExpr->getSourceRange();
2001}
2002
John McCall5acb0c92011-10-17 18:40:02 +00002003Sema::ARCConversionResult
2004Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
2005 Expr *&castExpr, CheckedConversionKind CCK) {
2006 QualType castExprType = castExpr->getType();
2007
2008 // For the purposes of the classification, we assume reference types
2009 // will bind to temporaries.
2010 QualType effCastType = castType;
2011 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
2012 effCastType = ref->getPointeeType();
2013
2014 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
2015 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002016 if (exprACTC == castACTC) {
2017 // check for viablity and report error if casting an rvalue to a
2018 // life-time qualifier.
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002019 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002020 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00002021 (castType != castExprType)) {
2022 const Type *DT = castType.getTypePtr();
2023 QualType QDT = castType;
2024 // We desugar some types but not others. We ignore those
2025 // that cannot happen in a cast; i.e. auto, and those which
2026 // should not be de-sugared; i.e typedef.
2027 if (const ParenType *PT = dyn_cast<ParenType>(DT))
2028 QDT = PT->desugar();
2029 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
2030 QDT = TP->desugar();
2031 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
2032 QDT = AT->desugar();
2033 if (QDT != castType &&
2034 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
2035 SourceLocation loc =
2036 (castRange.isValid() ? castRange.getBegin()
2037 : castExpr->getExprLoc());
2038 Diag(loc, diag::err_arc_nolifetime_behavior);
2039 }
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00002040 }
2041 return ACR_okay;
2042 }
2043
John McCall5acb0c92011-10-17 18:40:02 +00002044 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
2045
2046 // Allow all of these types to be cast to integer types (but not
2047 // vice-versa).
2048 if (castACTC == ACTC_none && castType->isIntegralType(Context))
2049 return ACR_okay;
2050
2051 // Allow casts between pointers to lifetime types (e.g., __strong id*)
2052 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
2053 // must be explicit.
2054 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
2055 return ACR_okay;
2056 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
2057 CCK != CCK_ImplicitConversion)
2058 return ACR_okay;
2059
2060 switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
2061 // For invalid casts, fall through.
2062 case ACC_invalid:
2063 break;
2064
2065 // Do nothing for both bottom and +0.
2066 case ACC_bottom:
2067 case ACC_plusZero:
2068 return ACR_okay;
2069
2070 // If the result is +1, consume it here.
2071 case ACC_plusOne:
2072 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
2073 CK_ARCConsumeObject, castExpr,
2074 0, VK_RValue);
2075 ExprNeedsCleanups = true;
2076 return ACR_okay;
2077 }
2078
2079 // If this is a non-implicit cast from id or block type to a
2080 // CoreFoundation type, delay complaining in case the cast is used
2081 // in an acceptable context.
2082 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
2083 CCK != CCK_ImplicitConversion)
2084 return ACR_unbridged;
2085
2086 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2087 castExpr, exprACTC, CCK);
2088 return ACR_okay;
2089}
2090
2091/// Given that we saw an expression with the ARCUnbridgedCastTy
2092/// placeholder type, complain bitterly.
2093void Sema::diagnoseARCUnbridgedCast(Expr *e) {
2094 // We expect the spurious ImplicitCastExpr to already have been stripped.
2095 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2096 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
2097
2098 SourceRange castRange;
2099 QualType castType;
2100 CheckedConversionKind CCK;
2101
2102 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
2103 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
2104 castType = cast->getTypeAsWritten();
2105 CCK = CCK_CStyleCast;
2106 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
2107 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
2108 castType = cast->getTypeAsWritten();
2109 CCK = CCK_OtherCast;
2110 } else {
2111 castType = cast->getType();
2112 CCK = CCK_ImplicitConversion;
2113 }
2114
2115 ARCConversionTypeClass castACTC =
2116 classifyTypeForARCConversion(castType.getNonReferenceType());
2117
2118 Expr *castExpr = realCast->getSubExpr();
2119 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
2120
2121 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2122 castExpr, ACTC_retainable, CCK);
2123}
2124
2125/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
2126/// type, remove the placeholder cast.
2127Expr *Sema::stripARCUnbridgedCast(Expr *e) {
2128 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2129
2130 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
2131 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
2132 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
2133 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
2134 assert(uo->getOpcode() == UO_Extension);
2135 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
2136 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
2137 sub->getValueKind(), sub->getObjectKind(),
2138 uo->getOperatorLoc());
2139 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
2140 assert(!gse->isResultDependent());
2141
2142 unsigned n = gse->getNumAssocs();
2143 SmallVector<Expr*, 4> subExprs(n);
2144 SmallVector<TypeSourceInfo*, 4> subTypes(n);
2145 for (unsigned i = 0; i != n; ++i) {
2146 subTypes[i] = gse->getAssocTypeSourceInfo(i);
2147 Expr *sub = gse->getAssocExpr(i);
2148 if (i == gse->getResultIndex())
2149 sub = stripARCUnbridgedCast(sub);
2150 subExprs[i] = sub;
2151 }
2152
2153 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
2154 gse->getControllingExpr(),
2155 subTypes.data(), subExprs.data(),
2156 n, gse->getDefaultLoc(),
2157 gse->getRParenLoc(),
2158 gse->containsUnexpandedParameterPack(),
2159 gse->getResultIndex());
2160 } else {
2161 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
2162 return cast<ImplicitCastExpr>(e)->getSubExpr();
2163 }
2164}
2165
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00002166bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
2167 QualType exprType) {
2168 QualType canCastType =
2169 Context.getCanonicalType(castType).getUnqualifiedType();
2170 QualType canExprType =
2171 Context.getCanonicalType(exprType).getUnqualifiedType();
2172 if (isa<ObjCObjectPointerType>(canCastType) &&
2173 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
2174 canExprType->isObjCObjectPointerType()) {
2175 if (const ObjCObjectPointerType *ObjT =
2176 canExprType->getAs<ObjCObjectPointerType>())
2177 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
2178 return false;
2179 }
2180 return true;
2181}
2182
John McCall7e5e5f42011-07-07 06:58:02 +00002183/// Look for an ObjCReclaimReturnedObject cast and destroy it.
2184static Expr *maybeUndoReclaimObject(Expr *e) {
2185 // For now, we just undo operands that are *immediately* reclaim
2186 // expressions, which prevents the vast majority of potential
2187 // problems here. To catch them all, we'd need to rebuild arbitrary
2188 // value-propagating subexpressions --- we can't reliably rebuild
2189 // in-place because of expression sharing.
2190 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00002191 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00002192 return ice->getSubExpr();
2193
2194 return e;
2195}
2196
John McCallf85e1932011-06-15 23:02:42 +00002197ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
2198 ObjCBridgeCastKind Kind,
2199 SourceLocation BridgeKeywordLoc,
2200 TypeSourceInfo *TSInfo,
2201 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00002202 ExprResult SubResult = UsualUnaryConversions(SubExpr);
2203 if (SubResult.isInvalid()) return ExprError();
2204 SubExpr = SubResult.take();
2205
John McCallf85e1932011-06-15 23:02:42 +00002206 QualType T = TSInfo->getType();
2207 QualType FromType = SubExpr->getType();
2208
John McCall1d9b3b22011-09-09 05:25:32 +00002209 CastKind CK;
2210
John McCallf85e1932011-06-15 23:02:42 +00002211 bool MustConsume = false;
2212 if (T->isDependentType() || SubExpr->isTypeDependent()) {
2213 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00002214 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00002215 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
2216 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00002217 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
2218 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00002219 switch (Kind) {
2220 case OBC_Bridge:
2221 break;
2222
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002223 case OBC_BridgeRetained: {
2224 bool br = KnownName(*this, "CFBridgingRelease");
John McCallf85e1932011-06-15 23:02:42 +00002225 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2226 << 2
2227 << FromType
2228 << (T->isBlockPointerType()? 1 : 0)
2229 << T
2230 << SubExpr->getSourceRange()
2231 << Kind;
2232 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2233 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
2234 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002235 << FromType << br
John McCallf85e1932011-06-15 23:02:42 +00002236 << FixItHint::CreateReplacement(BridgeKeywordLoc,
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002237 br ? "CFBridgingRelease "
2238 : "__bridge_transfer ");
John McCallf85e1932011-06-15 23:02:42 +00002239
2240 Kind = OBC_Bridge;
2241 break;
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002242 }
John McCallf85e1932011-06-15 23:02:42 +00002243
2244 case OBC_BridgeTransfer:
2245 // We must consume the Objective-C object produced by the cast.
2246 MustConsume = true;
2247 break;
2248 }
2249 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
2250 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00002251 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00002252 switch (Kind) {
2253 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00002254 // Reclaiming a value that's going to be __bridge-casted to CF
2255 // is very dangerous, so we don't do it.
2256 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00002257 break;
2258
2259 case OBC_BridgeRetained:
2260 // Produce the object before casting it.
2261 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00002262 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00002263 SubExpr, 0, VK_RValue);
2264 break;
2265
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002266 case OBC_BridgeTransfer: {
2267 bool br = KnownName(*this, "CFBridgingRetain");
John McCallf85e1932011-06-15 23:02:42 +00002268 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2269 << (FromType->isBlockPointerType()? 1 : 0)
2270 << FromType
2271 << 2
2272 << T
2273 << SubExpr->getSourceRange()
2274 << Kind;
2275
2276 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2277 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
2278 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002279 << T << br
2280 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2281 br ? "CFBridgingRetain " : "__bridge_retained");
John McCallf85e1932011-06-15 23:02:42 +00002282
2283 Kind = OBC_Bridge;
2284 break;
2285 }
Fariborz Jahanian52b62362012-02-01 22:56:20 +00002286 }
John McCallf85e1932011-06-15 23:02:42 +00002287 } else {
2288 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
2289 << FromType << T << Kind
2290 << SubExpr->getSourceRange()
2291 << TSInfo->getTypeLoc().getSourceRange();
2292 return ExprError();
2293 }
2294
John McCall1d9b3b22011-09-09 05:25:32 +00002295 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00002296 BridgeKeywordLoc,
2297 TSInfo, SubExpr);
2298
2299 if (MustConsume) {
2300 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00002301 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00002302 0, VK_RValue);
2303 }
2304
2305 return Result;
2306}
2307
2308ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
2309 SourceLocation LParenLoc,
2310 ObjCBridgeCastKind Kind,
2311 SourceLocation BridgeKeywordLoc,
2312 ParsedType Type,
2313 SourceLocation RParenLoc,
2314 Expr *SubExpr) {
2315 TypeSourceInfo *TSInfo = 0;
2316 QualType T = GetTypeFromParser(Type, &TSInfo);
2317 if (!TSInfo)
2318 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
2319 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
2320 SubExpr);
2321}