blob: 20c3b754313f69d7596f963500e211309fb8e906 [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]);
268 blockScope->Captures.push_back(
269 BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
270 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 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000457 // diagnose nonnull arguments.
458 for (specific_attr_iterator<NonNullAttr>
459 i = Method->specific_attr_begin<NonNullAttr>(),
460 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
461 CheckNonNullArguments(*i, Args, lbrac);
462 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000463
Douglas Gregor2725ca82010-04-21 19:57:20 +0000464 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000465 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000466}
467
Douglas Gregorc737acb2011-09-27 16:10:05 +0000468bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000469 // 'self' is objc 'self' in an objc method only.
John McCall4b9c2d22011-11-06 09:01:30 +0000470 ObjCMethodDecl *method =
471 dyn_cast<ObjCMethodDecl>(CurContext->getNonClosureAncestor());
472 if (!method) return false;
473
John McCallf85e1932011-06-15 23:02:42 +0000474 receiver = receiver->IgnoreParenLValueCasts();
475 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
John McCall4b9c2d22011-11-06 09:01:30 +0000476 if (DRE->getDecl() == method->getSelfDecl())
Douglas Gregorc737acb2011-09-27 16:10:05 +0000477 return true;
478 return false;
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000479}
480
Steve Narofff1afaf62009-02-26 15:55:06 +0000481// Helper method for ActOnClassMethod/ActOnInstanceMethod.
482// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000483// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000484// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000485ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000486 ObjCInterfaceDecl *ClassDecl) {
487 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000488 // lookup in class and all superclasses
489 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000490 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000491 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Steve Naroff5609ec02009-03-08 18:56:13 +0000493 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000494 if (!Method)
495 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000496
Steve Naroff5609ec02009-03-08 18:56:13 +0000497 // Before we give up, check if the selector is an instance method.
498 // But only in the root. This matches gcc's behaviour and what the
499 // runtime expects.
500 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000501 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000502 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000503 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000504 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000505 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
506 }
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Steve Naroff5609ec02009-03-08 18:56:13 +0000508 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000509 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000510 return Method;
511}
512
513ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
514 ObjCInterfaceDecl *ClassDecl) {
Douglas Gregor2e5c15b2011-12-15 05:27:12 +0000515 if (!ClassDecl->hasDefinition())
516 return 0;
517
Steve Naroff5609ec02009-03-08 18:56:13 +0000518 ObjCMethodDecl *Method = 0;
519 while (ClassDecl && !Method) {
520 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000521 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000522 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000523
Steve Naroff5609ec02009-03-08 18:56:13 +0000524 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000525 if (!Method)
526 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000527 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000528 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000529 return Method;
530}
531
John McCall3c3b7f92011-10-25 17:37:35 +0000532/// LookupMethodInType - Look up a method in an ObjCObjectType.
533ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type,
534 bool isInstance) {
535 const ObjCObjectType *objType = type->castAs<ObjCObjectType>();
536 if (ObjCInterfaceDecl *iface = objType->getInterface()) {
537 // Look it up in the main interface (and categories, etc.)
538 if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance))
539 return method;
540
541 // Okay, look for "private" methods declared in any
542 // @implementations we've seen.
543 if (isInstance) {
544 if (ObjCMethodDecl *method = LookupPrivateInstanceMethod(sel, iface))
545 return method;
546 } else {
547 if (ObjCMethodDecl *method = LookupPrivateClassMethod(sel, iface))
548 return method;
549 }
550 }
551
552 // Check qualifiers.
553 for (ObjCObjectType::qual_iterator
554 i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i)
555 if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance))
556 return method;
557
558 return 0;
559}
560
Fariborz Jahanian61478062011-03-09 20:18:06 +0000561/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
562/// list of a qualified objective pointer type.
563ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
564 const ObjCObjectPointerType *OPT,
565 bool Instance)
566{
567 ObjCMethodDecl *MD = 0;
568 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
569 E = OPT->qual_end(); I != E; ++I) {
570 ObjCProtocolDecl *PROTO = (*I);
571 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
572 return MD;
573 }
574 }
575 return 0;
576}
577
Chris Lattner7f816522010-04-11 07:45:24 +0000578/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
579/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000580ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000581HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000582 Expr *BaseExpr, SourceLocation OpLoc,
583 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000584 SourceLocation MemberLoc,
585 SourceLocation SuperLoc, QualType SuperType,
586 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000587 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
588 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000589
590 if (MemberName.getNameKind() != DeclarationName::Identifier) {
591 Diag(MemberLoc, diag::err_invalid_property_name)
592 << MemberName << QualType(OPT, 0);
593 return ExprError();
594 }
595
Chris Lattner7f816522010-04-11 07:45:24 +0000596 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Douglas Gregorb3029962011-11-14 22:10:01 +0000597 SourceRange BaseRange = Super? SourceRange(SuperLoc)
598 : BaseExpr->getSourceRange();
599 if (RequireCompleteType(MemberLoc, OPT->getPointeeType(),
600 PDiag(diag::err_property_not_found_forward_class)
601 << MemberName << BaseRange))
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000602 return ExprError();
Douglas Gregorb3029962011-11-14 22:10:01 +0000603
Chris Lattner7f816522010-04-11 07:45:24 +0000604 // Search for a declared property first.
605 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
606 // Check whether we can reference this property.
607 if (DiagnoseUseOfDecl(PD, MemberLoc))
608 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000609
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000610 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +0000611 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000612 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000613 MemberLoc,
614 SuperLoc, SuperType));
615 else
John McCall3c3b7f92011-10-25 17:37:35 +0000616 return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000617 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000618 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000619 }
620 // Check protocols on qualified interfaces.
621 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
622 E = OPT->qual_end(); I != E; ++I)
623 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
624 // Check whether we can reference this property.
625 if (DiagnoseUseOfDecl(PD, MemberLoc))
626 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000627
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000628 if (Super)
John McCall3c3b7f92011-10-25 17:37:35 +0000629 return Owned(new (Context) ObjCPropertyRefExpr(PD,
630 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000631 VK_LValue,
632 OK_ObjCProperty,
633 MemberLoc,
634 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000635 else
John McCall3c3b7f92011-10-25 17:37:35 +0000636 return Owned(new (Context) ObjCPropertyRefExpr(PD,
637 Context.PseudoObjectTy,
John McCallf89e55a2010-11-18 06:31:45 +0000638 VK_LValue,
639 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000640 MemberLoc,
641 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000642 }
643 // If that failed, look for an "implicit" property by seeing if the nullary
644 // selector is implemented.
645
646 // FIXME: The logic for looking up nullary and unary selectors should be
647 // shared with the code in ActOnInstanceMessage.
648
649 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
650 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000651
652 // May be founf in property's qualified list.
653 if (!Getter)
654 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000655
656 // If this reference is in an @implementation, check for 'private' methods.
657 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000658 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000659
660 // Look through local category implementations associated with the class.
661 if (!Getter)
662 Getter = IFace->getCategoryInstanceMethod(Sel);
663 if (Getter) {
664 // Check if we can reference this property.
665 if (DiagnoseUseOfDecl(Getter, MemberLoc))
666 return ExprError();
667 }
668 // If we found a getter then this may be a valid dot-reference, we
669 // will look for the matching setter, in case it is needed.
670 Selector SetterSel =
671 SelectorTable::constructSetterName(PP.getIdentifierTable(),
672 PP.getSelectorTable(), Member);
673 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000674
675 // May be founf in property's qualified list.
676 if (!Setter)
677 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
678
Chris Lattner7f816522010-04-11 07:45:24 +0000679 if (!Setter) {
680 // If this reference is in an @implementation, also check for 'private'
681 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000682 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000683 }
684 // Look through local category implementations associated with the class.
685 if (!Setter)
686 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000687
Chris Lattner7f816522010-04-11 07:45:24 +0000688 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
689 return ExprError();
690
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000691 if (Getter || Setter) {
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000692 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000693 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +0000694 Context.PseudoObjectTy,
695 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +0000696 MemberLoc,
697 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000698 else
John McCall12f78a62010-12-02 01:19:52 +0000699 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +0000700 Context.PseudoObjectTy,
701 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +0000702 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000703
Chris Lattner7f816522010-04-11 07:45:24 +0000704 }
705
706 // Attempt to correct for typos in property names.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000707 TypoCorrection Corrected = CorrectTypo(
708 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
709 NULL, IFace, false, CTC_NoKeywords, OPT);
710 if (ObjCPropertyDecl *Property =
711 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>()) {
712 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +0000713 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000714 << MemberName << QualType(OPT, 0) << TypoResult
715 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000716 Diag(Property->getLocation(), diag::note_previous_decl)
717 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000718 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
719 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000720 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000721 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000722 ObjCInterfaceDecl *ClassDeclared;
723 if (ObjCIvarDecl *Ivar =
724 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
725 QualType T = Ivar->getType();
726 if (const ObjCObjectPointerType * OBJPT =
727 T->getAsObjCInterfacePointerType()) {
Douglas Gregorb3029962011-11-14 22:10:01 +0000728 if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(),
729 PDiag(diag::err_property_not_as_forward_class)
730 << MemberName << BaseExpr->getSourceRange()))
731 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000732 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000733 Diag(MemberLoc,
734 diag::err_ivar_access_using_property_syntax_suggest)
735 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
736 << FixItHint::CreateReplacement(OpLoc, "->");
737 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000738 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000739
Chris Lattner7f816522010-04-11 07:45:24 +0000740 Diag(MemberLoc, diag::err_property_not_found)
741 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000742 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000743 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000744 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000745 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000746}
747
748
749
John McCall60d7b3a2010-08-24 06:29:42 +0000750ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000751ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
752 IdentifierInfo &propertyName,
753 SourceLocation receiverNameLoc,
754 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000756 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000757 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
758 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000759
760 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000761 if (IFace == 0) {
762 // If the "receiver" is 'super' in a method, handle it as an expression-like
763 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000764 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000765 IsSuper = true;
766
John McCall26743b22011-02-03 09:00:02 +0000767 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000768 if (CurMethod->isInstanceMethod()) {
769 QualType T =
770 Context.getObjCInterfaceType(CurMethod->getClassInterface());
771 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000772
773 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000774 /*BaseExpr*/0,
775 SourceLocation()/*OpLoc*/,
776 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000777 propertyNameLoc,
778 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000779 }
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Chris Lattnereb483eb2010-04-11 08:28:14 +0000781 // Otherwise, if this is a class method, try dispatching to our
782 // superclass.
783 IFace = CurMethod->getClassInterface()->getSuperClass();
784 }
John McCall26743b22011-02-03 09:00:02 +0000785 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000786
787 if (IFace == 0) {
788 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
789 return ExprError();
790 }
791 }
792
793 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000794 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000795 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000796
797 // If this reference is in an @implementation, check for 'private' methods.
798 if (!Getter)
799 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
800 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000801 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000802 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000803
804 if (Getter) {
805 // FIXME: refactor/share with ActOnMemberReference().
806 // Check if we can reference this property.
807 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
808 return ExprError();
809 }
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Steve Naroff61f72cb2009-03-09 21:12:44 +0000811 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000812 Selector SetterSel =
813 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000814 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000815
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000816 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000817 if (!Setter) {
818 // If this reference is in an @implementation, also check for 'private'
819 // methods.
820 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
821 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000822 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000823 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000824 }
825 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000826 if (!Setter)
827 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000828
829 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
830 return ExprError();
831
832 if (Getter || Setter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000833 if (IsSuper)
834 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +0000835 Context.PseudoObjectTy,
836 VK_LValue, OK_ObjCProperty,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000837 propertyNameLoc,
838 receiverNameLoc,
839 Context.getObjCInterfaceType(IFace)));
840
John McCall12f78a62010-12-02 01:19:52 +0000841 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +0000842 Context.PseudoObjectTy,
843 VK_LValue, OK_ObjCProperty,
John McCall12f78a62010-12-02 01:19:52 +0000844 propertyNameLoc,
845 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000846 }
847 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
848 << &propertyName << Context.getObjCInterfaceType(IFace));
849}
850
Douglas Gregor47bd5432010-04-14 02:46:37 +0000851Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000852 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000853 SourceLocation NameLoc,
854 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000855 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000856 ParsedType &ReceiverType) {
857 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000858
Douglas Gregor47bd5432010-04-14 02:46:37 +0000859 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000860 // messaging super. If the identifier is "super" and there is a
861 // trailing dot, it's an instance message.
862 if (IsSuper && S->isInObjcMethodScope())
863 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000864
865 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
866 LookupName(Result, S);
867
868 switch (Result.getResultKind()) {
869 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000870 // Normal name lookup didn't find anything. If we're in an
871 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000872 // FIXME: This is a hack. Ivar lookup should be part of normal
873 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000874 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
Argyrios Kyrtzidisccc9e762011-11-09 00:22:48 +0000875 if (!Method->getClassInterface()) {
876 // Fall back: let the parser try to parse it as an instance message.
877 return ObjCInstanceMessage;
878 }
879
Douglas Gregored464422010-04-19 20:09:36 +0000880 ObjCInterfaceDecl *ClassDeclared;
881 if (Method->getClassInterface()->lookupInstanceVariable(Name,
882 ClassDeclared))
883 return ObjCInstanceMessage;
884 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000885
Douglas Gregor47bd5432010-04-14 02:46:37 +0000886 // Break out; we'll perform typo correction below.
887 break;
888
889 case LookupResult::NotFoundInCurrentInstantiation:
890 case LookupResult::FoundOverloaded:
891 case LookupResult::FoundUnresolvedValue:
892 case LookupResult::Ambiguous:
893 Result.suppressDiagnostics();
894 return ObjCInstanceMessage;
895
896 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000897 // If the identifier is a class or not, and there is a trailing dot,
898 // it's an instance message.
899 if (HasTrailingDot)
900 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000901 // We found something. If it's a type, then we have a class
902 // message. Otherwise, it's an instance message.
903 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000904 QualType T;
905 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
906 T = Context.getObjCInterfaceType(Class);
907 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
908 T = Context.getTypeDeclType(Type);
909 else
910 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000911
Douglas Gregor1569f952010-04-21 20:38:13 +0000912 // We have a class message, and T is the type we're
913 // messaging. Build source-location information for it.
914 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000915 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000916 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000917 }
918 }
919
Douglas Gregoraaf87162010-04-14 20:04:41 +0000920 // Determine our typo-correction context.
921 CorrectTypoContext CTC = CTC_Expression;
922 if (ObjCMethodDecl *Method = getCurMethodDecl())
923 if (Method->getClassInterface() &&
924 Method->getClassInterface()->getSuperClass())
925 CTC = CTC_ObjCMessageReceiver;
926
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000927 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
928 Result.getLookupKind(), S, NULL,
929 NULL, false, CTC)) {
930 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000931 // If we found a declaration, correct when it refers to an Objective-C
932 // class.
Douglas Gregor1569f952010-04-21 20:38:13 +0000933 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000934 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000935 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000936 << FixItHint::CreateReplacement(SourceRange(NameLoc),
937 ND->getNameAsString());
938 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000939 << Corrected.getCorrection();
Douglas Gregor47bd5432010-04-14 02:46:37 +0000940
Douglas Gregor1569f952010-04-21 20:38:13 +0000941 QualType T = Context.getObjCInterfaceType(Class);
942 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000943 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000944 return ObjCClassMessage;
945 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000946 } else if (Corrected.isKeyword() &&
947 Corrected.getCorrectionAsIdentifierInfo()->isStr("super")) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000948 // If we've found the keyword "super", this is a send to super.
949 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000950 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000951 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000952 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000953 }
954 }
955
956 // Fall back: let the parser try to parse it as an instance message.
957 return ObjCInstanceMessage;
958}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000959
John McCall60d7b3a2010-08-24 06:29:42 +0000960ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000961 SourceLocation SuperLoc,
962 Selector Sel,
963 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +0000964 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000965 SourceLocation RBracLoc,
966 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000967 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000968 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000969 if (!Method) {
970 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
971 return ExprError();
972 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000973
Douglas Gregorf95861a2010-04-21 20:01:04 +0000974 ObjCInterfaceDecl *Class = Method->getClassInterface();
975 if (!Class) {
976 Diag(SuperLoc, diag::error_no_super_class_message)
977 << Method->getDeclName();
978 return ExprError();
979 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000980
Douglas Gregorf95861a2010-04-21 20:01:04 +0000981 ObjCInterfaceDecl *Super = Class->getSuperClass();
982 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000983 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000984 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
985 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000986 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000987 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000988
Douglas Gregorf95861a2010-04-21 20:01:04 +0000989 // We are in a method whose class has a superclass, so 'super'
990 // is acting as a keyword.
991 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +0000992 if (Sel.getMethodFamily() == OMF_dealloc)
993 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +0000994 if (Sel.getMethodFamily() == OMF_finalize)
995 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +0000996
Douglas Gregorf95861a2010-04-21 20:01:04 +0000997 // Since we are in an instance method, this is an instance
998 // message to the superclass instance.
999 QualType SuperTy = Context.getObjCInterfaceType(Super);
1000 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +00001001 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001002 Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001003 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001004 }
Douglas Gregorf95861a2010-04-21 20:01:04 +00001005
1006 // Since we are in a class method, this is a class message to
1007 // the superclass.
1008 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1009 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001010 SuperLoc, Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001011 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001012}
1013
1014/// \brief Build an Objective-C class message expression.
1015///
1016/// This routine takes care of both normal class messages and
1017/// class messages to the superclass.
1018///
1019/// \param ReceiverTypeInfo Type source information that describes the
1020/// receiver of this message. This may be NULL, in which case we are
1021/// sending to the superclass and \p SuperLoc must be a valid source
1022/// location.
1023
1024/// \param ReceiverType The type of the object receiving the
1025/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1026/// type as that refers to. For a superclass send, this is the type of
1027/// the superclass.
1028///
1029/// \param SuperLoc The location of the "super" keyword in a
1030/// superclass message.
1031///
1032/// \param Sel The selector to which the message is being sent.
1033///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001034/// \param Method The method that this class message is invoking, if
1035/// already known.
1036///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001037/// \param LBracLoc The location of the opening square bracket ']'.
1038///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001039/// \param RBrac The location of the closing square bracket ']'.
1040///
1041/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001042ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001043 QualType ReceiverType,
1044 SourceLocation SuperLoc,
1045 Selector Sel,
1046 ObjCMethodDecl *Method,
1047 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001048 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001049 SourceLocation RBracLoc,
1050 MultiExprArg ArgsIn) {
1051 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001052 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001053 if (LBracLoc.isInvalid()) {
1054 Diag(Loc, diag::err_missing_open_square_message_send)
1055 << FixItHint::CreateInsertion(Loc, "[");
1056 LBracLoc = Loc;
1057 }
1058
Douglas Gregor92e986e2010-04-22 16:44:27 +00001059 if (ReceiverType->isDependentType()) {
1060 // If the receiver type is dependent, we can't type-check anything
1061 // at this point. Build a dependent expression.
1062 unsigned NumArgs = ArgsIn.size();
1063 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1064 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001065 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1066 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001067 Sel, SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001068 makeArrayRef(Args, NumArgs),RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001069 }
Chris Lattner15faee12010-04-12 05:38:43 +00001070
Douglas Gregor2725ca82010-04-21 19:57:20 +00001071 // Find the class to which we are sending this message.
1072 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001073 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1074 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001075 Diag(Loc, diag::err_invalid_receiver_class_message)
1076 << ReceiverType;
1077 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001078 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001079 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian43bcdb22011-10-15 19:18:36 +00001080 // objc++ diagnoses during typename annotation.
1081 if (!getLangOptions().CPlusPlus)
1082 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001083 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001084 if (!Method) {
Douglas Gregorb3029962011-11-14 22:10:01 +00001085 SourceRange TypeRange
1086 = SuperLoc.isValid()? SourceRange(SuperLoc)
1087 : ReceiverTypeInfo->getTypeLoc().getSourceRange();
1088 if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class),
1089 (getLangOptions().ObjCAutoRefCount
1090 ? PDiag(diag::err_arc_receiver_forward_class)
1091 : PDiag(diag::warn_receiver_forward_class))
1092 << TypeRange)) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001093 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001094 Method = LookupFactoryMethodInGlobalPool(Sel,
1095 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001096 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001097 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1098 << Method->getDeclName();
1099 }
1100 if (!Method)
1101 Method = Class->lookupClassMethod(Sel);
1102
1103 // If we have an implementation in scope, check "private" methods.
1104 if (!Method)
1105 Method = LookupPrivateClassMethod(Sel, Class);
1106
1107 if (Method && DiagnoseUseOfDecl(Method, Loc))
1108 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001109 }
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Douglas Gregor2725ca82010-04-21 19:57:20 +00001111 // Check the argument types and determine the result type.
1112 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001113 ExprValueKind VK = VK_RValue;
1114
Douglas Gregor2725ca82010-04-21 19:57:20 +00001115 unsigned NumArgs = ArgsIn.size();
1116 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001117 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1118 SuperLoc.isValid(), LBracLoc, RBracLoc,
1119 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001120 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001121
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001122 if (Method && !Method->getResultType()->isVoidType() &&
1123 RequireCompleteType(LBracLoc, Method->getResultType(),
1124 diag::err_illegal_message_expr_incomplete_type))
1125 return ExprError();
1126
Douglas Gregor2725ca82010-04-21 19:57:20 +00001127 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001128 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001129 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001130 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001131 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001132 ReceiverType, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001133 Method, makeArrayRef(Args, NumArgs),
1134 RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001135 else
John McCallf89e55a2010-11-18 06:31:45 +00001136 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001137 ReceiverTypeInfo, Sel, SelectorLocs,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001138 Method, makeArrayRef(Args, NumArgs),
1139 RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001140 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001141}
1142
Douglas Gregor2725ca82010-04-21 19:57:20 +00001143// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001144// ArgExprs is optional - if it is present, the number of expressions
1145// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001146ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001147 ParsedType Receiver,
1148 Selector Sel,
1149 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001150 ArrayRef<SourceLocation> SelectorLocs,
Douglas Gregor77328d12010-09-15 23:19:31 +00001151 SourceLocation RBracLoc,
1152 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001153 TypeSourceInfo *ReceiverTypeInfo;
1154 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1155 if (ReceiverType.isNull())
1156 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001157
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Douglas Gregor2725ca82010-04-21 19:57:20 +00001159 if (!ReceiverTypeInfo)
1160 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1161
1162 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001163 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001164 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001165}
1166
1167/// \brief Build an Objective-C instance message expression.
1168///
1169/// This routine takes care of both normal instance messages and
1170/// instance messages to the superclass instance.
1171///
1172/// \param Receiver The expression that computes the object that will
1173/// receive this message. This may be empty, in which case we are
1174/// sending to the superclass instance and \p SuperLoc must be a valid
1175/// source location.
1176///
1177/// \param ReceiverType The (static) type of the object receiving the
1178/// message. When a \p Receiver expression is provided, this is the
1179/// same type as that expression. For a superclass instance send, this
1180/// is a pointer to the type of the superclass.
1181///
1182/// \param SuperLoc The location of the "super" keyword in a
1183/// superclass instance message.
1184///
1185/// \param Sel The selector to which the message is being sent.
1186///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001187/// \param Method The method that this instance message is invoking, if
1188/// already known.
1189///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001190/// \param LBracLoc The location of the opening square bracket ']'.
1191///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001192/// \param RBrac The location of the closing square bracket ']'.
1193///
1194/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001195ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001196 QualType ReceiverType,
1197 SourceLocation SuperLoc,
1198 Selector Sel,
1199 ObjCMethodDecl *Method,
1200 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001201 ArrayRef<SourceLocation> SelectorLocs,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001202 SourceLocation RBracLoc,
1203 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001204 // The location of the receiver.
1205 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1206
1207 if (LBracLoc.isInvalid()) {
1208 Diag(Loc, diag::err_missing_open_square_message_send)
1209 << FixItHint::CreateInsertion(Loc, "[");
1210 LBracLoc = Loc;
1211 }
1212
Douglas Gregor2725ca82010-04-21 19:57:20 +00001213 // If we have a receiver expression, perform appropriate promotions
1214 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001215 if (Receiver) {
John McCall5acb0c92011-10-17 18:40:02 +00001216 if (Receiver->hasPlaceholderType()) {
Douglas Gregorf1d1ca52011-12-01 01:37:36 +00001217 ExprResult Result;
1218 if (Receiver->getType() == Context.UnknownAnyTy)
1219 Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType());
1220 else
1221 Result = CheckPlaceholderExpr(Receiver);
1222 if (Result.isInvalid()) return ExprError();
1223 Receiver = Result.take();
John McCall5acb0c92011-10-17 18:40:02 +00001224 }
1225
Douglas Gregor92e986e2010-04-22 16:44:27 +00001226 if (Receiver->isTypeDependent()) {
1227 // If the receiver is type-dependent, we can't type-check anything
1228 // at this point. Build a dependent expression.
1229 unsigned NumArgs = ArgsIn.size();
1230 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1231 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1232 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001233 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001234 SelectorLocs, /*Method=*/0,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001235 makeArrayRef(Args, NumArgs),
1236 RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001237 }
1238
Douglas Gregor2725ca82010-04-21 19:57:20 +00001239 // If necessary, apply function/array conversion to the receiver.
1240 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001241 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1242 if (Result.isInvalid())
1243 return ExprError();
1244 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001245 ReceiverType = Receiver->getType();
1246 }
1247
Douglas Gregorf49bb082010-04-22 17:01:48 +00001248 if (!Method) {
1249 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001250 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001251 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001252 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1253 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001254 SourceRange(LBracLoc, RBracLoc),
1255 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001256 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001257 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001258 SourceRange(LBracLoc, RBracLoc),
1259 receiverIsId);
Fariborz Jahanianb76a97e2011-12-07 00:30:00 +00001260 if (Method)
1261 DiagnoseAvailabilityOfDecl(Method, Loc, 0);
1262
Douglas Gregorf49bb082010-04-22 17:01:48 +00001263 } else if (ReceiverType->isObjCClassType() ||
1264 ReceiverType->isObjCQualifiedClassType()) {
1265 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001266 // We allow sending a message to a qualified Class ("Class<foo>"), which
1267 // is ok as long as one of the protocols implements the selector (if not, warn).
1268 if (const ObjCObjectPointerType *QClassTy
1269 = ReceiverType->getAsObjCQualifiedClassType()) {
1270 // Search protocols for class methods.
1271 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1272 if (!Method) {
1273 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1274 // warn if instance method found for a Class message.
1275 if (Method) {
1276 Diag(Loc, diag::warn_instance_method_on_class_found)
1277 << Method->getSelector() << Sel;
1278 Diag(Method->getLocation(), diag::note_method_declared_at);
1279 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001280 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001281 } else {
1282 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1283 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1284 // First check the public methods in the class interface.
1285 Method = ClassDecl->lookupClassMethod(Sel);
1286
1287 if (!Method)
1288 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1289 }
1290 if (Method && DiagnoseUseOfDecl(Method, Loc))
1291 return ExprError();
1292 }
1293 if (!Method) {
1294 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00001295 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001296 Method = LookupFactoryMethodInGlobalPool(Sel,
1297 SourceRange(LBracLoc, RBracLoc),
1298 true);
1299 if (!Method) {
1300 // If no class (factory) method was found, check if an _instance_
1301 // method of the same name exists in the root class only.
1302 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001303 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001304 true);
1305 if (Method)
1306 if (const ObjCInterfaceDecl *ID =
1307 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1308 if (ID->getSuperClass())
1309 Diag(Loc, diag::warn_root_inst_method_not_found)
1310 << Sel << SourceRange(LBracLoc, RBracLoc);
1311 }
1312 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001313 }
1314 }
1315 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001316 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001317 ObjCInterfaceDecl* ClassDecl = 0;
1318
1319 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1320 // long as one of the protocols implements the selector (if not, warn).
1321 if (const ObjCObjectPointerType *QIdTy
1322 = ReceiverType->getAsObjCQualifiedIdType()) {
1323 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001324 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1325 if (!Method)
1326 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001327 } else if (const ObjCObjectPointerType *OCIType
1328 = ReceiverType->getAsObjCInterfacePointerType()) {
1329 // We allow sending a message to a pointer to an interface (an object).
1330 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001331
Douglas Gregorb3029962011-11-14 22:10:01 +00001332 // Try to complete the type. Under ARC, this is a hard error from which
1333 // we don't try to recover.
1334 const ObjCInterfaceDecl *forwardClass = 0;
1335 if (RequireCompleteType(Loc, OCIType->getPointeeType(),
1336 getLangOptions().ObjCAutoRefCount
1337 ? PDiag(diag::err_arc_receiver_forward_instance)
1338 << (Receiver ? Receiver->getSourceRange()
1339 : SourceRange(SuperLoc))
1340 : PDiag())) {
1341 if (getLangOptions().ObjCAutoRefCount)
1342 return ExprError();
1343
1344 forwardClass = OCIType->getInterfaceDecl();
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00001345 Method = 0;
1346 } else {
1347 Method = ClassDecl->lookupInstanceMethod(Sel);
John McCallf85e1932011-06-15 23:02:42 +00001348 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001349
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001350 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001351 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001352 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1353
Douglas Gregorf49bb082010-04-22 17:01:48 +00001354 if (!Method) {
1355 // If we have implementations in scope, check "private" methods.
1356 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1357
John McCallf85e1932011-06-15 23:02:42 +00001358 if (!Method && getLangOptions().ObjCAutoRefCount) {
1359 Diag(Loc, diag::err_arc_may_not_respond)
1360 << OCIType->getPointeeType() << Sel;
1361 return ExprError();
1362 }
1363
Douglas Gregorc737acb2011-09-27 16:10:05 +00001364 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001365 // If we still haven't found a method, look in the global pool. This
1366 // behavior isn't very desirable, however we need it for GCC
1367 // compatibility. FIXME: should we deviate??
1368 if (OCIType->qual_empty()) {
1369 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001370 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001371 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001372 Diag(Loc, diag::warn_maynot_respond)
1373 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1374 }
1375 }
1376 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001377 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001378 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001379 } else if (!getLangOptions().ObjCAutoRefCount &&
1380 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001381 (ReceiverType->isPointerType() ||
1382 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001383 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001384 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001385 Diag(Loc, diag::warn_bad_receiver_type)
1386 << ReceiverType
1387 << Receiver->getSourceRange();
1388 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001389 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00001390 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00001391 else {
1392 // TODO: specialized warning on null receivers?
1393 bool IsNull = Receiver->isNullPointerConstant(Context,
1394 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001395 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1396 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001397 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001398 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00001399 } else {
John Wiegley429bb272011-04-08 18:41:53 +00001400 ExprResult ReceiverRes;
1401 if (getLangOptions().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00001402 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00001403 if (ReceiverRes.isUsable()) {
1404 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00001405 return BuildInstanceMessage(Receiver,
1406 ReceiverType,
1407 SuperLoc,
1408 Sel,
1409 Method,
1410 LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001411 SelectorLocs,
John Wiegley429bb272011-04-08 18:41:53 +00001412 RBracLoc,
1413 move(ArgsIn));
1414 } else {
1415 // Reject other random receiver types (e.g. structs).
1416 Diag(Loc, diag::err_bad_receiver_type)
1417 << ReceiverType << Receiver->getSourceRange();
1418 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001419 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001420 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001421 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001422 }
Mike Stump1eb44332009-09-09 15:08:12 +00001423
Douglas Gregor2725ca82010-04-21 19:57:20 +00001424 // Check the message arguments.
1425 unsigned NumArgs = ArgsIn.size();
1426 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1427 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001428 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001429 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1430 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001431 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1432 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001433 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001434 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001435
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001436 if (Method && !Method->getResultType()->isVoidType() &&
1437 RequireCompleteType(LBracLoc, Method->getResultType(),
1438 diag::err_illegal_message_expr_incomplete_type))
1439 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001440
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001441 SourceLocation SelLoc = SelectorLocs.front();
1442
John McCallf85e1932011-06-15 23:02:42 +00001443 // In ARC, forbid the user from sending messages to
1444 // retain/release/autorelease/dealloc/retainCount explicitly.
1445 if (getLangOptions().ObjCAutoRefCount) {
1446 ObjCMethodFamily family =
1447 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1448 switch (family) {
1449 case OMF_init:
1450 if (Method)
1451 checkInitMethod(Method, ReceiverType);
1452
1453 case OMF_None:
1454 case OMF_alloc:
1455 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00001456 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00001457 case OMF_mutableCopy:
1458 case OMF_new:
1459 case OMF_self:
1460 break;
1461
1462 case OMF_dealloc:
1463 case OMF_retain:
1464 case OMF_release:
1465 case OMF_autorelease:
1466 case OMF_retainCount:
1467 Diag(Loc, diag::err_arc_illegal_explicit_message)
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001468 << Sel << SelLoc;
John McCallf85e1932011-06-15 23:02:42 +00001469 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001470
1471 case OMF_performSelector:
1472 if (Method && NumArgs >= 1) {
1473 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1474 Selector ArgSel = SelExp->getSelector();
1475 ObjCMethodDecl *SelMethod =
1476 LookupInstanceMethodInGlobalPool(ArgSel,
1477 SelExp->getSourceRange());
1478 if (!SelMethod)
1479 SelMethod =
1480 LookupFactoryMethodInGlobalPool(ArgSel,
1481 SelExp->getSourceRange());
1482 if (SelMethod) {
1483 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1484 switch (SelFamily) {
1485 case OMF_alloc:
1486 case OMF_copy:
1487 case OMF_mutableCopy:
1488 case OMF_new:
1489 case OMF_self:
1490 case OMF_init:
1491 // Issue error, unless ns_returns_not_retained.
1492 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1493 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001494 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001495 diag::err_arc_perform_selector_retains);
1496 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1497 }
1498 break;
1499 default:
1500 // +0 call. OK. unless ns_returns_retained.
1501 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1502 // selector names a +1 method
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001503 Diag(SelLoc,
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001504 diag::err_arc_perform_selector_retains);
1505 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1506 }
1507 break;
1508 }
1509 }
1510 } else {
1511 // error (may leak).
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001512 Diag(SelLoc, diag::warn_arc_perform_selector_leaks);
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001513 Diag(Args[0]->getExprLoc(), diag::note_used_here);
1514 }
1515 }
1516 break;
John McCallf85e1932011-06-15 23:02:42 +00001517 }
1518 }
1519
Douglas Gregor2725ca82010-04-21 19:57:20 +00001520 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001521 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001522 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001523 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001524 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001525 ReceiverType, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001526 makeArrayRef(Args, NumArgs), RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001527 else
John McCallf89e55a2010-11-18 06:31:45 +00001528 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001529 Receiver, Sel, SelectorLocs, Method,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001530 makeArrayRef(Args, NumArgs), RBracLoc);
John McCallf85e1932011-06-15 23:02:42 +00001531
1532 if (getLangOptions().ObjCAutoRefCount) {
1533 // In ARC, annotate delegate init calls.
1534 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00001535 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00001536 // Only consider init calls *directly* in init implementations,
1537 // not within blocks.
1538 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1539 if (method && method->getMethodFamily() == OMF_init) {
1540 // The implicit assignment to self means we also don't want to
1541 // consume the result.
1542 Result->setDelegateInitCall(true);
1543 return Owned(Result);
1544 }
1545 }
1546
1547 // In ARC, check for message sends which are likely to introduce
1548 // retain cycles.
1549 checkRetainCycles(Result);
1550 }
1551
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001552 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001553}
1554
1555// ActOnInstanceMessage - used for both unary and keyword messages.
1556// ArgExprs is optional - if it is present, the number of expressions
1557// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001558ExprResult Sema::ActOnInstanceMessage(Scope *S,
1559 Expr *Receiver,
1560 Selector Sel,
1561 SourceLocation LBracLoc,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001562 ArrayRef<SourceLocation> SelectorLocs,
John McCall60d7b3a2010-08-24 06:29:42 +00001563 SourceLocation RBracLoc,
1564 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001565 if (!Receiver)
1566 return ExprError();
1567
John McCall9ae2f072010-08-23 23:25:46 +00001568 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001569 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidis95137622011-10-03 06:36:17 +00001570 LBracLoc, SelectorLocs, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001571}
Chris Lattnereca7be62008-04-07 05:30:13 +00001572
John McCallf85e1932011-06-15 23:02:42 +00001573enum ARCConversionTypeClass {
John McCall2cf031d2011-10-01 01:01:08 +00001574 /// int, void, struct A
John McCallf85e1932011-06-15 23:02:42 +00001575 ACTC_none,
John McCall2cf031d2011-10-01 01:01:08 +00001576
1577 /// id, void (^)()
John McCallf85e1932011-06-15 23:02:42 +00001578 ACTC_retainable,
John McCall2cf031d2011-10-01 01:01:08 +00001579
1580 /// id*, id***, void (^*)(),
1581 ACTC_indirectRetainable,
1582
1583 /// void* might be a normal C type, or it might a CF type.
1584 ACTC_voidPtr,
1585
1586 /// struct A*
1587 ACTC_coreFoundation
John McCallf85e1932011-06-15 23:02:42 +00001588};
John McCall2cf031d2011-10-01 01:01:08 +00001589static bool isAnyRetainable(ARCConversionTypeClass ACTC) {
1590 return (ACTC == ACTC_retainable ||
1591 ACTC == ACTC_coreFoundation ||
1592 ACTC == ACTC_voidPtr);
1593}
1594static bool isAnyCLike(ARCConversionTypeClass ACTC) {
1595 return ACTC == ACTC_none ||
1596 ACTC == ACTC_voidPtr ||
1597 ACTC == ACTC_coreFoundation;
1598}
1599
John McCallf85e1932011-06-15 23:02:42 +00001600static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
John McCall2cf031d2011-10-01 01:01:08 +00001601 bool isIndirect = false;
John McCallf85e1932011-06-15 23:02:42 +00001602
1603 // Ignore an outermost reference type.
John McCall2cf031d2011-10-01 01:01:08 +00001604 if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
John McCallf85e1932011-06-15 23:02:42 +00001605 type = ref->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00001606 isIndirect = true;
1607 }
John McCallf85e1932011-06-15 23:02:42 +00001608
1609 // Drill through pointers and arrays recursively.
1610 while (true) {
1611 if (const PointerType *ptr = type->getAs<PointerType>()) {
1612 type = ptr->getPointeeType();
John McCall2cf031d2011-10-01 01:01:08 +00001613
1614 // The first level of pointer may be the innermost pointer on a CF type.
1615 if (!isIndirect) {
1616 if (type->isVoidType()) return ACTC_voidPtr;
1617 if (type->isRecordType()) return ACTC_coreFoundation;
1618 }
John McCallf85e1932011-06-15 23:02:42 +00001619 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1620 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1621 } else {
1622 break;
1623 }
John McCall2cf031d2011-10-01 01:01:08 +00001624 isIndirect = true;
John McCallf85e1932011-06-15 23:02:42 +00001625 }
1626
John McCall2cf031d2011-10-01 01:01:08 +00001627 if (isIndirect) {
1628 if (type->isObjCARCBridgableType())
1629 return ACTC_indirectRetainable;
1630 return ACTC_none;
1631 }
1632
1633 if (type->isObjCARCBridgableType())
1634 return ACTC_retainable;
1635
1636 return ACTC_none;
John McCallf85e1932011-06-15 23:02:42 +00001637}
1638
1639namespace {
John McCall2cf031d2011-10-01 01:01:08 +00001640 /// A result from the cast checker.
1641 enum ACCResult {
1642 /// Cannot be casted.
1643 ACC_invalid,
1644
1645 /// Can be safely retained or not retained.
1646 ACC_bottom,
1647
1648 /// Can be casted at +0.
1649 ACC_plusZero,
1650
1651 /// Can be casted at +1.
1652 ACC_plusOne
1653 };
1654 ACCResult merge(ACCResult left, ACCResult right) {
1655 if (left == right) return left;
1656 if (left == ACC_bottom) return right;
1657 if (right == ACC_bottom) return left;
1658 return ACC_invalid;
1659 }
1660
1661 /// A checker which white-lists certain expressions whose conversion
1662 /// to or from retainable type would otherwise be forbidden in ARC.
1663 class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> {
1664 typedef StmtVisitor<ARCCastChecker, ACCResult> super;
1665
John McCallf85e1932011-06-15 23:02:42 +00001666 ASTContext &Context;
John McCall2cf031d2011-10-01 01:01:08 +00001667 ARCConversionTypeClass SourceClass;
1668 ARCConversionTypeClass TargetClass;
1669
1670 static bool isCFType(QualType type) {
1671 // Someday this can use ns_bridged. For now, it has to do this.
1672 return type->isCARCBridgableType();
John McCallf85e1932011-06-15 23:02:42 +00001673 }
John McCall2cf031d2011-10-01 01:01:08 +00001674
1675 public:
1676 ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source,
1677 ARCConversionTypeClass target)
1678 : Context(Context), SourceClass(source), TargetClass(target) {}
1679
1680 using super::Visit;
1681 ACCResult Visit(Expr *e) {
1682 return super::Visit(e->IgnoreParens());
1683 }
1684
1685 ACCResult VisitStmt(Stmt *s) {
1686 return ACC_invalid;
1687 }
1688
1689 /// Null pointer constants can be casted however you please.
1690 ACCResult VisitExpr(Expr *e) {
1691 if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1692 return ACC_bottom;
1693 return ACC_invalid;
1694 }
1695
1696 /// Objective-C string literals can be safely casted.
1697 ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) {
1698 // If we're casting to any retainable type, go ahead. Global
1699 // strings are immune to retains, so this is bottom.
1700 if (isAnyRetainable(TargetClass)) return ACC_bottom;
1701
1702 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00001703 }
1704
John McCall2cf031d2011-10-01 01:01:08 +00001705 /// Look through certain implicit and explicit casts.
1706 ACCResult VisitCastExpr(CastExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00001707 switch (e->getCastKind()) {
1708 case CK_NullToPointer:
John McCall2cf031d2011-10-01 01:01:08 +00001709 return ACC_bottom;
1710
John McCallf85e1932011-06-15 23:02:42 +00001711 case CK_NoOp:
1712 case CK_LValueToRValue:
1713 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00001714 case CK_CPointerToObjCPointerCast:
1715 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00001716 case CK_AnyPointerToBlockPointerCast:
1717 return Visit(e->getSubExpr());
John McCall2cf031d2011-10-01 01:01:08 +00001718
John McCallf85e1932011-06-15 23:02:42 +00001719 default:
John McCall2cf031d2011-10-01 01:01:08 +00001720 return ACC_invalid;
John McCallf85e1932011-06-15 23:02:42 +00001721 }
1722 }
John McCall2cf031d2011-10-01 01:01:08 +00001723
1724 /// Look through unary extension.
1725 ACCResult VisitUnaryExtension(UnaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00001726 return Visit(e->getSubExpr());
1727 }
John McCall2cf031d2011-10-01 01:01:08 +00001728
1729 /// Ignore the LHS of a comma operator.
1730 ACCResult VisitBinComma(BinaryOperator *e) {
John McCallf85e1932011-06-15 23:02:42 +00001731 return Visit(e->getRHS());
1732 }
John McCall2cf031d2011-10-01 01:01:08 +00001733
1734 /// Conditional operators are okay if both sides are okay.
1735 ACCResult VisitConditionalOperator(ConditionalOperator *e) {
1736 ACCResult left = Visit(e->getTrueExpr());
1737 if (left == ACC_invalid) return ACC_invalid;
1738 return merge(left, Visit(e->getFalseExpr()));
John McCallf85e1932011-06-15 23:02:42 +00001739 }
John McCall2cf031d2011-10-01 01:01:08 +00001740
John McCall4b9c2d22011-11-06 09:01:30 +00001741 /// Look through pseudo-objects.
1742 ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) {
1743 // If we're getting here, we should always have a result.
1744 return Visit(e->getResultExpr());
1745 }
1746
John McCall2cf031d2011-10-01 01:01:08 +00001747 /// Statement expressions are okay if their result expression is okay.
1748 ACCResult VisitStmtExpr(StmtExpr *e) {
John McCallf85e1932011-06-15 23:02:42 +00001749 return Visit(e->getSubStmt()->body_back());
1750 }
John McCallf85e1932011-06-15 23:02:42 +00001751
John McCall2cf031d2011-10-01 01:01:08 +00001752 /// Some declaration references are okay.
1753 ACCResult VisitDeclRefExpr(DeclRefExpr *e) {
1754 // References to global constants from system headers are okay.
1755 // These are things like 'kCFStringTransformToLatin'. They are
1756 // can also be assumed to be immune to retains.
1757 VarDecl *var = dyn_cast<VarDecl>(e->getDecl());
1758 if (isAnyRetainable(TargetClass) &&
1759 isAnyRetainable(SourceClass) &&
1760 var &&
1761 var->getStorageClass() == SC_Extern &&
1762 var->getType().isConstQualified() &&
1763 Context.getSourceManager().isInSystemHeader(var->getLocation())) {
1764 return ACC_bottom;
1765 }
1766
1767 // Nothing else.
1768 return ACC_invalid;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001769 }
John McCall2cf031d2011-10-01 01:01:08 +00001770
1771 /// Some calls are okay.
1772 ACCResult VisitCallExpr(CallExpr *e) {
1773 if (FunctionDecl *fn = e->getDirectCallee())
1774 if (ACCResult result = checkCallToFunction(fn))
1775 return result;
1776
1777 return super::VisitCallExpr(e);
1778 }
1779
1780 ACCResult checkCallToFunction(FunctionDecl *fn) {
1781 // Require a CF*Ref return type.
1782 if (!isCFType(fn->getResultType()))
1783 return ACC_invalid;
1784
1785 if (!isAnyRetainable(TargetClass))
1786 return ACC_invalid;
1787
1788 // Honor an explicit 'not retained' attribute.
1789 if (fn->hasAttr<CFReturnsNotRetainedAttr>())
1790 return ACC_plusZero;
1791
1792 // Honor an explicit 'retained' attribute, except that for
1793 // now we're not going to permit implicit handling of +1 results,
1794 // because it's a bit frightening.
1795 if (fn->hasAttr<CFReturnsRetainedAttr>())
1796 return ACC_invalid; // ACC_plusOne if we start accepting this
1797
1798 // Recognize this specific builtin function, which is used by CFSTR.
1799 unsigned builtinID = fn->getBuiltinID();
1800 if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString)
1801 return ACC_bottom;
1802
1803 // Otherwise, don't do anything implicit with an unaudited function.
1804 if (!fn->hasAttr<CFAuditedTransferAttr>())
1805 return ACC_invalid;
1806
1807 // Otherwise, it's +0 unless it follows the create convention.
1808 if (ento::coreFoundation::followsCreateRule(fn))
1809 return ACC_invalid; // ACC_plusOne if we start accepting this
1810
1811 return ACC_plusZero;
1812 }
1813
1814 ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) {
1815 return checkCallToMethod(e->getMethodDecl());
1816 }
1817
1818 ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) {
1819 ObjCMethodDecl *method;
1820 if (e->isExplicitProperty())
1821 method = e->getExplicitProperty()->getGetterMethodDecl();
1822 else
1823 method = e->getImplicitPropertyGetter();
1824 return checkCallToMethod(method);
1825 }
1826
1827 ACCResult checkCallToMethod(ObjCMethodDecl *method) {
1828 if (!method) return ACC_invalid;
1829
1830 // Check for message sends to functions returning CF types. We
1831 // just obey the Cocoa conventions with these, even though the
1832 // return type is CF.
1833 if (!isAnyRetainable(TargetClass) || !isCFType(method->getResultType()))
1834 return ACC_invalid;
1835
1836 // If the method is explicitly marked not-retained, it's +0.
1837 if (method->hasAttr<CFReturnsNotRetainedAttr>())
1838 return ACC_plusZero;
1839
1840 // If the method is explicitly marked as returning retained, or its
1841 // selector follows a +1 Cocoa convention, treat it as +1.
1842 if (method->hasAttr<CFReturnsRetainedAttr>())
1843 return ACC_plusOne;
1844
1845 switch (method->getSelector().getMethodFamily()) {
1846 case OMF_alloc:
1847 case OMF_copy:
1848 case OMF_mutableCopy:
1849 case OMF_new:
1850 return ACC_plusOne;
1851
1852 default:
1853 // Otherwise, treat it as +0.
1854 return ACC_plusZero;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001855 }
1856 }
John McCall2cf031d2011-10-01 01:01:08 +00001857 };
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001858}
1859
John McCall5acb0c92011-10-17 18:40:02 +00001860static void
1861diagnoseObjCARCConversion(Sema &S, SourceRange castRange,
1862 QualType castType, ARCConversionTypeClass castACTC,
1863 Expr *castExpr, ARCConversionTypeClass exprACTC,
1864 Sema::CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00001865 SourceLocation loc =
John McCall2cf031d2011-10-01 01:01:08 +00001866 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
John McCallf85e1932011-06-15 23:02:42 +00001867
John McCall5acb0c92011-10-17 18:40:02 +00001868 if (S.makeUnavailableInSystemHeader(loc,
John McCall2cf031d2011-10-01 01:01:08 +00001869 "converts between Objective-C and C pointers in -fobjc-arc"))
John McCallf85e1932011-06-15 23:02:42 +00001870 return;
John McCall5acb0c92011-10-17 18:40:02 +00001871
1872 QualType castExprType = castExpr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001873
John McCall71c482c2011-06-17 06:50:50 +00001874 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00001875 switch (exprACTC) {
John McCall2cf031d2011-10-01 01:01:08 +00001876 case ACTC_none:
1877 case ACTC_coreFoundation:
1878 case ACTC_voidPtr:
1879 srcKind = (castExprType->isPointerType() ? 1 : 0);
1880 break;
1881 case ACTC_retainable:
1882 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1883 break;
1884 case ACTC_indirectRetainable:
1885 srcKind = 4;
1886 break;
John McCallf85e1932011-06-15 23:02:42 +00001887 }
1888
John McCall5acb0c92011-10-17 18:40:02 +00001889 // Check whether this could be fixed with a bridge cast.
1890 SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin());
1891 SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc;
John McCallf85e1932011-06-15 23:02:42 +00001892
John McCall5acb0c92011-10-17 18:40:02 +00001893 // Bridge from an ARC type to a CF type.
1894 if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) {
1895 S.Diag(loc, diag::err_arc_cast_requires_bridge)
1896 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
1897 << 2 // of C pointer type
1898 << castExprType
1899 << unsigned(castType->isBlockPointerType()) // to ObjC|block type
1900 << castType
1901 << castRange
1902 << castExpr->getSourceRange();
1903
1904 S.Diag(noteLoc, diag::note_arc_bridge)
1905 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1906 FixItHint::CreateInsertion(afterLParen, "__bridge "));
1907 S.Diag(noteLoc, diag::note_arc_bridge_transfer)
1908 << castExprType
1909 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1910 FixItHint::CreateInsertion(afterLParen, "__bridge_transfer "));
1911
1912 return;
1913 }
1914
1915 // Bridge from a CF type to an ARC type.
1916 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) {
1917 S.Diag(loc, diag::err_arc_cast_requires_bridge)
1918 << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit
1919 << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type
1920 << castExprType
1921 << 2 // to C pointer type
1922 << castType
1923 << castRange
1924 << castExpr->getSourceRange();
1925
1926 S.Diag(noteLoc, diag::note_arc_bridge)
1927 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1928 FixItHint::CreateInsertion(afterLParen, "__bridge "));
1929 S.Diag(noteLoc, diag::note_arc_bridge_retained)
1930 << castType
1931 << (CCK != Sema::CCK_CStyleCast ? FixItHint() :
1932 FixItHint::CreateInsertion(afterLParen, "__bridge_retained "));
1933
1934 return;
John McCallf85e1932011-06-15 23:02:42 +00001935 }
1936
John McCall5acb0c92011-10-17 18:40:02 +00001937 S.Diag(loc, diag::err_arc_mismatched_cast)
1938 << (CCK != Sema::CCK_ImplicitConversion)
1939 << srcKind << castExprType << castType
John McCallf85e1932011-06-15 23:02:42 +00001940 << castRange << castExpr->getSourceRange();
1941}
1942
John McCall5acb0c92011-10-17 18:40:02 +00001943Sema::ARCConversionResult
1944Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
1945 Expr *&castExpr, CheckedConversionKind CCK) {
1946 QualType castExprType = castExpr->getType();
1947
1948 // For the purposes of the classification, we assume reference types
1949 // will bind to temporaries.
1950 QualType effCastType = castType;
1951 if (const ReferenceType *ref = castType->getAs<ReferenceType>())
1952 effCastType = ref->getPointeeType();
1953
1954 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1955 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType);
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00001956 if (exprACTC == castACTC) {
1957 // check for viablity and report error if casting an rvalue to a
1958 // life-time qualifier.
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00001959 if ((castACTC == ACTC_retainable) &&
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00001960 (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) &&
Fariborz Jahanianfc2eff52011-10-29 00:06:10 +00001961 (castType != castExprType)) {
1962 const Type *DT = castType.getTypePtr();
1963 QualType QDT = castType;
1964 // We desugar some types but not others. We ignore those
1965 // that cannot happen in a cast; i.e. auto, and those which
1966 // should not be de-sugared; i.e typedef.
1967 if (const ParenType *PT = dyn_cast<ParenType>(DT))
1968 QDT = PT->desugar();
1969 else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT))
1970 QDT = TP->desugar();
1971 else if (const AttributedType *AT = dyn_cast<AttributedType>(DT))
1972 QDT = AT->desugar();
1973 if (QDT != castType &&
1974 QDT.getObjCLifetime() != Qualifiers::OCL_None) {
1975 SourceLocation loc =
1976 (castRange.isValid() ? castRange.getBegin()
1977 : castExpr->getExprLoc());
1978 Diag(loc, diag::err_arc_nolifetime_behavior);
1979 }
Fariborz Jahanian6d09f012011-10-28 20:06:07 +00001980 }
1981 return ACR_okay;
1982 }
1983
John McCall5acb0c92011-10-17 18:40:02 +00001984 if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay;
1985
1986 // Allow all of these types to be cast to integer types (but not
1987 // vice-versa).
1988 if (castACTC == ACTC_none && castType->isIntegralType(Context))
1989 return ACR_okay;
1990
1991 // Allow casts between pointers to lifetime types (e.g., __strong id*)
1992 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1993 // must be explicit.
1994 if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr)
1995 return ACR_okay;
1996 if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr &&
1997 CCK != CCK_ImplicitConversion)
1998 return ACR_okay;
1999
2000 switch (ARCCastChecker(Context, exprACTC, castACTC).Visit(castExpr)) {
2001 // For invalid casts, fall through.
2002 case ACC_invalid:
2003 break;
2004
2005 // Do nothing for both bottom and +0.
2006 case ACC_bottom:
2007 case ACC_plusZero:
2008 return ACR_okay;
2009
2010 // If the result is +1, consume it here.
2011 case ACC_plusOne:
2012 castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(),
2013 CK_ARCConsumeObject, castExpr,
2014 0, VK_RValue);
2015 ExprNeedsCleanups = true;
2016 return ACR_okay;
2017 }
2018
2019 // If this is a non-implicit cast from id or block type to a
2020 // CoreFoundation type, delay complaining in case the cast is used
2021 // in an acceptable context.
2022 if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) &&
2023 CCK != CCK_ImplicitConversion)
2024 return ACR_unbridged;
2025
2026 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2027 castExpr, exprACTC, CCK);
2028 return ACR_okay;
2029}
2030
2031/// Given that we saw an expression with the ARCUnbridgedCastTy
2032/// placeholder type, complain bitterly.
2033void Sema::diagnoseARCUnbridgedCast(Expr *e) {
2034 // We expect the spurious ImplicitCastExpr to already have been stripped.
2035 assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2036 CastExpr *realCast = cast<CastExpr>(e->IgnoreParens());
2037
2038 SourceRange castRange;
2039 QualType castType;
2040 CheckedConversionKind CCK;
2041
2042 if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) {
2043 castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc());
2044 castType = cast->getTypeAsWritten();
2045 CCK = CCK_CStyleCast;
2046 } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) {
2047 castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange();
2048 castType = cast->getTypeAsWritten();
2049 CCK = CCK_OtherCast;
2050 } else {
2051 castType = cast->getType();
2052 CCK = CCK_ImplicitConversion;
2053 }
2054
2055 ARCConversionTypeClass castACTC =
2056 classifyTypeForARCConversion(castType.getNonReferenceType());
2057
2058 Expr *castExpr = realCast->getSubExpr();
2059 assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable);
2060
2061 diagnoseObjCARCConversion(*this, castRange, castType, castACTC,
2062 castExpr, ACTC_retainable, CCK);
2063}
2064
2065/// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast
2066/// type, remove the placeholder cast.
2067Expr *Sema::stripARCUnbridgedCast(Expr *e) {
2068 assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
2069
2070 if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) {
2071 Expr *sub = stripARCUnbridgedCast(pe->getSubExpr());
2072 return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub);
2073 } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) {
2074 assert(uo->getOpcode() == UO_Extension);
2075 Expr *sub = stripARCUnbridgedCast(uo->getSubExpr());
2076 return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(),
2077 sub->getValueKind(), sub->getObjectKind(),
2078 uo->getOperatorLoc());
2079 } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
2080 assert(!gse->isResultDependent());
2081
2082 unsigned n = gse->getNumAssocs();
2083 SmallVector<Expr*, 4> subExprs(n);
2084 SmallVector<TypeSourceInfo*, 4> subTypes(n);
2085 for (unsigned i = 0; i != n; ++i) {
2086 subTypes[i] = gse->getAssocTypeSourceInfo(i);
2087 Expr *sub = gse->getAssocExpr(i);
2088 if (i == gse->getResultIndex())
2089 sub = stripARCUnbridgedCast(sub);
2090 subExprs[i] = sub;
2091 }
2092
2093 return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(),
2094 gse->getControllingExpr(),
2095 subTypes.data(), subExprs.data(),
2096 n, gse->getDefaultLoc(),
2097 gse->getRParenLoc(),
2098 gse->containsUnexpandedParameterPack(),
2099 gse->getResultIndex());
2100 } else {
2101 assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!");
2102 return cast<ImplicitCastExpr>(e)->getSubExpr();
2103 }
2104}
2105
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00002106bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
2107 QualType exprType) {
2108 QualType canCastType =
2109 Context.getCanonicalType(castType).getUnqualifiedType();
2110 QualType canExprType =
2111 Context.getCanonicalType(exprType).getUnqualifiedType();
2112 if (isa<ObjCObjectPointerType>(canCastType) &&
2113 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
2114 canExprType->isObjCObjectPointerType()) {
2115 if (const ObjCObjectPointerType *ObjT =
2116 canExprType->getAs<ObjCObjectPointerType>())
2117 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
2118 return false;
2119 }
2120 return true;
2121}
2122
John McCall7e5e5f42011-07-07 06:58:02 +00002123/// Look for an ObjCReclaimReturnedObject cast and destroy it.
2124static Expr *maybeUndoReclaimObject(Expr *e) {
2125 // For now, we just undo operands that are *immediately* reclaim
2126 // expressions, which prevents the vast majority of potential
2127 // problems here. To catch them all, we'd need to rebuild arbitrary
2128 // value-propagating subexpressions --- we can't reliably rebuild
2129 // in-place because of expression sharing.
2130 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00002131 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00002132 return ice->getSubExpr();
2133
2134 return e;
2135}
2136
John McCallf85e1932011-06-15 23:02:42 +00002137ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
2138 ObjCBridgeCastKind Kind,
2139 SourceLocation BridgeKeywordLoc,
2140 TypeSourceInfo *TSInfo,
2141 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00002142 ExprResult SubResult = UsualUnaryConversions(SubExpr);
2143 if (SubResult.isInvalid()) return ExprError();
2144 SubExpr = SubResult.take();
2145
John McCallf85e1932011-06-15 23:02:42 +00002146 QualType T = TSInfo->getType();
2147 QualType FromType = SubExpr->getType();
2148
John McCall1d9b3b22011-09-09 05:25:32 +00002149 CastKind CK;
2150
John McCallf85e1932011-06-15 23:02:42 +00002151 bool MustConsume = false;
2152 if (T->isDependentType() || SubExpr->isTypeDependent()) {
2153 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00002154 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00002155 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
2156 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00002157 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
2158 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00002159 switch (Kind) {
2160 case OBC_Bridge:
2161 break;
2162
2163 case OBC_BridgeRetained:
2164 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2165 << 2
2166 << FromType
2167 << (T->isBlockPointerType()? 1 : 0)
2168 << T
2169 << SubExpr->getSourceRange()
2170 << Kind;
2171 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2172 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
2173 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
2174 << FromType
2175 << FixItHint::CreateReplacement(BridgeKeywordLoc,
2176 "__bridge_transfer ");
2177
2178 Kind = OBC_Bridge;
2179 break;
2180
2181 case OBC_BridgeTransfer:
2182 // We must consume the Objective-C object produced by the cast.
2183 MustConsume = true;
2184 break;
2185 }
2186 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
2187 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00002188 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00002189 switch (Kind) {
2190 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00002191 // Reclaiming a value that's going to be __bridge-casted to CF
2192 // is very dangerous, so we don't do it.
2193 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00002194 break;
2195
2196 case OBC_BridgeRetained:
2197 // Produce the object before casting it.
2198 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00002199 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00002200 SubExpr, 0, VK_RValue);
2201 break;
2202
2203 case OBC_BridgeTransfer:
2204 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
2205 << (FromType->isBlockPointerType()? 1 : 0)
2206 << FromType
2207 << 2
2208 << T
2209 << SubExpr->getSourceRange()
2210 << Kind;
2211
2212 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
2213 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
2214 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
2215 << T
2216 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
2217
2218 Kind = OBC_Bridge;
2219 break;
2220 }
2221 } else {
2222 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
2223 << FromType << T << Kind
2224 << SubExpr->getSourceRange()
2225 << TSInfo->getTypeLoc().getSourceRange();
2226 return ExprError();
2227 }
2228
John McCall1d9b3b22011-09-09 05:25:32 +00002229 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00002230 BridgeKeywordLoc,
2231 TSInfo, SubExpr);
2232
2233 if (MustConsume) {
2234 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00002235 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00002236 0, VK_RValue);
2237 }
2238
2239 return Result;
2240}
2241
2242ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
2243 SourceLocation LParenLoc,
2244 ObjCBridgeCastKind Kind,
2245 SourceLocation BridgeKeywordLoc,
2246 ParsedType Type,
2247 SourceLocation RParenLoc,
2248 Expr *SubExpr) {
2249 TypeSourceInfo *TSInfo = 0;
2250 QualType T = GetTypeFromParser(Type, &TSInfo);
2251 if (!TSInfo)
2252 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
2253 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
2254 SubExpr);
2255}