blob: 402e54c0e80190f8525ea44801c3b289e6a21f11 [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;
Chris Lattner5f9e2722011-07-23 10:55:15 +000045 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
Douglas Gregor5cee1192011-07-27 05:40:30 +000050 // ObjC strings can't be wide or UTF.
51 if (!S->isAscii()) {
Chris Lattnerf4b136f2009-02-18 06:13:04 +000052 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,
Douglas Gregor5cee1192011-07-27 05:40:30 +000067 StringLiteral::Ascii, /*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;
Fariborz Jahanian4c91d892011-07-13 19:05:43 +0000181
182 if (!Method ||
183 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
184 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
185 = ReferencedSelectors.find(Sel);
186 if (Pos == ReferencedSelectors.end())
187 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
188 }
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000189
John McCallf85e1932011-06-15 23:02:42 +0000190 // In ARC, forbid the user from using @selector for
191 // retain/release/autorelease/dealloc/retainCount.
192 if (getLangOptions().ObjCAutoRefCount) {
193 switch (Sel.getMethodFamily()) {
194 case OMF_retain:
195 case OMF_release:
196 case OMF_autorelease:
197 case OMF_retainCount:
198 case OMF_dealloc:
199 Diag(AtLoc, diag::err_arc_illegal_selector) <<
200 Sel << SourceRange(LParenLoc, RParenLoc);
201 break;
202
203 case OMF_None:
204 case OMF_alloc:
205 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +0000206 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +0000207 case OMF_init:
208 case OMF_mutableCopy:
209 case OMF_new:
210 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +0000211 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +0000212 break;
213 }
214 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000215 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000216 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000217}
218
John McCallf312b1e2010-08-26 23:41:50 +0000219ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
220 SourceLocation AtLoc,
221 SourceLocation ProtoLoc,
222 SourceLocation LParenLoc,
223 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000224 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000225 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000226 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000227 return true;
228 }
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000230 QualType Ty = Context.getObjCProtoType();
231 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000232 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000233 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000234 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000235}
236
John McCall26743b22011-02-03 09:00:02 +0000237/// Try to capture an implicit reference to 'self'.
238ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
239 // Ignore block scopes: we can capture through them.
240 DeclContext *DC = CurContext;
241 while (true) {
242 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
243 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
244 else break;
245 }
246
247 // If we're not in an ObjC method, error out. Note that, unlike the
248 // C++ case, we don't require an instance method --- class methods
249 // still have a 'self', and we really do still need to capture it!
250 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
251 if (!method)
252 return 0;
253
254 ImplicitParamDecl *self = method->getSelfDecl();
255 assert(self && "capturing 'self' in non-definition?");
256
257 // Mark that we're closing on 'this' in all the block scopes, if applicable.
258 for (unsigned idx = FunctionScopes.size() - 1;
259 isa<BlockScopeInfo>(FunctionScopes[idx]);
John McCall6b5a61b2011-02-07 10:33:21 +0000260 --idx) {
261 BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
262 unsigned &captureIndex = blockScope->CaptureMap[self];
263 if (captureIndex) break;
264
265 bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
266 blockScope->Captures.push_back(
267 BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
268 captureIndex = blockScope->Captures.size(); // +1
269 }
John McCall26743b22011-02-03 09:00:02 +0000270
271 return method;
272}
273
Douglas Gregor926df6c2011-06-11 01:09:30 +0000274QualType Sema::getMessageSendResultType(QualType ReceiverType,
275 ObjCMethodDecl *Method,
276 bool isClassMessage, bool isSuperMessage) {
277 assert(Method && "Must have a method");
278 if (!Method->hasRelatedResultType())
279 return Method->getSendResultType();
280
281 // If a method has a related return type:
282 // - if the method found is an instance method, but the message send
283 // was a class message send, T is the declared return type of the method
284 // found
285 if (Method->isInstanceMethod() && isClassMessage)
286 return Method->getSendResultType();
287
288 // - if the receiver is super, T is a pointer to the class of the
289 // enclosing method definition
290 if (isSuperMessage) {
291 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
292 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
293 return Context.getObjCObjectPointerType(
294 Context.getObjCInterfaceType(Class));
295 }
296
297 // - if the receiver is the name of a class U, T is a pointer to U
298 if (ReceiverType->getAs<ObjCInterfaceType>() ||
299 ReceiverType->isObjCQualifiedInterfaceType())
300 return Context.getObjCObjectPointerType(ReceiverType);
301 // - if the receiver is of type Class or qualified Class type,
302 // T is the declared return type of the method.
303 if (ReceiverType->isObjCClassType() ||
304 ReceiverType->isObjCQualifiedClassType())
305 return Method->getSendResultType();
306
307 // - if the receiver is id, qualified id, Class, or qualified Class, T
308 // is the receiver type, otherwise
309 // - T is the type of the receiver expression.
310 return ReceiverType;
311}
John McCall26743b22011-02-03 09:00:02 +0000312
Douglas Gregor926df6c2011-06-11 01:09:30 +0000313void Sema::EmitRelatedResultTypeNote(const Expr *E) {
314 E = E->IgnoreParenImpCasts();
315 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
316 if (!MsgSend)
317 return;
318
319 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
320 if (!Method)
321 return;
322
323 if (!Method->hasRelatedResultType())
324 return;
325
326 if (Context.hasSameUnqualifiedType(Method->getResultType()
327 .getNonReferenceType(),
328 MsgSend->getType()))
329 return;
330
331 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
332 << Method->isInstanceMethod() << Method->getSelector()
333 << MsgSend->getType();
334}
335
336bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
337 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000338 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000339 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000340 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000341 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000342 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000343 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000344 for (unsigned i = 0; i != NumArgs; i++) {
345 if (Args[i]->isTypeDependent())
346 continue;
347
John Wiegley429bb272011-04-08 18:41:53 +0000348 ExprResult Result = DefaultArgumentPromotion(Args[i]);
349 if (Result.isInvalid())
350 return true;
351 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000352 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000353
John McCallf85e1932011-06-15 23:02:42 +0000354 unsigned DiagID;
355 if (getLangOptions().ObjCAutoRefCount)
356 DiagID = diag::err_arc_method_not_found;
357 else
358 DiagID = isClassMessage ? diag::warn_class_method_not_found
359 : diag::warn_inst_method_not_found;
Chris Lattner077bf5e2008-11-24 03:33:13 +0000360 Diag(lbrac, DiagID)
361 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +0000362
363 // In debuggers, we want to use __unknown_anytype for these
364 // results so that clients can cast them.
365 if (getLangOptions().DebuggerSupport) {
366 ReturnType = Context.UnknownAnyTy;
367 } else {
368 ReturnType = Context.getObjCIdType();
369 }
John McCallf89e55a2010-11-18 06:31:45 +0000370 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000371 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000372 }
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Douglas Gregor926df6c2011-06-11 01:09:30 +0000374 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
375 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000376 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000377
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000378 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000379 // Method might have more arguments than selector indicates. This is due
380 // to addition of c-style arguments in method.
381 if (Method->param_size() > Sel.getNumArgs())
382 NumNamedArgs = Method->param_size();
383 // FIXME. This need be cleaned up.
384 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000385 Diag(lbrac, diag::err_typecheck_call_too_few_args)
386 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000387 return false;
388 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000389
Chris Lattner312531a2009-04-12 08:11:20 +0000390 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000391 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000392 // We can't do any type-checking on a type-dependent argument.
393 if (Args[i]->isTypeDependent())
394 continue;
395
Chris Lattner85a932e2008-01-04 22:32:30 +0000396 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000397
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000398 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000399 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000401 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
402 Param->getType(),
403 PDiag(diag::err_call_incomplete_argument)
404 << argExpr->getSourceRange()))
405 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000406
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000407 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
408 Param);
John McCall3fa5cae2010-10-26 07:05:15 +0000409 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000410 if (ArgE.isInvalid())
411 IsError = true;
412 else
413 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000414 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000415
416 // Promote additional arguments to variadic methods.
417 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000418 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
419 if (Args[i]->isTypeDependent())
420 continue;
421
John Wiegley429bb272011-04-08 18:41:53 +0000422 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
423 IsError |= Arg.isInvalid();
424 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000425 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000426 } else {
427 // Check for extra arguments to non-variadic methods.
428 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000429 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000430 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000431 << 2 /*method*/ << NumNamedArgs << NumArgs
432 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000433 << SourceRange(Args[NumNamedArgs]->getLocStart(),
434 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000435 }
436 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000437 // diagnose nonnull arguments.
438 for (specific_attr_iterator<NonNullAttr>
439 i = Method->specific_attr_begin<NonNullAttr>(),
440 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
441 CheckNonNullArguments(*i, Args, lbrac);
442 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000443
Douglas Gregor2725ca82010-04-21 19:57:20 +0000444 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000445 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000446}
447
John McCallf85e1932011-06-15 23:02:42 +0000448bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000449 // 'self' is objc 'self' in an objc method only.
Fariborz Jahanianb4602102011-03-28 16:23:34 +0000450 DeclContext *DC = CurContext;
451 while (isa<BlockDecl>(DC))
452 DC = DC->getParent();
453 if (DC && !isa<ObjCMethodDecl>(DC))
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000454 return false;
John McCallf85e1932011-06-15 23:02:42 +0000455 receiver = receiver->IgnoreParenLValueCasts();
456 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000457 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
458 return true;
459 return false;
460}
461
Steve Narofff1afaf62009-02-26 15:55:06 +0000462// Helper method for ActOnClassMethod/ActOnInstanceMethod.
463// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000464// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000465// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000466ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000467 ObjCInterfaceDecl *ClassDecl) {
468 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000469 // lookup in class and all superclasses
470 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000471 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000472 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Steve Naroff5609ec02009-03-08 18:56:13 +0000474 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000475 if (!Method)
476 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Steve Naroff5609ec02009-03-08 18:56:13 +0000478 // Before we give up, check if the selector is an instance method.
479 // But only in the root. This matches gcc's behaviour and what the
480 // runtime expects.
481 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000482 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000483 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000484 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000485 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000486 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
487 }
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Steve Naroff5609ec02009-03-08 18:56:13 +0000489 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000490 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000491 return Method;
492}
493
494ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
495 ObjCInterfaceDecl *ClassDecl) {
496 ObjCMethodDecl *Method = 0;
497 while (ClassDecl && !Method) {
498 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000499 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000500 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000501
Steve Naroff5609ec02009-03-08 18:56:13 +0000502 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000503 if (!Method)
504 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000505 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000506 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000507 return Method;
508}
509
Fariborz Jahanian61478062011-03-09 20:18:06 +0000510/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
511/// list of a qualified objective pointer type.
512ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
513 const ObjCObjectPointerType *OPT,
514 bool Instance)
515{
516 ObjCMethodDecl *MD = 0;
517 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
518 E = OPT->qual_end(); I != E; ++I) {
519 ObjCProtocolDecl *PROTO = (*I);
520 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
521 return MD;
522 }
523 }
524 return 0;
525}
526
Chris Lattner7f816522010-04-11 07:45:24 +0000527/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
528/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000529ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000530HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000531 Expr *BaseExpr, SourceLocation OpLoc,
532 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000533 SourceLocation MemberLoc,
534 SourceLocation SuperLoc, QualType SuperType,
535 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000536 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
537 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000538
539 if (MemberName.getNameKind() != DeclarationName::Identifier) {
540 Diag(MemberLoc, diag::err_invalid_property_name)
541 << MemberName << QualType(OPT, 0);
542 return ExprError();
543 }
544
Chris Lattner7f816522010-04-11 07:45:24 +0000545 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
546
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000547 if (IFace->isForwardDecl()) {
548 Diag(MemberLoc, diag::err_property_not_found_forward_class)
549 << MemberName << QualType(OPT, 0);
550 Diag(IFace->getLocation(), diag::note_forward_class);
551 return ExprError();
552 }
Chris Lattner7f816522010-04-11 07:45:24 +0000553 // Search for a declared property first.
554 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
555 // Check whether we can reference this property.
556 if (DiagnoseUseOfDecl(PD, MemberLoc))
557 return ExprError();
558 QualType ResTy = PD->getType();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000559 ResTy = ResTy.getNonLValueExprType(Context);
Chris Lattner7f816522010-04-11 07:45:24 +0000560 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
561 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000562 if (Getter &&
563 (Getter->hasRelatedResultType()
564 || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
565 ResTy = getMessageSendResultType(QualType(OPT, 0), Getter, false,
566 Super);
567
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000568 if (Super)
569 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000570 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000571 MemberLoc,
572 SuperLoc, SuperType));
573 else
574 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000575 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000576 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000577 }
578 // Check protocols on qualified interfaces.
579 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
580 E = OPT->qual_end(); I != E; ++I)
581 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
582 // Check whether we can reference this property.
583 if (DiagnoseUseOfDecl(PD, MemberLoc))
584 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000585
586 QualType T = PD->getType();
587 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
588 T = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000589 if (Super)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000590 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000591 VK_LValue,
592 OK_ObjCProperty,
593 MemberLoc,
594 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000595 else
Douglas Gregor926df6c2011-06-11 01:09:30 +0000596 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000597 VK_LValue,
598 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000599 MemberLoc,
600 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000601 }
602 // If that failed, look for an "implicit" property by seeing if the nullary
603 // selector is implemented.
604
605 // FIXME: The logic for looking up nullary and unary selectors should be
606 // shared with the code in ActOnInstanceMessage.
607
608 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
609 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000610
611 // May be founf in property's qualified list.
612 if (!Getter)
613 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000614
615 // If this reference is in an @implementation, check for 'private' methods.
616 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000617 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000618
619 // Look through local category implementations associated with the class.
620 if (!Getter)
621 Getter = IFace->getCategoryInstanceMethod(Sel);
622 if (Getter) {
623 // Check if we can reference this property.
624 if (DiagnoseUseOfDecl(Getter, MemberLoc))
625 return ExprError();
626 }
627 // If we found a getter then this may be a valid dot-reference, we
628 // will look for the matching setter, in case it is needed.
629 Selector SetterSel =
630 SelectorTable::constructSetterName(PP.getIdentifierTable(),
631 PP.getSelectorTable(), Member);
632 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000633
634 // May be founf in property's qualified list.
635 if (!Setter)
636 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
637
Chris Lattner7f816522010-04-11 07:45:24 +0000638 if (!Setter) {
639 // If this reference is in an @implementation, also check for 'private'
640 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000641 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000642 }
643 // Look through local category implementations associated with the class.
644 if (!Setter)
645 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000646
Chris Lattner7f816522010-04-11 07:45:24 +0000647 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
648 return ExprError();
649
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000650 if (Getter || Setter) {
651 QualType PType;
652 if (Getter)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000653 PType = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000654 else {
655 ParmVarDecl *ArgDecl = *Setter->param_begin();
656 PType = ArgDecl->getType();
657 }
658
John McCall09431682010-11-18 19:01:18 +0000659 ExprValueKind VK = VK_LValue;
660 ExprObjectKind OK = OK_ObjCProperty;
661 if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
662 PType->isVoidType())
663 VK = VK_RValue, OK = OK_Ordinary;
664
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000665 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000666 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
667 PType, VK, OK,
668 MemberLoc,
669 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000670 else
John McCall12f78a62010-12-02 01:19:52 +0000671 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
672 PType, VK, OK,
673 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000674
Chris Lattner7f816522010-04-11 07:45:24 +0000675 }
676
677 // Attempt to correct for typos in property names.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000678 TypoCorrection Corrected = CorrectTypo(
679 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
680 NULL, IFace, false, CTC_NoKeywords, OPT);
681 if (ObjCPropertyDecl *Property =
682 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>()) {
683 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +0000684 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000685 << MemberName << QualType(OPT, 0) << TypoResult
686 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000687 Diag(Property->getLocation(), diag::note_previous_decl)
688 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000689 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
690 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000691 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000692 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000693 ObjCInterfaceDecl *ClassDeclared;
694 if (ObjCIvarDecl *Ivar =
695 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
696 QualType T = Ivar->getType();
697 if (const ObjCObjectPointerType * OBJPT =
698 T->getAsObjCInterfacePointerType()) {
699 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
700 if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
701 if (IFace->isForwardDecl()) {
702 Diag(MemberLoc, diag::err_property_not_as_forward_class)
Fariborz Jahanian2a96bf52011-02-17 17:30:05 +0000703 << MemberName << IFace;
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000704 Diag(IFace->getLocation(), diag::note_forward_class);
705 return ExprError();
706 }
707 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000708 Diag(MemberLoc,
709 diag::err_ivar_access_using_property_syntax_suggest)
710 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
711 << FixItHint::CreateReplacement(OpLoc, "->");
712 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000713 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000714
Chris Lattner7f816522010-04-11 07:45:24 +0000715 Diag(MemberLoc, diag::err_property_not_found)
716 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000717 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000718 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000719 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000720 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000721}
722
723
724
John McCall60d7b3a2010-08-24 06:29:42 +0000725ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000726ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
727 IdentifierInfo &propertyName,
728 SourceLocation receiverNameLoc,
729 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000730
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000731 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000732 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
733 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000734
735 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000736 if (IFace == 0) {
737 // If the "receiver" is 'super' in a method, handle it as an expression-like
738 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000739 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000740 IsSuper = true;
741
John McCall26743b22011-02-03 09:00:02 +0000742 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000743 if (CurMethod->isInstanceMethod()) {
744 QualType T =
745 Context.getObjCInterfaceType(CurMethod->getClassInterface());
746 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000747
748 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000749 /*BaseExpr*/0,
750 SourceLocation()/*OpLoc*/,
751 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000752 propertyNameLoc,
753 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000754 }
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Chris Lattnereb483eb2010-04-11 08:28:14 +0000756 // Otherwise, if this is a class method, try dispatching to our
757 // superclass.
758 IFace = CurMethod->getClassInterface()->getSuperClass();
759 }
John McCall26743b22011-02-03 09:00:02 +0000760 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000761
762 if (IFace == 0) {
763 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
764 return ExprError();
765 }
766 }
767
768 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000769 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000770 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000771
772 // If this reference is in an @implementation, check for 'private' methods.
773 if (!Getter)
774 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
775 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000776 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000777 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000778
779 if (Getter) {
780 // FIXME: refactor/share with ActOnMemberReference().
781 // Check if we can reference this property.
782 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
783 return ExprError();
784 }
Mike Stump1eb44332009-09-09 15:08:12 +0000785
Steve Naroff61f72cb2009-03-09 21:12:44 +0000786 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000787 Selector SetterSel =
788 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000789 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000791 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000792 if (!Setter) {
793 // If this reference is in an @implementation, also check for 'private'
794 // methods.
795 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
796 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000797 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000798 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000799 }
800 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000801 if (!Setter)
802 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000803
804 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
805 return ExprError();
806
807 if (Getter || Setter) {
808 QualType PType;
809
John McCall09431682010-11-18 19:01:18 +0000810 ExprValueKind VK = VK_LValue;
811 if (Getter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000812 PType = getMessageSendResultType(Context.getObjCInterfaceType(IFace),
813 Getter, true,
814 receiverNamePtr->isStr("super"));
John McCall09431682010-11-18 19:01:18 +0000815 if (!getLangOptions().CPlusPlus &&
816 !PType.hasQualifiers() && PType->isVoidType())
817 VK = VK_RValue;
818 } else {
Steve Naroff61f72cb2009-03-09 21:12:44 +0000819 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
820 E = Setter->param_end(); PI != E; ++PI)
821 PType = (*PI)->getType();
John McCall09431682010-11-18 19:01:18 +0000822 VK = VK_LValue;
Steve Naroff61f72cb2009-03-09 21:12:44 +0000823 }
John McCall09431682010-11-18 19:01:18 +0000824
825 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
826
Douglas Gregor926df6c2011-06-11 01:09:30 +0000827 if (IsSuper)
828 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
829 PType, VK, OK,
830 propertyNameLoc,
831 receiverNameLoc,
832 Context.getObjCInterfaceType(IFace)));
833
John McCall12f78a62010-12-02 01:19:52 +0000834 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
835 PType, VK, OK,
836 propertyNameLoc,
837 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000838 }
839 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
840 << &propertyName << Context.getObjCInterfaceType(IFace));
841}
842
Douglas Gregor47bd5432010-04-14 02:46:37 +0000843Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000844 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000845 SourceLocation NameLoc,
846 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000847 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000848 ParsedType &ReceiverType) {
849 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000850
Douglas Gregor47bd5432010-04-14 02:46:37 +0000851 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000852 // messaging super. If the identifier is "super" and there is a
853 // trailing dot, it's an instance message.
854 if (IsSuper && S->isInObjcMethodScope())
855 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000856
857 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
858 LookupName(Result, S);
859
860 switch (Result.getResultKind()) {
861 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000862 // Normal name lookup didn't find anything. If we're in an
863 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000864 // FIXME: This is a hack. Ivar lookup should be part of normal
865 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000866 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
867 ObjCInterfaceDecl *ClassDeclared;
868 if (Method->getClassInterface()->lookupInstanceVariable(Name,
869 ClassDeclared))
870 return ObjCInstanceMessage;
871 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000872
Douglas Gregor47bd5432010-04-14 02:46:37 +0000873 // Break out; we'll perform typo correction below.
874 break;
875
876 case LookupResult::NotFoundInCurrentInstantiation:
877 case LookupResult::FoundOverloaded:
878 case LookupResult::FoundUnresolvedValue:
879 case LookupResult::Ambiguous:
880 Result.suppressDiagnostics();
881 return ObjCInstanceMessage;
882
883 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000884 // If the identifier is a class or not, and there is a trailing dot,
885 // it's an instance message.
886 if (HasTrailingDot)
887 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000888 // We found something. If it's a type, then we have a class
889 // message. Otherwise, it's an instance message.
890 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000891 QualType T;
892 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
893 T = Context.getObjCInterfaceType(Class);
894 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
895 T = Context.getTypeDeclType(Type);
896 else
897 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000898
Douglas Gregor1569f952010-04-21 20:38:13 +0000899 // We have a class message, and T is the type we're
900 // messaging. Build source-location information for it.
901 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000902 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000903 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000904 }
905 }
906
Douglas Gregoraaf87162010-04-14 20:04:41 +0000907 // Determine our typo-correction context.
908 CorrectTypoContext CTC = CTC_Expression;
909 if (ObjCMethodDecl *Method = getCurMethodDecl())
910 if (Method->getClassInterface() &&
911 Method->getClassInterface()->getSuperClass())
912 CTC = CTC_ObjCMessageReceiver;
913
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000914 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
915 Result.getLookupKind(), S, NULL,
916 NULL, false, CTC)) {
917 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000918 // If we found a declaration, correct when it refers to an Objective-C
919 // class.
Douglas Gregor1569f952010-04-21 20:38:13 +0000920 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000921 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000922 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000923 << FixItHint::CreateReplacement(SourceRange(NameLoc),
924 ND->getNameAsString());
925 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000926 << Corrected.getCorrection();
Douglas Gregor47bd5432010-04-14 02:46:37 +0000927
Douglas Gregor1569f952010-04-21 20:38:13 +0000928 QualType T = Context.getObjCInterfaceType(Class);
929 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000930 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000931 return ObjCClassMessage;
932 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000933 } else if (Corrected.isKeyword() &&
934 Corrected.getCorrectionAsIdentifierInfo()->isStr("super")) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000935 // If we've found the keyword "super", this is a send to super.
936 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000937 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000938 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000939 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000940 }
941 }
942
943 // Fall back: let the parser try to parse it as an instance message.
944 return ObjCInstanceMessage;
945}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000946
John McCall60d7b3a2010-08-24 06:29:42 +0000947ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000948 SourceLocation SuperLoc,
949 Selector Sel,
950 SourceLocation LBracLoc,
951 SourceLocation SelectorLoc,
952 SourceLocation RBracLoc,
953 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000954 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000955 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000956 if (!Method) {
957 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
958 return ExprError();
959 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000960
Douglas Gregorf95861a2010-04-21 20:01:04 +0000961 ObjCInterfaceDecl *Class = Method->getClassInterface();
962 if (!Class) {
963 Diag(SuperLoc, diag::error_no_super_class_message)
964 << Method->getDeclName();
965 return ExprError();
966 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000967
Douglas Gregorf95861a2010-04-21 20:01:04 +0000968 ObjCInterfaceDecl *Super = Class->getSuperClass();
969 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000970 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000971 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
972 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000973 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000974 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000975
Douglas Gregorf95861a2010-04-21 20:01:04 +0000976 // We are in a method whose class has a superclass, so 'super'
977 // is acting as a keyword.
978 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +0000979 if (Sel.getMethodFamily() == OMF_dealloc)
980 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +0000981 if (Sel.getMethodFamily() == OMF_finalize)
982 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +0000983
Douglas Gregorf95861a2010-04-21 20:01:04 +0000984 // Since we are in an instance method, this is an instance
985 // message to the superclass instance.
986 QualType SuperTy = Context.getObjCInterfaceType(Super);
987 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +0000988 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000989 Sel, /*Method=*/0,
990 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000991 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000992
993 // Since we are in a class method, this is a class message to
994 // the superclass.
995 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
996 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000997 SuperLoc, Sel, /*Method=*/0,
998 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000999}
1000
1001/// \brief Build an Objective-C class message expression.
1002///
1003/// This routine takes care of both normal class messages and
1004/// class messages to the superclass.
1005///
1006/// \param ReceiverTypeInfo Type source information that describes the
1007/// receiver of this message. This may be NULL, in which case we are
1008/// sending to the superclass and \p SuperLoc must be a valid source
1009/// location.
1010
1011/// \param ReceiverType The type of the object receiving the
1012/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1013/// type as that refers to. For a superclass send, this is the type of
1014/// the superclass.
1015///
1016/// \param SuperLoc The location of the "super" keyword in a
1017/// superclass message.
1018///
1019/// \param Sel The selector to which the message is being sent.
1020///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001021/// \param Method The method that this class message is invoking, if
1022/// already known.
1023///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001024/// \param LBracLoc The location of the opening square bracket ']'.
1025///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001026/// \param RBrac The location of the closing square bracket ']'.
1027///
1028/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001029ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001030 QualType ReceiverType,
1031 SourceLocation SuperLoc,
1032 Selector Sel,
1033 ObjCMethodDecl *Method,
1034 SourceLocation LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001035 SourceLocation SelectorLoc,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001036 SourceLocation RBracLoc,
1037 MultiExprArg ArgsIn) {
1038 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001039 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001040 if (LBracLoc.isInvalid()) {
1041 Diag(Loc, diag::err_missing_open_square_message_send)
1042 << FixItHint::CreateInsertion(Loc, "[");
1043 LBracLoc = Loc;
1044 }
1045
Douglas Gregor92e986e2010-04-22 16:44:27 +00001046 if (ReceiverType->isDependentType()) {
1047 // If the receiver type is dependent, we can't type-check anything
1048 // at this point. Build a dependent expression.
1049 unsigned NumArgs = ArgsIn.size();
1050 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1051 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001052 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1053 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001054 Sel, SelectorLoc, /*Method=*/0,
Douglas Gregor92e986e2010-04-22 16:44:27 +00001055 Args, NumArgs, RBracLoc));
1056 }
Chris Lattner15faee12010-04-12 05:38:43 +00001057
Douglas Gregor2725ca82010-04-21 19:57:20 +00001058 // Find the class to which we are sending this message.
1059 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001060 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1061 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001062 Diag(Loc, diag::err_invalid_receiver_class_message)
1063 << ReceiverType;
1064 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001065 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001066 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian02b0d652011-03-08 19:12:46 +00001067 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001068 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001069 if (!Method) {
1070 if (Class->isForwardDecl()) {
John McCallf85e1932011-06-15 23:02:42 +00001071 if (getLangOptions().ObjCAutoRefCount) {
1072 Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
1073 } else {
1074 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1075 }
1076
Douglas Gregorf49bb082010-04-22 17:01:48 +00001077 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001078 Method = LookupFactoryMethodInGlobalPool(Sel,
1079 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001080 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001081 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1082 << Method->getDeclName();
1083 }
1084 if (!Method)
1085 Method = Class->lookupClassMethod(Sel);
1086
1087 // If we have an implementation in scope, check "private" methods.
1088 if (!Method)
1089 Method = LookupPrivateClassMethod(Sel, Class);
1090
1091 if (Method && DiagnoseUseOfDecl(Method, Loc))
1092 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001093 }
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Douglas Gregor2725ca82010-04-21 19:57:20 +00001095 // Check the argument types and determine the result type.
1096 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001097 ExprValueKind VK = VK_RValue;
1098
Douglas Gregor2725ca82010-04-21 19:57:20 +00001099 unsigned NumArgs = ArgsIn.size();
1100 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001101 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1102 SuperLoc.isValid(), LBracLoc, RBracLoc,
1103 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001104 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001105
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001106 if (Method && !Method->getResultType()->isVoidType() &&
1107 RequireCompleteType(LBracLoc, Method->getResultType(),
1108 diag::err_illegal_message_expr_incomplete_type))
1109 return ExprError();
1110
Douglas Gregor2725ca82010-04-21 19:57:20 +00001111 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001112 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001113 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001114 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001115 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001116 ReceiverType, Sel, SelectorLoc,
1117 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001118 else
John McCallf89e55a2010-11-18 06:31:45 +00001119 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001120 ReceiverTypeInfo, Sel, SelectorLoc,
1121 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001122 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001123}
1124
Douglas Gregor2725ca82010-04-21 19:57:20 +00001125// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001126// ArgExprs is optional - if it is present, the number of expressions
1127// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001128ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001129 ParsedType Receiver,
1130 Selector Sel,
1131 SourceLocation LBracLoc,
1132 SourceLocation SelectorLoc,
1133 SourceLocation RBracLoc,
1134 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001135 TypeSourceInfo *ReceiverTypeInfo;
1136 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1137 if (ReceiverType.isNull())
1138 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001139
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Douglas Gregor2725ca82010-04-21 19:57:20 +00001141 if (!ReceiverTypeInfo)
1142 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1143
1144 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001145 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001146 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001147}
1148
1149/// \brief Build an Objective-C instance message expression.
1150///
1151/// This routine takes care of both normal instance messages and
1152/// instance messages to the superclass instance.
1153///
1154/// \param Receiver The expression that computes the object that will
1155/// receive this message. This may be empty, in which case we are
1156/// sending to the superclass instance and \p SuperLoc must be a valid
1157/// source location.
1158///
1159/// \param ReceiverType The (static) type of the object receiving the
1160/// message. When a \p Receiver expression is provided, this is the
1161/// same type as that expression. For a superclass instance send, this
1162/// is a pointer to the type of the superclass.
1163///
1164/// \param SuperLoc The location of the "super" keyword in a
1165/// superclass instance message.
1166///
1167/// \param Sel The selector to which the message is being sent.
1168///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001169/// \param Method The method that this instance message is invoking, if
1170/// already known.
1171///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001172/// \param LBracLoc The location of the opening square bracket ']'.
1173///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001174/// \param RBrac The location of the closing square bracket ']'.
1175///
1176/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001177ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001178 QualType ReceiverType,
1179 SourceLocation SuperLoc,
1180 Selector Sel,
1181 ObjCMethodDecl *Method,
1182 SourceLocation LBracLoc,
1183 SourceLocation SelectorLoc,
1184 SourceLocation RBracLoc,
1185 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001186 // The location of the receiver.
1187 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1188
1189 if (LBracLoc.isInvalid()) {
1190 Diag(Loc, diag::err_missing_open_square_message_send)
1191 << FixItHint::CreateInsertion(Loc, "[");
1192 LBracLoc = Loc;
1193 }
1194
Douglas Gregor2725ca82010-04-21 19:57:20 +00001195 // If we have a receiver expression, perform appropriate promotions
1196 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001197 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001198 if (Receiver->isTypeDependent()) {
1199 // If the receiver is type-dependent, we can't type-check anything
1200 // at this point. Build a dependent expression.
1201 unsigned NumArgs = ArgsIn.size();
1202 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1203 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1204 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001205 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001206 SelectorLoc, /*Method=*/0,
1207 Args, NumArgs, RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001208 }
1209
Douglas Gregor2725ca82010-04-21 19:57:20 +00001210 // If necessary, apply function/array conversion to the receiver.
1211 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001212 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1213 if (Result.isInvalid())
1214 return ExprError();
1215 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001216 ReceiverType = Receiver->getType();
1217 }
1218
Douglas Gregorf49bb082010-04-22 17:01:48 +00001219 if (!Method) {
1220 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001221 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001222 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001223 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1224 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001225 SourceRange(LBracLoc, RBracLoc),
1226 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001227 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001228 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001229 SourceRange(LBracLoc, RBracLoc),
1230 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001231 } else if (ReceiverType->isObjCClassType() ||
1232 ReceiverType->isObjCQualifiedClassType()) {
1233 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001234 // We allow sending a message to a qualified Class ("Class<foo>"), which
1235 // is ok as long as one of the protocols implements the selector (if not, warn).
1236 if (const ObjCObjectPointerType *QClassTy
1237 = ReceiverType->getAsObjCQualifiedClassType()) {
1238 // Search protocols for class methods.
1239 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1240 if (!Method) {
1241 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1242 // warn if instance method found for a Class message.
1243 if (Method) {
1244 Diag(Loc, diag::warn_instance_method_on_class_found)
1245 << Method->getSelector() << Sel;
1246 Diag(Method->getLocation(), diag::note_method_declared_at);
1247 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001248 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001249 } else {
1250 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1251 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1252 // First check the public methods in the class interface.
1253 Method = ClassDecl->lookupClassMethod(Sel);
1254
1255 if (!Method)
1256 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1257 }
1258 if (Method && DiagnoseUseOfDecl(Method, Loc))
1259 return ExprError();
1260 }
1261 if (!Method) {
1262 // If not messaging 'self', look for any factory method named 'Sel'.
1263 if (!Receiver || !isSelfExpr(Receiver)) {
1264 Method = LookupFactoryMethodInGlobalPool(Sel,
1265 SourceRange(LBracLoc, RBracLoc),
1266 true);
1267 if (!Method) {
1268 // If no class (factory) method was found, check if an _instance_
1269 // method of the same name exists in the root class only.
1270 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001271 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001272 true);
1273 if (Method)
1274 if (const ObjCInterfaceDecl *ID =
1275 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1276 if (ID->getSuperClass())
1277 Diag(Loc, diag::warn_root_inst_method_not_found)
1278 << Sel << SourceRange(LBracLoc, RBracLoc);
1279 }
1280 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001281 }
1282 }
1283 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001284 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001285 ObjCInterfaceDecl* ClassDecl = 0;
1286
1287 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1288 // long as one of the protocols implements the selector (if not, warn).
1289 if (const ObjCObjectPointerType *QIdTy
1290 = ReceiverType->getAsObjCQualifiedIdType()) {
1291 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001292 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1293 if (!Method)
1294 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001295 } else if (const ObjCObjectPointerType *OCIType
1296 = ReceiverType->getAsObjCInterfacePointerType()) {
1297 // We allow sending a message to a pointer to an interface (an object).
1298 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001299
1300 if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCount) {
1301 Diag(Loc, diag::err_arc_receiver_forward_instance)
1302 << OCIType->getPointeeType()
1303 << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperLoc));
1304 return ExprError();
1305 }
1306
Douglas Gregorf49bb082010-04-22 17:01:48 +00001307 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1308 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +00001309 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001310 Method = ClassDecl->lookupInstanceMethod(Sel);
1311
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001312 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001313 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001314 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1315
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001316 const ObjCInterfaceDecl *forwardClass = 0;
Douglas Gregorf49bb082010-04-22 17:01:48 +00001317 if (!Method) {
1318 // If we have implementations in scope, check "private" methods.
1319 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1320
John McCallf85e1932011-06-15 23:02:42 +00001321 if (!Method && getLangOptions().ObjCAutoRefCount) {
1322 Diag(Loc, diag::err_arc_may_not_respond)
1323 << OCIType->getPointeeType() << Sel;
1324 return ExprError();
1325 }
1326
Douglas Gregorf49bb082010-04-22 17:01:48 +00001327 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1328 // If we still haven't found a method, look in the global pool. This
1329 // behavior isn't very desirable, however we need it for GCC
1330 // compatibility. FIXME: should we deviate??
1331 if (OCIType->qual_empty()) {
1332 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001333 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001334 if (OCIType->getInterfaceDecl()->isForwardDecl())
1335 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001336 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001337 Diag(Loc, diag::warn_maynot_respond)
1338 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1339 }
1340 }
1341 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001342 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001343 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001344 } else if (!getLangOptions().ObjCAutoRefCount &&
1345 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001346 (ReceiverType->isPointerType() ||
1347 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001348 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001349 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001350 Diag(Loc, diag::warn_bad_receiver_type)
1351 << ReceiverType
1352 << Receiver->getSourceRange();
1353 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001354 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1355 CK_BitCast).take();
John McCall404cd162010-11-13 01:35:44 +00001356 else {
1357 // TODO: specialized warning on null receivers?
1358 bool IsNull = Receiver->isNullPointerConstant(Context,
1359 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001360 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1361 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001362 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001363 ReceiverType = Receiver->getType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00001364 }
John Wiegley429bb272011-04-08 18:41:53 +00001365 else {
1366 ExprResult ReceiverRes;
1367 if (getLangOptions().CPlusPlus)
1368 ReceiverRes = PerformContextuallyConvertToObjCId(Receiver);
1369 if (ReceiverRes.isUsable()) {
1370 Receiver = ReceiverRes.take();
1371 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
1372 Receiver = ICE->getSubExpr();
1373 ReceiverType = Receiver->getType();
1374 }
1375 return BuildInstanceMessage(Receiver,
1376 ReceiverType,
1377 SuperLoc,
1378 Sel,
1379 Method,
1380 LBracLoc,
1381 SelectorLoc,
1382 RBracLoc,
1383 move(ArgsIn));
1384 } else {
1385 // Reject other random receiver types (e.g. structs).
1386 Diag(Loc, diag::err_bad_receiver_type)
1387 << ReceiverType << Receiver->getSourceRange();
1388 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001389 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001390 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001391 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001392 }
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Douglas Gregor2725ca82010-04-21 19:57:20 +00001394 // Check the message arguments.
1395 unsigned NumArgs = ArgsIn.size();
1396 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1397 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001398 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001399 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1400 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001401 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1402 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001403 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001404 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001405
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001406 if (Method && !Method->getResultType()->isVoidType() &&
1407 RequireCompleteType(LBracLoc, Method->getResultType(),
1408 diag::err_illegal_message_expr_incomplete_type))
1409 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001410
John McCallf85e1932011-06-15 23:02:42 +00001411 // In ARC, forbid the user from sending messages to
1412 // retain/release/autorelease/dealloc/retainCount explicitly.
1413 if (getLangOptions().ObjCAutoRefCount) {
1414 ObjCMethodFamily family =
1415 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1416 switch (family) {
1417 case OMF_init:
1418 if (Method)
1419 checkInitMethod(Method, ReceiverType);
1420
1421 case OMF_None:
1422 case OMF_alloc:
1423 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00001424 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00001425 case OMF_mutableCopy:
1426 case OMF_new:
1427 case OMF_self:
1428 break;
1429
1430 case OMF_dealloc:
1431 case OMF_retain:
1432 case OMF_release:
1433 case OMF_autorelease:
1434 case OMF_retainCount:
1435 Diag(Loc, diag::err_arc_illegal_explicit_message)
1436 << Sel << SelectorLoc;
1437 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001438
1439 case OMF_performSelector:
1440 if (Method && NumArgs >= 1) {
1441 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1442 Selector ArgSel = SelExp->getSelector();
1443 ObjCMethodDecl *SelMethod =
1444 LookupInstanceMethodInGlobalPool(ArgSel,
1445 SelExp->getSourceRange());
1446 if (!SelMethod)
1447 SelMethod =
1448 LookupFactoryMethodInGlobalPool(ArgSel,
1449 SelExp->getSourceRange());
1450 if (SelMethod) {
1451 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1452 switch (SelFamily) {
1453 case OMF_alloc:
1454 case OMF_copy:
1455 case OMF_mutableCopy:
1456 case OMF_new:
1457 case OMF_self:
1458 case OMF_init:
1459 // Issue error, unless ns_returns_not_retained.
1460 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1461 // selector names a +1 method
1462 Diag(SelectorLoc,
1463 diag::err_arc_perform_selector_retains);
1464 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1465 }
1466 break;
1467 default:
1468 // +0 call. OK. unless ns_returns_retained.
1469 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1470 // selector names a +1 method
1471 Diag(SelectorLoc,
1472 diag::err_arc_perform_selector_retains);
1473 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1474 }
1475 break;
1476 }
1477 }
1478 } else {
1479 // error (may leak).
1480 Diag(SelectorLoc, diag::warn_arc_perform_selector_leaks);
1481 Diag(Args[0]->getExprLoc(), diag::note_used_here);
1482 }
1483 }
1484 break;
John McCallf85e1932011-06-15 23:02:42 +00001485 }
1486 }
1487
Douglas Gregor2725ca82010-04-21 19:57:20 +00001488 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001489 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001490 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001491 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001492 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001493 ReceiverType, Sel, SelectorLoc, Method,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001494 Args, NumArgs, RBracLoc);
1495 else
John McCallf89e55a2010-11-18 06:31:45 +00001496 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001497 Receiver, Sel, SelectorLoc, Method,
1498 Args, NumArgs, RBracLoc);
John McCallf85e1932011-06-15 23:02:42 +00001499
1500 if (getLangOptions().ObjCAutoRefCount) {
1501 // In ARC, annotate delegate init calls.
1502 if (Result->getMethodFamily() == OMF_init &&
1503 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
1504 // Only consider init calls *directly* in init implementations,
1505 // not within blocks.
1506 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1507 if (method && method->getMethodFamily() == OMF_init) {
1508 // The implicit assignment to self means we also don't want to
1509 // consume the result.
1510 Result->setDelegateInitCall(true);
1511 return Owned(Result);
1512 }
1513 }
1514
1515 // In ARC, check for message sends which are likely to introduce
1516 // retain cycles.
1517 checkRetainCycles(Result);
1518 }
1519
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001520 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001521}
1522
1523// ActOnInstanceMessage - used for both unary and keyword messages.
1524// ArgExprs is optional - if it is present, the number of expressions
1525// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001526ExprResult Sema::ActOnInstanceMessage(Scope *S,
1527 Expr *Receiver,
1528 Selector Sel,
1529 SourceLocation LBracLoc,
1530 SourceLocation SelectorLoc,
1531 SourceLocation RBracLoc,
1532 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001533 if (!Receiver)
1534 return ExprError();
1535
John McCall9ae2f072010-08-23 23:25:46 +00001536 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001537 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001538 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001539}
Chris Lattnereca7be62008-04-07 05:30:13 +00001540
John McCallf85e1932011-06-15 23:02:42 +00001541enum ARCConversionTypeClass {
1542 ACTC_none,
1543 ACTC_retainable,
1544 ACTC_indirectRetainable
1545};
1546static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
1547 ARCConversionTypeClass ACTC = ACTC_retainable;
1548
1549 // Ignore an outermost reference type.
1550 if (const ReferenceType *ref = type->getAs<ReferenceType>())
1551 type = ref->getPointeeType();
1552
1553 // Drill through pointers and arrays recursively.
1554 while (true) {
1555 if (const PointerType *ptr = type->getAs<PointerType>()) {
1556 type = ptr->getPointeeType();
1557 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1558 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1559 } else {
1560 break;
1561 }
1562 ACTC = ACTC_indirectRetainable;
1563 }
1564
1565 if (!type->isObjCRetainableType()) return ACTC_none;
1566 return ACTC;
1567}
1568
1569namespace {
1570 /// Return true if the given expression can be reasonably converted
1571 /// between a retainable pointer type and a C pointer type.
1572 struct ARCCastChecker : StmtVisitor<ARCCastChecker, bool> {
1573 ASTContext &Context;
1574 ARCCastChecker(ASTContext &Context) : Context(Context) {}
1575 bool VisitStmt(Stmt *s) {
1576 return false;
1577 }
1578 bool VisitExpr(Expr *e) {
1579 return e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
1580 }
1581
1582 bool VisitParenExpr(ParenExpr *e) {
1583 return Visit(e->getSubExpr());
1584 }
1585 bool VisitCastExpr(CastExpr *e) {
1586 switch (e->getCastKind()) {
1587 case CK_NullToPointer:
1588 return true;
1589 case CK_NoOp:
1590 case CK_LValueToRValue:
1591 case CK_BitCast:
1592 case CK_AnyPointerToObjCPointerCast:
1593 case CK_AnyPointerToBlockPointerCast:
1594 return Visit(e->getSubExpr());
1595 default:
1596 return false;
1597 }
1598 }
1599 bool VisitUnaryExtension(UnaryOperator *e) {
1600 return Visit(e->getSubExpr());
1601 }
1602 bool VisitBinComma(BinaryOperator *e) {
1603 return Visit(e->getRHS());
1604 }
1605 bool VisitConditionalOperator(ConditionalOperator *e) {
1606 // Conditional operators are okay if both sides are okay.
1607 return Visit(e->getTrueExpr()) && Visit(e->getFalseExpr());
1608 }
1609 bool VisitObjCStringLiteral(ObjCStringLiteral *e) {
1610 // Always white-list Objective-C string literals.
1611 return true;
1612 }
1613 bool VisitStmtExpr(StmtExpr *e) {
1614 return Visit(e->getSubStmt()->body_back());
1615 }
1616 bool VisitDeclRefExpr(DeclRefExpr *e) {
1617 // White-list references to global extern strings from system
1618 // headers.
1619 if (VarDecl *var = dyn_cast<VarDecl>(e->getDecl()))
1620 if (var->getStorageClass() == SC_Extern &&
1621 var->getType().isConstQualified() &&
1622 Context.getSourceManager().isInSystemHeader(var->getLocation()))
1623 return true;
1624 return false;
1625 }
1626 };
1627}
1628
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001629bool
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001630Sema::ValidObjCARCNoBridgeCastExpr(Expr *&Exp, QualType castType) {
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001631 Expr *NewExp = Exp->IgnoreParenCasts();
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001632
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001633 if (!isa<ObjCMessageExpr>(NewExp) && !isa<ObjCPropertyRefExpr>(NewExp)
1634 && !isa<CallExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001635 return false;
1636 ObjCMethodDecl *method = 0;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001637 bool MethodReturnsPlusOne = false;
1638
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001639 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(NewExp)) {
1640 method = PRE->getExplicitProperty()->getGetterMethodDecl();
1641 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001642 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001643 method = ME->getMethodDecl();
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001644 else {
1645 CallExpr *CE = cast<CallExpr>(NewExp);
1646 Decl *CallDecl = CE->getCalleeDecl();
1647 if (!CallDecl)
1648 return false;
1649 if (CallDecl->hasAttr<CFReturnsNotRetainedAttr>())
1650 return true;
1651 MethodReturnsPlusOne = CallDecl->hasAttr<CFReturnsRetainedAttr>();
1652 if (!MethodReturnsPlusOne) {
1653 if (NamedDecl *ND = dyn_cast<NamedDecl>(CallDecl))
1654 if (const IdentifierInfo *Id = ND->getIdentifier())
1655 if (Id->isStr("__builtin___CFStringMakeConstantString"))
1656 return true;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001657 }
1658 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001659
1660 if (!MethodReturnsPlusOne) {
1661 if (!method)
1662 return false;
1663 if (method->hasAttr<CFReturnsNotRetainedAttr>())
1664 return true;
1665 MethodReturnsPlusOne = method->hasAttr<CFReturnsRetainedAttr>();
1666 if (!MethodReturnsPlusOne) {
1667 ObjCMethodFamily family = method->getSelector().getMethodFamily();
1668 switch (family) {
1669 case OMF_alloc:
1670 case OMF_copy:
1671 case OMF_mutableCopy:
1672 case OMF_new:
1673 MethodReturnsPlusOne = true;
1674 break;
1675 default:
1676 break;
1677 }
1678 }
1679 }
1680
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001681 if (MethodReturnsPlusOne) {
1682 TypeSourceInfo *TSInfo =
1683 Context.getTrivialTypeSourceInfo(castType, SourceLocation());
1684 ExprResult ExpRes = BuildObjCBridgedCast(SourceLocation(), OBC_BridgeTransfer,
1685 SourceLocation(), TSInfo, Exp);
1686 Exp = ExpRes.take();
1687 }
1688 return true;
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001689}
1690
John McCallf85e1932011-06-15 23:02:42 +00001691void
1692Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001693 Expr *&castExpr, CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00001694 QualType castExprType = castExpr->getType();
1695
1696 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1697 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
1698 if (exprACTC == castACTC) return;
Fariborz Jahanian8295b7b2011-06-22 16:36:45 +00001699 if (exprACTC && castType->isIntegralType(Context)) return;
John McCallf85e1932011-06-15 23:02:42 +00001700
1701 // Allow casts between pointers to lifetime types (e.g., __strong id*)
1702 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1703 // must be explicit.
1704 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
1705 if (const PointerType *CastExprPtr = castExprType->getAs<PointerType>()) {
1706 QualType CastPointee = CastPtr->getPointeeType();
1707 QualType CastExprPointee = CastExprPtr->getPointeeType();
1708 if ((CCK != CCK_ImplicitConversion &&
1709 CastPointee->isObjCIndirectLifetimeType() &&
1710 CastExprPointee->isVoidType()) ||
1711 (CastPointee->isVoidType() &&
1712 CastExprPointee->isObjCIndirectLifetimeType()))
1713 return;
1714 }
1715 }
1716
1717 if (ARCCastChecker(Context).Visit(castExpr))
1718 return;
1719
1720 SourceLocation loc =
1721 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
1722
1723 if (makeUnavailableInSystemHeader(loc,
1724 "converts between Objective-C and C pointers in -fobjc-arc"))
1725 return;
1726
John McCall71c482c2011-06-17 06:50:50 +00001727 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00001728 switch (exprACTC) {
1729 case ACTC_none:
1730 srcKind = (castExprType->isPointerType() ? 1 : 0);
1731 break;
1732 case ACTC_retainable:
1733 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1734 break;
1735 case ACTC_indirectRetainable:
1736 srcKind = 4;
1737 break;
1738 }
1739
1740 if (CCK == CCK_CStyleCast) {
1741 // Check whether this could be fixed with a bridge cast.
1742 SourceLocation AfterLParen = PP.getLocForEndOfToken(castRange.getBegin());
1743 SourceLocation NoteLoc = AfterLParen.isValid()? AfterLParen : loc;
1744
1745 if (castType->isObjCARCBridgableType() &&
1746 castExprType->isCARCBridgableType()) {
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001747 // explicit unbridged casts are allowed if the source of the cast is a
1748 // message sent to an objc method (or property access)
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001749 if (ValidObjCARCNoBridgeCastExpr(castExpr, castType))
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001750 return;
John McCallf85e1932011-06-15 23:02:42 +00001751 Diag(loc, diag::err_arc_cast_requires_bridge)
1752 << 2
1753 << castExprType
1754 << (castType->isBlockPointerType()? 1 : 0)
1755 << castType
1756 << castRange
1757 << castExpr->getSourceRange();
1758 Diag(NoteLoc, diag::note_arc_bridge)
1759 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1760 Diag(NoteLoc, diag::note_arc_bridge_transfer)
1761 << castExprType
1762 << FixItHint::CreateInsertion(AfterLParen, "__bridge_transfer ");
1763
1764 return;
1765 }
1766
1767 if (castType->isCARCBridgableType() &&
1768 castExprType->isObjCARCBridgableType()){
1769 Diag(loc, diag::err_arc_cast_requires_bridge)
1770 << (castExprType->isBlockPointerType()? 1 : 0)
1771 << castExprType
1772 << 2
1773 << castType
1774 << castRange
1775 << castExpr->getSourceRange();
1776
1777 Diag(NoteLoc, diag::note_arc_bridge)
1778 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1779 Diag(NoteLoc, diag::note_arc_bridge_retained)
1780 << castType
1781 << FixItHint::CreateInsertion(AfterLParen, "__bridge_retained ");
1782 return;
1783 }
1784 }
1785
1786 Diag(loc, diag::err_arc_mismatched_cast)
1787 << (CCK != CCK_ImplicitConversion) << srcKind << castExprType << castType
1788 << castRange << castExpr->getSourceRange();
1789}
1790
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00001791bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
1792 QualType exprType) {
1793 QualType canCastType =
1794 Context.getCanonicalType(castType).getUnqualifiedType();
1795 QualType canExprType =
1796 Context.getCanonicalType(exprType).getUnqualifiedType();
1797 if (isa<ObjCObjectPointerType>(canCastType) &&
1798 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
1799 canExprType->isObjCObjectPointerType()) {
1800 if (const ObjCObjectPointerType *ObjT =
1801 canExprType->getAs<ObjCObjectPointerType>())
1802 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
1803 return false;
1804 }
1805 return true;
1806}
1807
John McCall7e5e5f42011-07-07 06:58:02 +00001808/// Look for an ObjCReclaimReturnedObject cast and destroy it.
1809static Expr *maybeUndoReclaimObject(Expr *e) {
1810 // For now, we just undo operands that are *immediately* reclaim
1811 // expressions, which prevents the vast majority of potential
1812 // problems here. To catch them all, we'd need to rebuild arbitrary
1813 // value-propagating subexpressions --- we can't reliably rebuild
1814 // in-place because of expression sharing.
1815 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
1816 if (ice->getCastKind() == CK_ObjCReclaimReturnedObject)
1817 return ice->getSubExpr();
1818
1819 return e;
1820}
1821
John McCallf85e1932011-06-15 23:02:42 +00001822ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
1823 ObjCBridgeCastKind Kind,
1824 SourceLocation BridgeKeywordLoc,
1825 TypeSourceInfo *TSInfo,
1826 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00001827 ExprResult SubResult = UsualUnaryConversions(SubExpr);
1828 if (SubResult.isInvalid()) return ExprError();
1829 SubExpr = SubResult.take();
1830
John McCallf85e1932011-06-15 23:02:42 +00001831 QualType T = TSInfo->getType();
1832 QualType FromType = SubExpr->getType();
1833
1834 bool MustConsume = false;
1835 if (T->isDependentType() || SubExpr->isTypeDependent()) {
1836 // Okay: we'll build a dependent expression type.
1837 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
1838 // Casting CF -> id
1839 switch (Kind) {
1840 case OBC_Bridge:
1841 break;
1842
1843 case OBC_BridgeRetained:
1844 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1845 << 2
1846 << FromType
1847 << (T->isBlockPointerType()? 1 : 0)
1848 << T
1849 << SubExpr->getSourceRange()
1850 << Kind;
1851 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1852 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
1853 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
1854 << FromType
1855 << FixItHint::CreateReplacement(BridgeKeywordLoc,
1856 "__bridge_transfer ");
1857
1858 Kind = OBC_Bridge;
1859 break;
1860
1861 case OBC_BridgeTransfer:
1862 // We must consume the Objective-C object produced by the cast.
1863 MustConsume = true;
1864 break;
1865 }
1866 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
1867 // Okay: id -> CF
1868 switch (Kind) {
1869 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00001870 // Reclaiming a value that's going to be __bridge-casted to CF
1871 // is very dangerous, so we don't do it.
1872 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00001873 break;
1874
1875 case OBC_BridgeRetained:
1876 // Produce the object before casting it.
1877 SubExpr = ImplicitCastExpr::Create(Context, FromType,
1878 CK_ObjCProduceObject,
1879 SubExpr, 0, VK_RValue);
1880 break;
1881
1882 case OBC_BridgeTransfer:
1883 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1884 << (FromType->isBlockPointerType()? 1 : 0)
1885 << FromType
1886 << 2
1887 << T
1888 << SubExpr->getSourceRange()
1889 << Kind;
1890
1891 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1892 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
1893 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
1894 << T
1895 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
1896
1897 Kind = OBC_Bridge;
1898 break;
1899 }
1900 } else {
1901 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
1902 << FromType << T << Kind
1903 << SubExpr->getSourceRange()
1904 << TSInfo->getTypeLoc().getSourceRange();
1905 return ExprError();
1906 }
1907
1908 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind,
1909 BridgeKeywordLoc,
1910 TSInfo, SubExpr);
1911
1912 if (MustConsume) {
1913 ExprNeedsCleanups = true;
1914 Result = ImplicitCastExpr::Create(Context, T, CK_ObjCConsumeObject, Result,
1915 0, VK_RValue);
1916 }
1917
1918 return Result;
1919}
1920
1921ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
1922 SourceLocation LParenLoc,
1923 ObjCBridgeCastKind Kind,
1924 SourceLocation BridgeKeywordLoc,
1925 ParsedType Type,
1926 SourceLocation RParenLoc,
1927 Expr *SubExpr) {
1928 TypeSourceInfo *TSInfo = 0;
1929 QualType T = GetTypeFromParser(Type, &TSInfo);
1930 if (!TSInfo)
1931 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
1932 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
1933 SubExpr);
1934}