blob: 83b01f24a218df8075af8284ad12193265495d99 [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"
Chris Lattner85a932e2008-01-04 22:32:30 +000019#include "clang/AST/ASTContext.h"
20#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000021#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000022#include "clang/AST/StmtVisitor.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000023#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000024#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000025#include "clang/Lex/Preprocessor.h"
26
Chris Lattner85a932e2008-01-04 22:32:30 +000027using namespace clang;
John McCall26743b22011-02-03 09:00:02 +000028using namespace sema;
Chris Lattner85a932e2008-01-04 22:32:30 +000029
John McCallf312b1e2010-08-26 23:41:50 +000030ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
31 Expr **strings,
32 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000033 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
34
Chris Lattnerf4b136f2009-02-18 06:13:04 +000035 // Most ObjC strings are formed out of a single piece. However, we *can*
36 // have strings formed out of multiple @ strings with multiple pptokens in
37 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
38 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner39c28bb2009-02-18 06:48:40 +000039 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000040
Chris Lattnerf4b136f2009-02-18 06:13:04 +000041 // If we have a multi-part string, merge it all together.
42 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000043 // Concatenate objc strings.
Chris Lattner39c28bb2009-02-18 06:48:40 +000044 llvm::SmallString<128> StrBuf;
45 llvm::SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000046
Chris Lattner726e1682009-02-18 05:49:11 +000047 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000048 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000049
Chris Lattner39c28bb2009-02-18 06:48:40 +000050 // ObjC strings can't be wide.
Chris Lattnerf4b136f2009-02-18 06:13:04 +000051 if (S->isWide()) {
52 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
53 << S->getSourceRange();
54 return true;
55 }
Mike Stump1eb44332009-09-09 15:08:12 +000056
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +000057 // Append the string.
58 StrBuf += S->getString();
Mike Stump1eb44332009-09-09 15:08:12 +000059
Chris Lattner39c28bb2009-02-18 06:48:40 +000060 // Get the locations of the string tokens.
61 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattner85a932e2008-01-04 22:32:30 +000062 }
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattner39c28bb2009-02-18 06:48:40 +000064 // Create the aggregate string with the appropriate content and location
65 // information.
Jay Foad65aa6882011-06-21 15:13:30 +000066 S = StringLiteral::Create(Context, StrBuf,
Anders Carlsson3e2193c2011-04-14 00:40:03 +000067 /*Wide=*/false, /*Pascal=*/false,
Chris Lattner2085fd62009-02-18 06:40:38 +000068 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000069 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000070 }
Mike Stump1eb44332009-09-09 15:08:12 +000071
Chris Lattner69039812009-02-18 06:01:06 +000072 // Verify that this composite string is acceptable for ObjC strings.
73 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000074 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000075
76 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000077 // the NSString interface is seen in this translation unit. Note: We
78 // don't use NSConstantString, since the runtime team considers this
79 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000080 QualType Ty = Context.getObjCConstantStringInterface();
81 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000082 Ty = Context.getObjCObjectPointerType(Ty);
Fariborz Jahanian8a437762010-04-23 23:19:04 +000083 } else if (getLangOptions().NoConstantCFStrings) {
Fariborz Jahanian4c733072010-10-19 17:19:29 +000084 IdentifierInfo *NSIdent=0;
85 std::string StringClass(getLangOptions().ObjCConstantStringClass);
86
87 if (StringClass.empty())
88 NSIdent = &Context.Idents.get("NSConstantString");
89 else
90 NSIdent = &Context.Idents.get(StringClass);
91
Fariborz Jahanian8a437762010-04-23 23:19:04 +000092 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
93 LookupOrdinaryName);
94 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
95 Context.setObjCConstantStringInterface(StrIF);
96 Ty = Context.getObjCConstantStringInterface();
97 Ty = Context.getObjCObjectPointerType(Ty);
98 } else {
99 // If there is no NSConstantString interface defined then treat this
100 // as error and recover from it.
101 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
102 << S->getSourceRange();
103 Ty = Context.getObjCIdType();
104 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000105 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000106 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +0000107 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
108 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000109 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
110 Context.setObjCConstantStringInterface(StrIF);
111 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000112 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000113 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000114 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000115 // strings as untyped objects and let the runtime figure it out later.
116 Ty = Context.getObjCIdType();
117 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Chris Lattnerf4b136f2009-02-18 06:13:04 +0000120 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +0000121}
122
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000123ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000124 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000125 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000126 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000127 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000128 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000129 StrTy = Context.DependentTy;
130 else {
Fariborz Jahanian6c916152011-06-16 22:34:44 +0000131 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
132 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000133 if (RequireCompleteType(AtLoc, EncodedType,
134 PDiag(diag::err_incomplete_type_objc_at_encode)
135 << EncodedTypeInfo->getTypeLoc().getSourceRange()))
136 return ExprError();
137
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000138 std::string Str;
139 Context.getObjCEncodingForType(EncodedType, Str);
140
141 // The type of @encode is the same as the type of the corresponding string,
142 // which is an array type.
143 StrTy = Context.CharTy;
144 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000145 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000146 StrTy.addConst();
147 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
148 ArrayType::Normal, 0);
149 }
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Douglas Gregor81d34662010-04-20 15:39:42 +0000151 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000152}
153
John McCallf312b1e2010-08-26 23:41:50 +0000154ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
155 SourceLocation EncodeLoc,
156 SourceLocation LParenLoc,
157 ParsedType ty,
158 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000159 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000160 TypeSourceInfo *TInfo;
161 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
162 if (!TInfo)
163 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
164 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000165
Douglas Gregor81d34662010-04-20 15:39:42 +0000166 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000167}
168
John McCallf312b1e2010-08-26 23:41:50 +0000169ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
170 SourceLocation AtLoc,
171 SourceLocation SelLoc,
172 SourceLocation LParenLoc,
173 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000174 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000175 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000176 if (!Method)
177 Method = LookupFactoryMethodInGlobalPool(Sel,
178 SourceRange(LParenLoc, RParenLoc));
179 if (!Method)
180 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
181
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000182 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
183 = ReferencedSelectors.find(Sel);
184 if (Pos == ReferencedSelectors.end())
185 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
186
John McCallf85e1932011-06-15 23:02:42 +0000187 // In ARC, forbid the user from using @selector for
188 // retain/release/autorelease/dealloc/retainCount.
189 if (getLangOptions().ObjCAutoRefCount) {
190 switch (Sel.getMethodFamily()) {
191 case OMF_retain:
192 case OMF_release:
193 case OMF_autorelease:
194 case OMF_retainCount:
195 case OMF_dealloc:
196 Diag(AtLoc, diag::err_arc_illegal_selector) <<
197 Sel << SourceRange(LParenLoc, RParenLoc);
198 break;
199
200 case OMF_None:
201 case OMF_alloc:
202 case OMF_copy:
203 case OMF_init:
204 case OMF_mutableCopy:
205 case OMF_new:
206 case OMF_self:
207 break;
208 }
209 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000210 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000211 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000212}
213
John McCallf312b1e2010-08-26 23:41:50 +0000214ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
215 SourceLocation AtLoc,
216 SourceLocation ProtoLoc,
217 SourceLocation LParenLoc,
218 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000219 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000220 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000221 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000222 return true;
223 }
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000225 QualType Ty = Context.getObjCProtoType();
226 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000227 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000228 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000229 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000230}
231
John McCall26743b22011-02-03 09:00:02 +0000232/// Try to capture an implicit reference to 'self'.
233ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
234 // Ignore block scopes: we can capture through them.
235 DeclContext *DC = CurContext;
236 while (true) {
237 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
238 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
239 else break;
240 }
241
242 // If we're not in an ObjC method, error out. Note that, unlike the
243 // C++ case, we don't require an instance method --- class methods
244 // still have a 'self', and we really do still need to capture it!
245 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
246 if (!method)
247 return 0;
248
249 ImplicitParamDecl *self = method->getSelfDecl();
250 assert(self && "capturing 'self' in non-definition?");
251
252 // Mark that we're closing on 'this' in all the block scopes, if applicable.
253 for (unsigned idx = FunctionScopes.size() - 1;
254 isa<BlockScopeInfo>(FunctionScopes[idx]);
John McCall6b5a61b2011-02-07 10:33:21 +0000255 --idx) {
256 BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
257 unsigned &captureIndex = blockScope->CaptureMap[self];
258 if (captureIndex) break;
259
260 bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
261 blockScope->Captures.push_back(
262 BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
263 captureIndex = blockScope->Captures.size(); // +1
264 }
John McCall26743b22011-02-03 09:00:02 +0000265
266 return method;
267}
268
Douglas Gregor926df6c2011-06-11 01:09:30 +0000269QualType Sema::getMessageSendResultType(QualType ReceiverType,
270 ObjCMethodDecl *Method,
271 bool isClassMessage, bool isSuperMessage) {
272 assert(Method && "Must have a method");
273 if (!Method->hasRelatedResultType())
274 return Method->getSendResultType();
275
276 // If a method has a related return type:
277 // - if the method found is an instance method, but the message send
278 // was a class message send, T is the declared return type of the method
279 // found
280 if (Method->isInstanceMethod() && isClassMessage)
281 return Method->getSendResultType();
282
283 // - if the receiver is super, T is a pointer to the class of the
284 // enclosing method definition
285 if (isSuperMessage) {
286 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
287 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
288 return Context.getObjCObjectPointerType(
289 Context.getObjCInterfaceType(Class));
290 }
291
292 // - if the receiver is the name of a class U, T is a pointer to U
293 if (ReceiverType->getAs<ObjCInterfaceType>() ||
294 ReceiverType->isObjCQualifiedInterfaceType())
295 return Context.getObjCObjectPointerType(ReceiverType);
296 // - if the receiver is of type Class or qualified Class type,
297 // T is the declared return type of the method.
298 if (ReceiverType->isObjCClassType() ||
299 ReceiverType->isObjCQualifiedClassType())
300 return Method->getSendResultType();
301
302 // - if the receiver is id, qualified id, Class, or qualified Class, T
303 // is the receiver type, otherwise
304 // - T is the type of the receiver expression.
305 return ReceiverType;
306}
John McCall26743b22011-02-03 09:00:02 +0000307
Douglas Gregor926df6c2011-06-11 01:09:30 +0000308void Sema::EmitRelatedResultTypeNote(const Expr *E) {
309 E = E->IgnoreParenImpCasts();
310 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
311 if (!MsgSend)
312 return;
313
314 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
315 if (!Method)
316 return;
317
318 if (!Method->hasRelatedResultType())
319 return;
320
321 if (Context.hasSameUnqualifiedType(Method->getResultType()
322 .getNonReferenceType(),
323 MsgSend->getType()))
324 return;
325
326 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
327 << Method->isInstanceMethod() << Method->getSelector()
328 << MsgSend->getType();
329}
330
331bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
332 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000333 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000334 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000335 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000336 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000337 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000338 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000339 for (unsigned i = 0; i != NumArgs; i++) {
340 if (Args[i]->isTypeDependent())
341 continue;
342
John Wiegley429bb272011-04-08 18:41:53 +0000343 ExprResult Result = DefaultArgumentPromotion(Args[i]);
344 if (Result.isInvalid())
345 return true;
346 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000347 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000348
John McCallf85e1932011-06-15 23:02:42 +0000349 unsigned DiagID;
350 if (getLangOptions().ObjCAutoRefCount)
351 DiagID = diag::err_arc_method_not_found;
352 else
353 DiagID = isClassMessage ? diag::warn_class_method_not_found
354 : diag::warn_inst_method_not_found;
Chris Lattner077bf5e2008-11-24 03:33:13 +0000355 Diag(lbrac, DiagID)
356 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000357 ReturnType = Context.getObjCIdType();
John McCallf89e55a2010-11-18 06:31:45 +0000358 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000359 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000360 }
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Douglas Gregor926df6c2011-06-11 01:09:30 +0000362 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
363 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000364 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000366 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000367 // Method might have more arguments than selector indicates. This is due
368 // to addition of c-style arguments in method.
369 if (Method->param_size() > Sel.getNumArgs())
370 NumNamedArgs = Method->param_size();
371 // FIXME. This need be cleaned up.
372 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000373 Diag(lbrac, diag::err_typecheck_call_too_few_args)
374 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000375 return false;
376 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000377
Chris Lattner312531a2009-04-12 08:11:20 +0000378 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000379 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000380 // We can't do any type-checking on a type-dependent argument.
381 if (Args[i]->isTypeDependent())
382 continue;
383
Chris Lattner85a932e2008-01-04 22:32:30 +0000384 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000385
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000386 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000387 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000389 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
390 Param->getType(),
391 PDiag(diag::err_call_incomplete_argument)
392 << argExpr->getSourceRange()))
393 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000394
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000395 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
396 Param);
John McCall3fa5cae2010-10-26 07:05:15 +0000397 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000398 if (ArgE.isInvalid())
399 IsError = true;
400 else
401 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000402 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000403
404 // Promote additional arguments to variadic methods.
405 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000406 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
407 if (Args[i]->isTypeDependent())
408 continue;
409
John Wiegley429bb272011-04-08 18:41:53 +0000410 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
411 IsError |= Arg.isInvalid();
412 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000413 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000414 } else {
415 // Check for extra arguments to non-variadic methods.
416 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000417 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000418 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000419 << 2 /*method*/ << NumNamedArgs << NumArgs
420 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000421 << SourceRange(Args[NumNamedArgs]->getLocStart(),
422 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000423 }
424 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000425 // diagnose nonnull arguments.
426 for (specific_attr_iterator<NonNullAttr>
427 i = Method->specific_attr_begin<NonNullAttr>(),
428 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
429 CheckNonNullArguments(*i, Args, lbrac);
430 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000431
Douglas Gregor2725ca82010-04-21 19:57:20 +0000432 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000433 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000434}
435
John McCallf85e1932011-06-15 23:02:42 +0000436bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000437 // 'self' is objc 'self' in an objc method only.
Fariborz Jahanianb4602102011-03-28 16:23:34 +0000438 DeclContext *DC = CurContext;
439 while (isa<BlockDecl>(DC))
440 DC = DC->getParent();
441 if (DC && !isa<ObjCMethodDecl>(DC))
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000442 return false;
John McCallf85e1932011-06-15 23:02:42 +0000443 receiver = receiver->IgnoreParenLValueCasts();
444 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000445 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
446 return true;
447 return false;
448}
449
Steve Narofff1afaf62009-02-26 15:55:06 +0000450// Helper method for ActOnClassMethod/ActOnInstanceMethod.
451// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000452// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000453// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000454ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000455 ObjCInterfaceDecl *ClassDecl) {
456 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000457 // lookup in class and all superclasses
458 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000459 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000460 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Steve Naroff5609ec02009-03-08 18:56:13 +0000462 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000463 if (!Method)
464 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Steve Naroff5609ec02009-03-08 18:56:13 +0000466 // Before we give up, check if the selector is an instance method.
467 // But only in the root. This matches gcc's behaviour and what the
468 // runtime expects.
469 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000470 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000471 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000472 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000473 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000474 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
475 }
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Steve Naroff5609ec02009-03-08 18:56:13 +0000477 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000478 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000479 return Method;
480}
481
482ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
483 ObjCInterfaceDecl *ClassDecl) {
484 ObjCMethodDecl *Method = 0;
485 while (ClassDecl && !Method) {
486 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000487 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000488 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Steve Naroff5609ec02009-03-08 18:56:13 +0000490 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000491 if (!Method)
492 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000493 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000494 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000495 return Method;
496}
497
Fariborz Jahanian61478062011-03-09 20:18:06 +0000498/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
499/// list of a qualified objective pointer type.
500ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
501 const ObjCObjectPointerType *OPT,
502 bool Instance)
503{
504 ObjCMethodDecl *MD = 0;
505 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
506 E = OPT->qual_end(); I != E; ++I) {
507 ObjCProtocolDecl *PROTO = (*I);
508 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
509 return MD;
510 }
511 }
512 return 0;
513}
514
Chris Lattner7f816522010-04-11 07:45:24 +0000515/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
516/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000517ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000518HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000519 Expr *BaseExpr, DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000520 SourceLocation MemberLoc,
521 SourceLocation SuperLoc, QualType SuperType,
522 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000523 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
524 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000525
526 if (MemberName.getNameKind() != DeclarationName::Identifier) {
527 Diag(MemberLoc, diag::err_invalid_property_name)
528 << MemberName << QualType(OPT, 0);
529 return ExprError();
530 }
531
Chris Lattner7f816522010-04-11 07:45:24 +0000532 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
533
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000534 if (IFace->isForwardDecl()) {
535 Diag(MemberLoc, diag::err_property_not_found_forward_class)
536 << MemberName << QualType(OPT, 0);
537 Diag(IFace->getLocation(), diag::note_forward_class);
538 return ExprError();
539 }
Chris Lattner7f816522010-04-11 07:45:24 +0000540 // Search for a declared property first.
541 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
542 // Check whether we can reference this property.
543 if (DiagnoseUseOfDecl(PD, MemberLoc))
544 return ExprError();
545 QualType ResTy = PD->getType();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000546 ResTy = ResTy.getNonLValueExprType(Context);
Chris Lattner7f816522010-04-11 07:45:24 +0000547 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
548 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000549 if (Getter &&
550 (Getter->hasRelatedResultType()
551 || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
552 ResTy = getMessageSendResultType(QualType(OPT, 0), Getter, false,
553 Super);
554
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000555 if (Super)
556 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000557 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000558 MemberLoc,
559 SuperLoc, SuperType));
560 else
561 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000562 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000563 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000564 }
565 // Check protocols on qualified interfaces.
566 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
567 E = OPT->qual_end(); I != E; ++I)
568 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
569 // Check whether we can reference this property.
570 if (DiagnoseUseOfDecl(PD, MemberLoc))
571 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000572
573 QualType T = PD->getType();
574 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
575 T = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000576 if (Super)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000577 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000578 VK_LValue,
579 OK_ObjCProperty,
580 MemberLoc,
581 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000582 else
Douglas Gregor926df6c2011-06-11 01:09:30 +0000583 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000584 VK_LValue,
585 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000586 MemberLoc,
587 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000588 }
589 // If that failed, look for an "implicit" property by seeing if the nullary
590 // selector is implemented.
591
592 // FIXME: The logic for looking up nullary and unary selectors should be
593 // shared with the code in ActOnInstanceMessage.
594
595 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
596 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000597
598 // May be founf in property's qualified list.
599 if (!Getter)
600 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000601
602 // If this reference is in an @implementation, check for 'private' methods.
603 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000604 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000605
606 // Look through local category implementations associated with the class.
607 if (!Getter)
608 Getter = IFace->getCategoryInstanceMethod(Sel);
609 if (Getter) {
610 // Check if we can reference this property.
611 if (DiagnoseUseOfDecl(Getter, MemberLoc))
612 return ExprError();
613 }
614 // If we found a getter then this may be a valid dot-reference, we
615 // will look for the matching setter, in case it is needed.
616 Selector SetterSel =
617 SelectorTable::constructSetterName(PP.getIdentifierTable(),
618 PP.getSelectorTable(), Member);
619 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000620
621 // May be founf in property's qualified list.
622 if (!Setter)
623 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
624
Chris Lattner7f816522010-04-11 07:45:24 +0000625 if (!Setter) {
626 // If this reference is in an @implementation, also check for 'private'
627 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000628 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000629 }
630 // Look through local category implementations associated with the class.
631 if (!Setter)
632 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000633
Chris Lattner7f816522010-04-11 07:45:24 +0000634 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
635 return ExprError();
636
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000637 if (Getter || Setter) {
638 QualType PType;
639 if (Getter)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000640 PType = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000641 else {
642 ParmVarDecl *ArgDecl = *Setter->param_begin();
643 PType = ArgDecl->getType();
644 }
645
John McCall09431682010-11-18 19:01:18 +0000646 ExprValueKind VK = VK_LValue;
647 ExprObjectKind OK = OK_ObjCProperty;
648 if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
649 PType->isVoidType())
650 VK = VK_RValue, OK = OK_Ordinary;
651
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000652 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000653 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
654 PType, VK, OK,
655 MemberLoc,
656 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000657 else
John McCall12f78a62010-12-02 01:19:52 +0000658 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
659 PType, VK, OK,
660 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000661
Chris Lattner7f816522010-04-11 07:45:24 +0000662 }
663
664 // Attempt to correct for typos in property names.
665 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000666 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
Chris Lattner7f816522010-04-11 07:45:24 +0000667 Res.getAsSingle<ObjCPropertyDecl>()) {
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000668 DeclarationName TypoResult = Res.getLookupName();
Chris Lattner7f816522010-04-11 07:45:24 +0000669 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000670 << MemberName << QualType(OPT, 0) << TypoResult
671 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000672 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
673 Diag(Property->getLocation(), diag::note_previous_decl)
674 << Property->getDeclName();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000675 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc,
676 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000677 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000678 ObjCInterfaceDecl *ClassDeclared;
679 if (ObjCIvarDecl *Ivar =
680 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
681 QualType T = Ivar->getType();
682 if (const ObjCObjectPointerType * OBJPT =
683 T->getAsObjCInterfacePointerType()) {
684 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
685 if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
686 if (IFace->isForwardDecl()) {
687 Diag(MemberLoc, diag::err_property_not_as_forward_class)
Fariborz Jahanian2a96bf52011-02-17 17:30:05 +0000688 << MemberName << IFace;
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000689 Diag(IFace->getLocation(), diag::note_forward_class);
690 return ExprError();
691 }
692 }
693 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000694
Chris Lattner7f816522010-04-11 07:45:24 +0000695 Diag(MemberLoc, diag::err_property_not_found)
696 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000697 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000698 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000699 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000700 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000701}
702
703
704
John McCall60d7b3a2010-08-24 06:29:42 +0000705ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000706ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
707 IdentifierInfo &propertyName,
708 SourceLocation receiverNameLoc,
709 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000711 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000712 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
713 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000714
715 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000716 if (IFace == 0) {
717 // If the "receiver" is 'super' in a method, handle it as an expression-like
718 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000719 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000720 IsSuper = true;
721
John McCall26743b22011-02-03 09:00:02 +0000722 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000723 if (CurMethod->isInstanceMethod()) {
724 QualType T =
725 Context.getObjCInterfaceType(CurMethod->getClassInterface());
726 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000727
728 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000729 /*BaseExpr*/0, &propertyName,
730 propertyNameLoc,
731 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000732 }
Mike Stump1eb44332009-09-09 15:08:12 +0000733
Chris Lattnereb483eb2010-04-11 08:28:14 +0000734 // Otherwise, if this is a class method, try dispatching to our
735 // superclass.
736 IFace = CurMethod->getClassInterface()->getSuperClass();
737 }
John McCall26743b22011-02-03 09:00:02 +0000738 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000739
740 if (IFace == 0) {
741 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
742 return ExprError();
743 }
744 }
745
746 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000747 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000748 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000749
750 // If this reference is in an @implementation, check for 'private' methods.
751 if (!Getter)
752 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
753 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000754 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000755 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000756
757 if (Getter) {
758 // FIXME: refactor/share with ActOnMemberReference().
759 // Check if we can reference this property.
760 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
761 return ExprError();
762 }
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Steve Naroff61f72cb2009-03-09 21:12:44 +0000764 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000765 Selector SetterSel =
766 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000767 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000769 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000770 if (!Setter) {
771 // If this reference is in an @implementation, also check for 'private'
772 // methods.
773 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
774 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000775 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000776 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000777 }
778 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000779 if (!Setter)
780 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000781
782 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
783 return ExprError();
784
785 if (Getter || Setter) {
786 QualType PType;
787
John McCall09431682010-11-18 19:01:18 +0000788 ExprValueKind VK = VK_LValue;
789 if (Getter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000790 PType = getMessageSendResultType(Context.getObjCInterfaceType(IFace),
791 Getter, true,
792 receiverNamePtr->isStr("super"));
John McCall09431682010-11-18 19:01:18 +0000793 if (!getLangOptions().CPlusPlus &&
794 !PType.hasQualifiers() && PType->isVoidType())
795 VK = VK_RValue;
796 } else {
Steve Naroff61f72cb2009-03-09 21:12:44 +0000797 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
798 E = Setter->param_end(); PI != E; ++PI)
799 PType = (*PI)->getType();
John McCall09431682010-11-18 19:01:18 +0000800 VK = VK_LValue;
Steve Naroff61f72cb2009-03-09 21:12:44 +0000801 }
John McCall09431682010-11-18 19:01:18 +0000802
803 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
804
Douglas Gregor926df6c2011-06-11 01:09:30 +0000805 if (IsSuper)
806 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
807 PType, VK, OK,
808 propertyNameLoc,
809 receiverNameLoc,
810 Context.getObjCInterfaceType(IFace)));
811
John McCall12f78a62010-12-02 01:19:52 +0000812 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
813 PType, VK, OK,
814 propertyNameLoc,
815 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000816 }
817 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
818 << &propertyName << Context.getObjCInterfaceType(IFace));
819}
820
Douglas Gregor47bd5432010-04-14 02:46:37 +0000821Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000822 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000823 SourceLocation NameLoc,
824 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000825 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000826 ParsedType &ReceiverType) {
827 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000828
Douglas Gregor47bd5432010-04-14 02:46:37 +0000829 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000830 // messaging super. If the identifier is "super" and there is a
831 // trailing dot, it's an instance message.
832 if (IsSuper && S->isInObjcMethodScope())
833 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000834
835 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
836 LookupName(Result, S);
837
838 switch (Result.getResultKind()) {
839 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000840 // Normal name lookup didn't find anything. If we're in an
841 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000842 // FIXME: This is a hack. Ivar lookup should be part of normal
843 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000844 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
845 ObjCInterfaceDecl *ClassDeclared;
846 if (Method->getClassInterface()->lookupInstanceVariable(Name,
847 ClassDeclared))
848 return ObjCInstanceMessage;
849 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000850
Douglas Gregor47bd5432010-04-14 02:46:37 +0000851 // Break out; we'll perform typo correction below.
852 break;
853
854 case LookupResult::NotFoundInCurrentInstantiation:
855 case LookupResult::FoundOverloaded:
856 case LookupResult::FoundUnresolvedValue:
857 case LookupResult::Ambiguous:
858 Result.suppressDiagnostics();
859 return ObjCInstanceMessage;
860
861 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000862 // If the identifier is a class or not, and there is a trailing dot,
863 // it's an instance message.
864 if (HasTrailingDot)
865 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000866 // We found something. If it's a type, then we have a class
867 // message. Otherwise, it's an instance message.
868 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000869 QualType T;
870 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
871 T = Context.getObjCInterfaceType(Class);
872 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
873 T = Context.getTypeDeclType(Type);
874 else
875 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000876
Douglas Gregor1569f952010-04-21 20:38:13 +0000877 // We have a class message, and T is the type we're
878 // messaging. Build source-location information for it.
879 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000880 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000881 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000882 }
883 }
884
Douglas Gregoraaf87162010-04-14 20:04:41 +0000885 // Determine our typo-correction context.
886 CorrectTypoContext CTC = CTC_Expression;
887 if (ObjCMethodDecl *Method = getCurMethodDecl())
888 if (Method->getClassInterface() &&
889 Method->getClassInterface()->getSuperClass())
890 CTC = CTC_ObjCMessageReceiver;
891
892 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
893 if (Result.isSingleResult()) {
894 // If we found a declaration, correct when it refers to an Objective-C
895 // class.
896 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000897 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000898 Diag(NameLoc, diag::err_unknown_receiver_suggest)
899 << Name << Result.getLookupName()
900 << FixItHint::CreateReplacement(SourceRange(NameLoc),
901 ND->getNameAsString());
902 Diag(ND->getLocation(), diag::note_previous_decl)
903 << Corrected;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000904
Douglas Gregor1569f952010-04-21 20:38:13 +0000905 QualType T = Context.getObjCInterfaceType(Class);
906 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000907 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000908 return ObjCClassMessage;
909 }
910 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
911 Corrected.getAsIdentifierInfo()->isStr("super")) {
912 // If we've found the keyword "super", this is a send to super.
913 Diag(NameLoc, diag::err_unknown_receiver_suggest)
914 << Name << Corrected
915 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000916 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000917 }
918 }
919
920 // Fall back: let the parser try to parse it as an instance message.
921 return ObjCInstanceMessage;
922}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000923
John McCall60d7b3a2010-08-24 06:29:42 +0000924ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000925 SourceLocation SuperLoc,
926 Selector Sel,
927 SourceLocation LBracLoc,
928 SourceLocation SelectorLoc,
929 SourceLocation RBracLoc,
930 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000931 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000932 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000933 if (!Method) {
934 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
935 return ExprError();
936 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000937
Douglas Gregorf95861a2010-04-21 20:01:04 +0000938 ObjCInterfaceDecl *Class = Method->getClassInterface();
939 if (!Class) {
940 Diag(SuperLoc, diag::error_no_super_class_message)
941 << Method->getDeclName();
942 return ExprError();
943 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000944
Douglas Gregorf95861a2010-04-21 20:01:04 +0000945 ObjCInterfaceDecl *Super = Class->getSuperClass();
946 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000947 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000948 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
949 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000950 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000951 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000952
Douglas Gregorf95861a2010-04-21 20:01:04 +0000953 // We are in a method whose class has a superclass, so 'super'
954 // is acting as a keyword.
955 if (Method->isInstanceMethod()) {
956 // Since we are in an instance method, this is an instance
957 // message to the superclass instance.
958 QualType SuperTy = Context.getObjCInterfaceType(Super);
959 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +0000960 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000961 Sel, /*Method=*/0,
962 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000963 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000964
965 // Since we are in a class method, this is a class message to
966 // the superclass.
967 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
968 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000969 SuperLoc, Sel, /*Method=*/0,
970 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000971}
972
973/// \brief Build an Objective-C class message expression.
974///
975/// This routine takes care of both normal class messages and
976/// class messages to the superclass.
977///
978/// \param ReceiverTypeInfo Type source information that describes the
979/// receiver of this message. This may be NULL, in which case we are
980/// sending to the superclass and \p SuperLoc must be a valid source
981/// location.
982
983/// \param ReceiverType The type of the object receiving the
984/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
985/// type as that refers to. For a superclass send, this is the type of
986/// the superclass.
987///
988/// \param SuperLoc The location of the "super" keyword in a
989/// superclass message.
990///
991/// \param Sel The selector to which the message is being sent.
992///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000993/// \param Method The method that this class message is invoking, if
994/// already known.
995///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000996/// \param LBracLoc The location of the opening square bracket ']'.
997///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000998/// \param RBrac The location of the closing square bracket ']'.
999///
1000/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001001ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001002 QualType ReceiverType,
1003 SourceLocation SuperLoc,
1004 Selector Sel,
1005 ObjCMethodDecl *Method,
1006 SourceLocation LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001007 SourceLocation SelectorLoc,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001008 SourceLocation RBracLoc,
1009 MultiExprArg ArgsIn) {
1010 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001011 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001012 if (LBracLoc.isInvalid()) {
1013 Diag(Loc, diag::err_missing_open_square_message_send)
1014 << FixItHint::CreateInsertion(Loc, "[");
1015 LBracLoc = Loc;
1016 }
1017
Douglas Gregor92e986e2010-04-22 16:44:27 +00001018 if (ReceiverType->isDependentType()) {
1019 // If the receiver type is dependent, we can't type-check anything
1020 // at this point. Build a dependent expression.
1021 unsigned NumArgs = ArgsIn.size();
1022 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1023 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001024 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1025 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001026 Sel, SelectorLoc, /*Method=*/0,
Douglas Gregor92e986e2010-04-22 16:44:27 +00001027 Args, NumArgs, RBracLoc));
1028 }
Chris Lattner15faee12010-04-12 05:38:43 +00001029
Douglas Gregor2725ca82010-04-21 19:57:20 +00001030 // Find the class to which we are sending this message.
1031 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001032 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1033 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001034 Diag(Loc, diag::err_invalid_receiver_class_message)
1035 << ReceiverType;
1036 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001037 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001038 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian02b0d652011-03-08 19:12:46 +00001039 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001040 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001041 if (!Method) {
1042 if (Class->isForwardDecl()) {
John McCallf85e1932011-06-15 23:02:42 +00001043 if (getLangOptions().ObjCAutoRefCount) {
1044 Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
1045 } else {
1046 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1047 }
1048
Douglas Gregorf49bb082010-04-22 17:01:48 +00001049 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001050 Method = LookupFactoryMethodInGlobalPool(Sel,
1051 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001052 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001053 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1054 << Method->getDeclName();
1055 }
1056 if (!Method)
1057 Method = Class->lookupClassMethod(Sel);
1058
1059 // If we have an implementation in scope, check "private" methods.
1060 if (!Method)
1061 Method = LookupPrivateClassMethod(Sel, Class);
1062
1063 if (Method && DiagnoseUseOfDecl(Method, Loc))
1064 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001065 }
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Douglas Gregor2725ca82010-04-21 19:57:20 +00001067 // Check the argument types and determine the result type.
1068 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001069 ExprValueKind VK = VK_RValue;
1070
Douglas Gregor2725ca82010-04-21 19:57:20 +00001071 unsigned NumArgs = ArgsIn.size();
1072 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001073 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1074 SuperLoc.isValid(), LBracLoc, RBracLoc,
1075 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001076 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001077
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001078 if (Method && !Method->getResultType()->isVoidType() &&
1079 RequireCompleteType(LBracLoc, Method->getResultType(),
1080 diag::err_illegal_message_expr_incomplete_type))
1081 return ExprError();
1082
Douglas Gregor2725ca82010-04-21 19:57:20 +00001083 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001084 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001085 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001086 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001087 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001088 ReceiverType, Sel, SelectorLoc,
1089 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001090 else
John McCallf89e55a2010-11-18 06:31:45 +00001091 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001092 ReceiverTypeInfo, Sel, SelectorLoc,
1093 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001094 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001095}
1096
Douglas Gregor2725ca82010-04-21 19:57:20 +00001097// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001098// ArgExprs is optional - if it is present, the number of expressions
1099// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001100ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001101 ParsedType Receiver,
1102 Selector Sel,
1103 SourceLocation LBracLoc,
1104 SourceLocation SelectorLoc,
1105 SourceLocation RBracLoc,
1106 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001107 TypeSourceInfo *ReceiverTypeInfo;
1108 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1109 if (ReceiverType.isNull())
1110 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Douglas Gregor2725ca82010-04-21 19:57:20 +00001113 if (!ReceiverTypeInfo)
1114 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1115
1116 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001117 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001118 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001119}
1120
1121/// \brief Build an Objective-C instance message expression.
1122///
1123/// This routine takes care of both normal instance messages and
1124/// instance messages to the superclass instance.
1125///
1126/// \param Receiver The expression that computes the object that will
1127/// receive this message. This may be empty, in which case we are
1128/// sending to the superclass instance and \p SuperLoc must be a valid
1129/// source location.
1130///
1131/// \param ReceiverType The (static) type of the object receiving the
1132/// message. When a \p Receiver expression is provided, this is the
1133/// same type as that expression. For a superclass instance send, this
1134/// is a pointer to the type of the superclass.
1135///
1136/// \param SuperLoc The location of the "super" keyword in a
1137/// superclass instance message.
1138///
1139/// \param Sel The selector to which the message is being sent.
1140///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001141/// \param Method The method that this instance message is invoking, if
1142/// already known.
1143///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001144/// \param LBracLoc The location of the opening square bracket ']'.
1145///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001146/// \param RBrac The location of the closing square bracket ']'.
1147///
1148/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001149ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001150 QualType ReceiverType,
1151 SourceLocation SuperLoc,
1152 Selector Sel,
1153 ObjCMethodDecl *Method,
1154 SourceLocation LBracLoc,
1155 SourceLocation SelectorLoc,
1156 SourceLocation RBracLoc,
1157 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001158 // The location of the receiver.
1159 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1160
1161 if (LBracLoc.isInvalid()) {
1162 Diag(Loc, diag::err_missing_open_square_message_send)
1163 << FixItHint::CreateInsertion(Loc, "[");
1164 LBracLoc = Loc;
1165 }
1166
Douglas Gregor2725ca82010-04-21 19:57:20 +00001167 // If we have a receiver expression, perform appropriate promotions
1168 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001169 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001170 if (Receiver->isTypeDependent()) {
1171 // If the receiver is type-dependent, we can't type-check anything
1172 // at this point. Build a dependent expression.
1173 unsigned NumArgs = ArgsIn.size();
1174 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1175 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1176 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001177 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001178 SelectorLoc, /*Method=*/0,
1179 Args, NumArgs, RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001180 }
1181
Douglas Gregor2725ca82010-04-21 19:57:20 +00001182 // If necessary, apply function/array conversion to the receiver.
1183 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001184 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1185 if (Result.isInvalid())
1186 return ExprError();
1187 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001188 ReceiverType = Receiver->getType();
1189 }
1190
Douglas Gregorf49bb082010-04-22 17:01:48 +00001191 if (!Method) {
1192 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001193 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001194 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001195 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1196 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001197 SourceRange(LBracLoc, RBracLoc),
1198 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001199 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001200 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001201 SourceRange(LBracLoc, RBracLoc),
1202 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001203 } else if (ReceiverType->isObjCClassType() ||
1204 ReceiverType->isObjCQualifiedClassType()) {
1205 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001206 // We allow sending a message to a qualified Class ("Class<foo>"), which
1207 // is ok as long as one of the protocols implements the selector (if not, warn).
1208 if (const ObjCObjectPointerType *QClassTy
1209 = ReceiverType->getAsObjCQualifiedClassType()) {
1210 // Search protocols for class methods.
1211 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1212 if (!Method) {
1213 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1214 // warn if instance method found for a Class message.
1215 if (Method) {
1216 Diag(Loc, diag::warn_instance_method_on_class_found)
1217 << Method->getSelector() << Sel;
1218 Diag(Method->getLocation(), diag::note_method_declared_at);
1219 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001220 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001221 } else {
1222 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1223 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1224 // First check the public methods in the class interface.
1225 Method = ClassDecl->lookupClassMethod(Sel);
1226
1227 if (!Method)
1228 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1229 }
1230 if (Method && DiagnoseUseOfDecl(Method, Loc))
1231 return ExprError();
1232 }
1233 if (!Method) {
1234 // If not messaging 'self', look for any factory method named 'Sel'.
1235 if (!Receiver || !isSelfExpr(Receiver)) {
1236 Method = LookupFactoryMethodInGlobalPool(Sel,
1237 SourceRange(LBracLoc, RBracLoc),
1238 true);
1239 if (!Method) {
1240 // If no class (factory) method was found, check if an _instance_
1241 // method of the same name exists in the root class only.
1242 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001243 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001244 true);
1245 if (Method)
1246 if (const ObjCInterfaceDecl *ID =
1247 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1248 if (ID->getSuperClass())
1249 Diag(Loc, diag::warn_root_inst_method_not_found)
1250 << Sel << SourceRange(LBracLoc, RBracLoc);
1251 }
1252 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001253 }
1254 }
1255 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001256 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001257 ObjCInterfaceDecl* ClassDecl = 0;
1258
1259 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1260 // long as one of the protocols implements the selector (if not, warn).
1261 if (const ObjCObjectPointerType *QIdTy
1262 = ReceiverType->getAsObjCQualifiedIdType()) {
1263 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001264 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1265 if (!Method)
1266 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001267 } else if (const ObjCObjectPointerType *OCIType
1268 = ReceiverType->getAsObjCInterfacePointerType()) {
1269 // We allow sending a message to a pointer to an interface (an object).
1270 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001271
1272 if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCount) {
1273 Diag(Loc, diag::err_arc_receiver_forward_instance)
1274 << OCIType->getPointeeType()
1275 << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperLoc));
1276 return ExprError();
1277 }
1278
Douglas Gregorf49bb082010-04-22 17:01:48 +00001279 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1280 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +00001281 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001282 Method = ClassDecl->lookupInstanceMethod(Sel);
1283
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001284 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001285 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001286 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1287
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001288 const ObjCInterfaceDecl *forwardClass = 0;
Douglas Gregorf49bb082010-04-22 17:01:48 +00001289 if (!Method) {
1290 // If we have implementations in scope, check "private" methods.
1291 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1292
John McCallf85e1932011-06-15 23:02:42 +00001293 if (!Method && getLangOptions().ObjCAutoRefCount) {
1294 Diag(Loc, diag::err_arc_may_not_respond)
1295 << OCIType->getPointeeType() << Sel;
1296 return ExprError();
1297 }
1298
Douglas Gregorf49bb082010-04-22 17:01:48 +00001299 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1300 // If we still haven't found a method, look in the global pool. This
1301 // behavior isn't very desirable, however we need it for GCC
1302 // compatibility. FIXME: should we deviate??
1303 if (OCIType->qual_empty()) {
1304 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001305 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001306 if (OCIType->getInterfaceDecl()->isForwardDecl())
1307 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001308 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001309 Diag(Loc, diag::warn_maynot_respond)
1310 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1311 }
1312 }
1313 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001314 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001315 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001316 } else if (!getLangOptions().ObjCAutoRefCount &&
1317 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001318 (ReceiverType->isPointerType() ||
1319 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001320 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001321 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001322 Diag(Loc, diag::warn_bad_receiver_type)
1323 << ReceiverType
1324 << Receiver->getSourceRange();
1325 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001326 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1327 CK_BitCast).take();
John McCall404cd162010-11-13 01:35:44 +00001328 else {
1329 // TODO: specialized warning on null receivers?
1330 bool IsNull = Receiver->isNullPointerConstant(Context,
1331 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001332 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1333 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001334 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001335 ReceiverType = Receiver->getType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00001336 }
John Wiegley429bb272011-04-08 18:41:53 +00001337 else {
1338 ExprResult ReceiverRes;
1339 if (getLangOptions().CPlusPlus)
1340 ReceiverRes = PerformContextuallyConvertToObjCId(Receiver);
1341 if (ReceiverRes.isUsable()) {
1342 Receiver = ReceiverRes.take();
1343 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
1344 Receiver = ICE->getSubExpr();
1345 ReceiverType = Receiver->getType();
1346 }
1347 return BuildInstanceMessage(Receiver,
1348 ReceiverType,
1349 SuperLoc,
1350 Sel,
1351 Method,
1352 LBracLoc,
1353 SelectorLoc,
1354 RBracLoc,
1355 move(ArgsIn));
1356 } else {
1357 // Reject other random receiver types (e.g. structs).
1358 Diag(Loc, diag::err_bad_receiver_type)
1359 << ReceiverType << Receiver->getSourceRange();
1360 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001361 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001362 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001363 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001364 }
Mike Stump1eb44332009-09-09 15:08:12 +00001365
Douglas Gregor2725ca82010-04-21 19:57:20 +00001366 // Check the message arguments.
1367 unsigned NumArgs = ArgsIn.size();
1368 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1369 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001370 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001371 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1372 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001373 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1374 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001375 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001376 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001377
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001378 if (Method && !Method->getResultType()->isVoidType() &&
1379 RequireCompleteType(LBracLoc, Method->getResultType(),
1380 diag::err_illegal_message_expr_incomplete_type))
1381 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001382
John McCallf85e1932011-06-15 23:02:42 +00001383 // In ARC, forbid the user from sending messages to
1384 // retain/release/autorelease/dealloc/retainCount explicitly.
1385 if (getLangOptions().ObjCAutoRefCount) {
1386 ObjCMethodFamily family =
1387 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1388 switch (family) {
1389 case OMF_init:
1390 if (Method)
1391 checkInitMethod(Method, ReceiverType);
1392
1393 case OMF_None:
1394 case OMF_alloc:
1395 case OMF_copy:
1396 case OMF_mutableCopy:
1397 case OMF_new:
1398 case OMF_self:
1399 break;
1400
1401 case OMF_dealloc:
1402 case OMF_retain:
1403 case OMF_release:
1404 case OMF_autorelease:
1405 case OMF_retainCount:
1406 Diag(Loc, diag::err_arc_illegal_explicit_message)
1407 << Sel << SelectorLoc;
1408 break;
1409 }
1410 }
1411
Douglas Gregor2725ca82010-04-21 19:57:20 +00001412 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001413 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001414 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001415 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001416 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001417 ReceiverType, Sel, SelectorLoc, Method,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001418 Args, NumArgs, RBracLoc);
1419 else
John McCallf89e55a2010-11-18 06:31:45 +00001420 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001421 Receiver, Sel, SelectorLoc, Method,
1422 Args, NumArgs, RBracLoc);
John McCallf85e1932011-06-15 23:02:42 +00001423
1424 if (getLangOptions().ObjCAutoRefCount) {
1425 // In ARC, annotate delegate init calls.
1426 if (Result->getMethodFamily() == OMF_init &&
1427 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
1428 // Only consider init calls *directly* in init implementations,
1429 // not within blocks.
1430 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1431 if (method && method->getMethodFamily() == OMF_init) {
1432 // The implicit assignment to self means we also don't want to
1433 // consume the result.
1434 Result->setDelegateInitCall(true);
1435 return Owned(Result);
1436 }
1437 }
1438
1439 // In ARC, check for message sends which are likely to introduce
1440 // retain cycles.
1441 checkRetainCycles(Result);
1442 }
1443
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001444 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001445}
1446
1447// ActOnInstanceMessage - used for both unary and keyword messages.
1448// ArgExprs is optional - if it is present, the number of expressions
1449// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001450ExprResult Sema::ActOnInstanceMessage(Scope *S,
1451 Expr *Receiver,
1452 Selector Sel,
1453 SourceLocation LBracLoc,
1454 SourceLocation SelectorLoc,
1455 SourceLocation RBracLoc,
1456 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001457 if (!Receiver)
1458 return ExprError();
1459
John McCall9ae2f072010-08-23 23:25:46 +00001460 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001461 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001462 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001463}
Chris Lattnereca7be62008-04-07 05:30:13 +00001464
John McCallf85e1932011-06-15 23:02:42 +00001465enum ARCConversionTypeClass {
1466 ACTC_none,
1467 ACTC_retainable,
1468 ACTC_indirectRetainable
1469};
1470static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
1471 ARCConversionTypeClass ACTC = ACTC_retainable;
1472
1473 // Ignore an outermost reference type.
1474 if (const ReferenceType *ref = type->getAs<ReferenceType>())
1475 type = ref->getPointeeType();
1476
1477 // Drill through pointers and arrays recursively.
1478 while (true) {
1479 if (const PointerType *ptr = type->getAs<PointerType>()) {
1480 type = ptr->getPointeeType();
1481 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1482 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1483 } else {
1484 break;
1485 }
1486 ACTC = ACTC_indirectRetainable;
1487 }
1488
1489 if (!type->isObjCRetainableType()) return ACTC_none;
1490 return ACTC;
1491}
1492
1493namespace {
1494 /// Return true if the given expression can be reasonably converted
1495 /// between a retainable pointer type and a C pointer type.
1496 struct ARCCastChecker : StmtVisitor<ARCCastChecker, bool> {
1497 ASTContext &Context;
1498 ARCCastChecker(ASTContext &Context) : Context(Context) {}
1499 bool VisitStmt(Stmt *s) {
1500 return false;
1501 }
1502 bool VisitExpr(Expr *e) {
1503 return e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
1504 }
1505
1506 bool VisitParenExpr(ParenExpr *e) {
1507 return Visit(e->getSubExpr());
1508 }
1509 bool VisitCastExpr(CastExpr *e) {
1510 switch (e->getCastKind()) {
1511 case CK_NullToPointer:
1512 return true;
1513 case CK_NoOp:
1514 case CK_LValueToRValue:
1515 case CK_BitCast:
1516 case CK_AnyPointerToObjCPointerCast:
1517 case CK_AnyPointerToBlockPointerCast:
1518 return Visit(e->getSubExpr());
1519 default:
1520 return false;
1521 }
1522 }
1523 bool VisitUnaryExtension(UnaryOperator *e) {
1524 return Visit(e->getSubExpr());
1525 }
1526 bool VisitBinComma(BinaryOperator *e) {
1527 return Visit(e->getRHS());
1528 }
1529 bool VisitConditionalOperator(ConditionalOperator *e) {
1530 // Conditional operators are okay if both sides are okay.
1531 return Visit(e->getTrueExpr()) && Visit(e->getFalseExpr());
1532 }
1533 bool VisitObjCStringLiteral(ObjCStringLiteral *e) {
1534 // Always white-list Objective-C string literals.
1535 return true;
1536 }
1537 bool VisitStmtExpr(StmtExpr *e) {
1538 return Visit(e->getSubStmt()->body_back());
1539 }
1540 bool VisitDeclRefExpr(DeclRefExpr *e) {
1541 // White-list references to global extern strings from system
1542 // headers.
1543 if (VarDecl *var = dyn_cast<VarDecl>(e->getDecl()))
1544 if (var->getStorageClass() == SC_Extern &&
1545 var->getType().isConstQualified() &&
1546 Context.getSourceManager().isInSystemHeader(var->getLocation()))
1547 return true;
1548 return false;
1549 }
1550 };
1551}
1552
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001553bool
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001554Sema::ValidObjCARCNoBridgeCastExpr(Expr *&Exp, QualType castType) {
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001555 Expr *NewExp = Exp->IgnoreParenCasts();
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001556
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001557 if (!isa<ObjCMessageExpr>(NewExp) && !isa<ObjCPropertyRefExpr>(NewExp)
1558 && !isa<CallExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001559 return false;
1560 ObjCMethodDecl *method = 0;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001561 bool MethodReturnsPlusOne = false;
1562
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001563 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(NewExp)) {
1564 method = PRE->getExplicitProperty()->getGetterMethodDecl();
1565 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001566 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001567 method = ME->getMethodDecl();
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001568 else {
1569 CallExpr *CE = cast<CallExpr>(NewExp);
1570 Decl *CallDecl = CE->getCalleeDecl();
1571 if (!CallDecl)
1572 return false;
1573 if (CallDecl->hasAttr<CFReturnsNotRetainedAttr>())
1574 return true;
1575 MethodReturnsPlusOne = CallDecl->hasAttr<CFReturnsRetainedAttr>();
1576 if (!MethodReturnsPlusOne) {
1577 if (NamedDecl *ND = dyn_cast<NamedDecl>(CallDecl))
1578 if (const IdentifierInfo *Id = ND->getIdentifier())
1579 if (Id->isStr("__builtin___CFStringMakeConstantString"))
1580 return true;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001581 }
1582 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001583
1584 if (!MethodReturnsPlusOne) {
1585 if (!method)
1586 return false;
1587 if (method->hasAttr<CFReturnsNotRetainedAttr>())
1588 return true;
1589 MethodReturnsPlusOne = method->hasAttr<CFReturnsRetainedAttr>();
1590 if (!MethodReturnsPlusOne) {
1591 ObjCMethodFamily family = method->getSelector().getMethodFamily();
1592 switch (family) {
1593 case OMF_alloc:
1594 case OMF_copy:
1595 case OMF_mutableCopy:
1596 case OMF_new:
1597 MethodReturnsPlusOne = true;
1598 break;
1599 default:
1600 break;
1601 }
1602 }
1603 }
1604
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001605 if (MethodReturnsPlusOne) {
1606 TypeSourceInfo *TSInfo =
1607 Context.getTrivialTypeSourceInfo(castType, SourceLocation());
1608 ExprResult ExpRes = BuildObjCBridgedCast(SourceLocation(), OBC_BridgeTransfer,
1609 SourceLocation(), TSInfo, Exp);
1610 Exp = ExpRes.take();
1611 }
1612 return true;
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001613}
1614
John McCallf85e1932011-06-15 23:02:42 +00001615void
1616Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001617 Expr *&castExpr, CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00001618 QualType castExprType = castExpr->getType();
1619
1620 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1621 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
1622 if (exprACTC == castACTC) return;
1623 if (exprACTC && castType->isBooleanType()) return;
1624
1625 // Allow casts between pointers to lifetime types (e.g., __strong id*)
1626 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1627 // must be explicit.
1628 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
1629 if (const PointerType *CastExprPtr = castExprType->getAs<PointerType>()) {
1630 QualType CastPointee = CastPtr->getPointeeType();
1631 QualType CastExprPointee = CastExprPtr->getPointeeType();
1632 if ((CCK != CCK_ImplicitConversion &&
1633 CastPointee->isObjCIndirectLifetimeType() &&
1634 CastExprPointee->isVoidType()) ||
1635 (CastPointee->isVoidType() &&
1636 CastExprPointee->isObjCIndirectLifetimeType()))
1637 return;
1638 }
1639 }
1640
1641 if (ARCCastChecker(Context).Visit(castExpr))
1642 return;
1643
1644 SourceLocation loc =
1645 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
1646
1647 if (makeUnavailableInSystemHeader(loc,
1648 "converts between Objective-C and C pointers in -fobjc-arc"))
1649 return;
1650
John McCall71c482c2011-06-17 06:50:50 +00001651 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00001652 switch (exprACTC) {
1653 case ACTC_none:
1654 srcKind = (castExprType->isPointerType() ? 1 : 0);
1655 break;
1656 case ACTC_retainable:
1657 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1658 break;
1659 case ACTC_indirectRetainable:
1660 srcKind = 4;
1661 break;
1662 }
1663
1664 if (CCK == CCK_CStyleCast) {
1665 // Check whether this could be fixed with a bridge cast.
1666 SourceLocation AfterLParen = PP.getLocForEndOfToken(castRange.getBegin());
1667 SourceLocation NoteLoc = AfterLParen.isValid()? AfterLParen : loc;
1668
1669 if (castType->isObjCARCBridgableType() &&
1670 castExprType->isCARCBridgableType()) {
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001671 // explicit unbridged casts are allowed if the source of the cast is a
1672 // message sent to an objc method (or property access)
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001673 if (ValidObjCARCNoBridgeCastExpr(castExpr, castType))
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001674 return;
John McCallf85e1932011-06-15 23:02:42 +00001675 Diag(loc, diag::err_arc_cast_requires_bridge)
1676 << 2
1677 << castExprType
1678 << (castType->isBlockPointerType()? 1 : 0)
1679 << castType
1680 << castRange
1681 << castExpr->getSourceRange();
1682 Diag(NoteLoc, diag::note_arc_bridge)
1683 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1684 Diag(NoteLoc, diag::note_arc_bridge_transfer)
1685 << castExprType
1686 << FixItHint::CreateInsertion(AfterLParen, "__bridge_transfer ");
1687
1688 return;
1689 }
1690
1691 if (castType->isCARCBridgableType() &&
1692 castExprType->isObjCARCBridgableType()){
1693 Diag(loc, diag::err_arc_cast_requires_bridge)
1694 << (castExprType->isBlockPointerType()? 1 : 0)
1695 << castExprType
1696 << 2
1697 << castType
1698 << castRange
1699 << castExpr->getSourceRange();
1700
1701 Diag(NoteLoc, diag::note_arc_bridge)
1702 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1703 Diag(NoteLoc, diag::note_arc_bridge_retained)
1704 << castType
1705 << FixItHint::CreateInsertion(AfterLParen, "__bridge_retained ");
1706 return;
1707 }
1708 }
1709
1710 Diag(loc, diag::err_arc_mismatched_cast)
1711 << (CCK != CCK_ImplicitConversion) << srcKind << castExprType << castType
1712 << castRange << castExpr->getSourceRange();
1713}
1714
1715ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
1716 ObjCBridgeCastKind Kind,
1717 SourceLocation BridgeKeywordLoc,
1718 TypeSourceInfo *TSInfo,
1719 Expr *SubExpr) {
1720 QualType T = TSInfo->getType();
1721 QualType FromType = SubExpr->getType();
1722
1723 bool MustConsume = false;
1724 if (T->isDependentType() || SubExpr->isTypeDependent()) {
1725 // Okay: we'll build a dependent expression type.
1726 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
1727 // Casting CF -> id
1728 switch (Kind) {
1729 case OBC_Bridge:
1730 break;
1731
1732 case OBC_BridgeRetained:
1733 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1734 << 2
1735 << FromType
1736 << (T->isBlockPointerType()? 1 : 0)
1737 << T
1738 << SubExpr->getSourceRange()
1739 << Kind;
1740 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1741 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
1742 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
1743 << FromType
1744 << FixItHint::CreateReplacement(BridgeKeywordLoc,
1745 "__bridge_transfer ");
1746
1747 Kind = OBC_Bridge;
1748 break;
1749
1750 case OBC_BridgeTransfer:
1751 // We must consume the Objective-C object produced by the cast.
1752 MustConsume = true;
1753 break;
1754 }
1755 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
1756 // Okay: id -> CF
1757 switch (Kind) {
1758 case OBC_Bridge:
1759 break;
1760
1761 case OBC_BridgeRetained:
1762 // Produce the object before casting it.
1763 SubExpr = ImplicitCastExpr::Create(Context, FromType,
1764 CK_ObjCProduceObject,
1765 SubExpr, 0, VK_RValue);
1766 break;
1767
1768 case OBC_BridgeTransfer:
1769 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1770 << (FromType->isBlockPointerType()? 1 : 0)
1771 << FromType
1772 << 2
1773 << T
1774 << SubExpr->getSourceRange()
1775 << Kind;
1776
1777 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1778 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
1779 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
1780 << T
1781 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
1782
1783 Kind = OBC_Bridge;
1784 break;
1785 }
1786 } else {
1787 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
1788 << FromType << T << Kind
1789 << SubExpr->getSourceRange()
1790 << TSInfo->getTypeLoc().getSourceRange();
1791 return ExprError();
1792 }
1793
1794 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind,
1795 BridgeKeywordLoc,
1796 TSInfo, SubExpr);
1797
1798 if (MustConsume) {
1799 ExprNeedsCleanups = true;
1800 Result = ImplicitCastExpr::Create(Context, T, CK_ObjCConsumeObject, Result,
1801 0, VK_RValue);
1802 }
1803
1804 return Result;
1805}
1806
1807ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
1808 SourceLocation LParenLoc,
1809 ObjCBridgeCastKind Kind,
1810 SourceLocation BridgeKeywordLoc,
1811 ParsedType Type,
1812 SourceLocation RParenLoc,
1813 Expr *SubExpr) {
1814 TypeSourceInfo *TSInfo = 0;
1815 QualType T = GetTypeFromParser(Type, &TSInfo);
1816 if (!TSInfo)
1817 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
1818 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
1819 SubExpr);
1820}