blob: f3893ce2a587280475e000248c20cf3a92e3cfe2 [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:
206 case OMF_init:
207 case OMF_mutableCopy:
208 case OMF_new:
209 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +0000210 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +0000211 break;
212 }
213 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000214 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000215 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000216}
217
John McCallf312b1e2010-08-26 23:41:50 +0000218ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
219 SourceLocation AtLoc,
220 SourceLocation ProtoLoc,
221 SourceLocation LParenLoc,
222 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000223 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000224 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000225 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000226 return true;
227 }
Mike Stump1eb44332009-09-09 15:08:12 +0000228
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000229 QualType Ty = Context.getObjCProtoType();
230 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000231 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000232 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000233 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000234}
235
John McCall26743b22011-02-03 09:00:02 +0000236/// Try to capture an implicit reference to 'self'.
237ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
238 // Ignore block scopes: we can capture through them.
239 DeclContext *DC = CurContext;
240 while (true) {
241 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
242 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
243 else break;
244 }
245
246 // If we're not in an ObjC method, error out. Note that, unlike the
247 // C++ case, we don't require an instance method --- class methods
248 // still have a 'self', and we really do still need to capture it!
249 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
250 if (!method)
251 return 0;
252
253 ImplicitParamDecl *self = method->getSelfDecl();
254 assert(self && "capturing 'self' in non-definition?");
255
256 // Mark that we're closing on 'this' in all the block scopes, if applicable.
257 for (unsigned idx = FunctionScopes.size() - 1;
258 isa<BlockScopeInfo>(FunctionScopes[idx]);
John McCall6b5a61b2011-02-07 10:33:21 +0000259 --idx) {
260 BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
261 unsigned &captureIndex = blockScope->CaptureMap[self];
262 if (captureIndex) break;
263
264 bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
265 blockScope->Captures.push_back(
266 BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
267 captureIndex = blockScope->Captures.size(); // +1
268 }
John McCall26743b22011-02-03 09:00:02 +0000269
270 return method;
271}
272
Douglas Gregor926df6c2011-06-11 01:09:30 +0000273QualType Sema::getMessageSendResultType(QualType ReceiverType,
274 ObjCMethodDecl *Method,
275 bool isClassMessage, bool isSuperMessage) {
276 assert(Method && "Must have a method");
277 if (!Method->hasRelatedResultType())
278 return Method->getSendResultType();
279
280 // If a method has a related return type:
281 // - if the method found is an instance method, but the message send
282 // was a class message send, T is the declared return type of the method
283 // found
284 if (Method->isInstanceMethod() && isClassMessage)
285 return Method->getSendResultType();
286
287 // - if the receiver is super, T is a pointer to the class of the
288 // enclosing method definition
289 if (isSuperMessage) {
290 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
291 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
292 return Context.getObjCObjectPointerType(
293 Context.getObjCInterfaceType(Class));
294 }
295
296 // - if the receiver is the name of a class U, T is a pointer to U
297 if (ReceiverType->getAs<ObjCInterfaceType>() ||
298 ReceiverType->isObjCQualifiedInterfaceType())
299 return Context.getObjCObjectPointerType(ReceiverType);
300 // - if the receiver is of type Class or qualified Class type,
301 // T is the declared return type of the method.
302 if (ReceiverType->isObjCClassType() ||
303 ReceiverType->isObjCQualifiedClassType())
304 return Method->getSendResultType();
305
306 // - if the receiver is id, qualified id, Class, or qualified Class, T
307 // is the receiver type, otherwise
308 // - T is the type of the receiver expression.
309 return ReceiverType;
310}
John McCall26743b22011-02-03 09:00:02 +0000311
Douglas Gregor926df6c2011-06-11 01:09:30 +0000312void Sema::EmitRelatedResultTypeNote(const Expr *E) {
313 E = E->IgnoreParenImpCasts();
314 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
315 if (!MsgSend)
316 return;
317
318 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
319 if (!Method)
320 return;
321
322 if (!Method->hasRelatedResultType())
323 return;
324
325 if (Context.hasSameUnqualifiedType(Method->getResultType()
326 .getNonReferenceType(),
327 MsgSend->getType()))
328 return;
329
330 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
331 << Method->isInstanceMethod() << Method->getSelector()
332 << MsgSend->getType();
333}
334
335bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
336 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000337 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000338 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000339 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000340 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000341 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000342 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000343 for (unsigned i = 0; i != NumArgs; i++) {
344 if (Args[i]->isTypeDependent())
345 continue;
346
John Wiegley429bb272011-04-08 18:41:53 +0000347 ExprResult Result = DefaultArgumentPromotion(Args[i]);
348 if (Result.isInvalid())
349 return true;
350 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000351 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000352
John McCallf85e1932011-06-15 23:02:42 +0000353 unsigned DiagID;
354 if (getLangOptions().ObjCAutoRefCount)
355 DiagID = diag::err_arc_method_not_found;
356 else
357 DiagID = isClassMessage ? diag::warn_class_method_not_found
358 : diag::warn_inst_method_not_found;
Chris Lattner077bf5e2008-11-24 03:33:13 +0000359 Diag(lbrac, DiagID)
360 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +0000361
362 // In debuggers, we want to use __unknown_anytype for these
363 // results so that clients can cast them.
364 if (getLangOptions().DebuggerSupport) {
365 ReturnType = Context.UnknownAnyTy;
366 } else {
367 ReturnType = Context.getObjCIdType();
368 }
John McCallf89e55a2010-11-18 06:31:45 +0000369 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000370 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000371 }
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Douglas Gregor926df6c2011-06-11 01:09:30 +0000373 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
374 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000375 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000377 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000378 // Method might have more arguments than selector indicates. This is due
379 // to addition of c-style arguments in method.
380 if (Method->param_size() > Sel.getNumArgs())
381 NumNamedArgs = Method->param_size();
382 // FIXME. This need be cleaned up.
383 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000384 Diag(lbrac, diag::err_typecheck_call_too_few_args)
385 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000386 return false;
387 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000388
Chris Lattner312531a2009-04-12 08:11:20 +0000389 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000390 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000391 // We can't do any type-checking on a type-dependent argument.
392 if (Args[i]->isTypeDependent())
393 continue;
394
Chris Lattner85a932e2008-01-04 22:32:30 +0000395 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000396
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000397 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000398 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000400 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
401 Param->getType(),
402 PDiag(diag::err_call_incomplete_argument)
403 << argExpr->getSourceRange()))
404 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000405
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000406 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
407 Param);
John McCall3fa5cae2010-10-26 07:05:15 +0000408 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000409 if (ArgE.isInvalid())
410 IsError = true;
411 else
412 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000413 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000414
415 // Promote additional arguments to variadic methods.
416 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000417 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
418 if (Args[i]->isTypeDependent())
419 continue;
420
John Wiegley429bb272011-04-08 18:41:53 +0000421 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
422 IsError |= Arg.isInvalid();
423 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000424 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000425 } else {
426 // Check for extra arguments to non-variadic methods.
427 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000428 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000429 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000430 << 2 /*method*/ << NumNamedArgs << NumArgs
431 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000432 << SourceRange(Args[NumNamedArgs]->getLocStart(),
433 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000434 }
435 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000436 // diagnose nonnull arguments.
437 for (specific_attr_iterator<NonNullAttr>
438 i = Method->specific_attr_begin<NonNullAttr>(),
439 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
440 CheckNonNullArguments(*i, Args, lbrac);
441 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000442
Douglas Gregor2725ca82010-04-21 19:57:20 +0000443 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000444 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000445}
446
John McCallf85e1932011-06-15 23:02:42 +0000447bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000448 // 'self' is objc 'self' in an objc method only.
Fariborz Jahanianb4602102011-03-28 16:23:34 +0000449 DeclContext *DC = CurContext;
450 while (isa<BlockDecl>(DC))
451 DC = DC->getParent();
452 if (DC && !isa<ObjCMethodDecl>(DC))
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000453 return false;
John McCallf85e1932011-06-15 23:02:42 +0000454 receiver = receiver->IgnoreParenLValueCasts();
455 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000456 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
457 return true;
458 return false;
459}
460
Steve Narofff1afaf62009-02-26 15:55:06 +0000461// Helper method for ActOnClassMethod/ActOnInstanceMethod.
462// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000463// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000464// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000465ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000466 ObjCInterfaceDecl *ClassDecl) {
467 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000468 // lookup in class and all superclasses
469 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000470 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000471 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Steve Naroff5609ec02009-03-08 18:56:13 +0000473 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000474 if (!Method)
475 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Steve Naroff5609ec02009-03-08 18:56:13 +0000477 // Before we give up, check if the selector is an instance method.
478 // But only in the root. This matches gcc's behaviour and what the
479 // runtime expects.
480 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000481 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000482 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000483 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000484 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000485 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Steve Naroff5609ec02009-03-08 18:56:13 +0000488 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000489 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000490 return Method;
491}
492
493ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
494 ObjCInterfaceDecl *ClassDecl) {
495 ObjCMethodDecl *Method = 0;
496 while (ClassDecl && !Method) {
497 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000498 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000499 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Steve Naroff5609ec02009-03-08 18:56:13 +0000501 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000502 if (!Method)
503 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000504 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000505 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000506 return Method;
507}
508
Fariborz Jahanian61478062011-03-09 20:18:06 +0000509/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
510/// list of a qualified objective pointer type.
511ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
512 const ObjCObjectPointerType *OPT,
513 bool Instance)
514{
515 ObjCMethodDecl *MD = 0;
516 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
517 E = OPT->qual_end(); I != E; ++I) {
518 ObjCProtocolDecl *PROTO = (*I);
519 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
520 return MD;
521 }
522 }
523 return 0;
524}
525
Chris Lattner7f816522010-04-11 07:45:24 +0000526/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
527/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000528ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000529HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000530 Expr *BaseExpr, SourceLocation OpLoc,
531 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000532 SourceLocation MemberLoc,
533 SourceLocation SuperLoc, QualType SuperType,
534 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000535 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
536 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000537
538 if (MemberName.getNameKind() != DeclarationName::Identifier) {
539 Diag(MemberLoc, diag::err_invalid_property_name)
540 << MemberName << QualType(OPT, 0);
541 return ExprError();
542 }
543
Chris Lattner7f816522010-04-11 07:45:24 +0000544 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
545
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000546 if (IFace->isForwardDecl()) {
547 Diag(MemberLoc, diag::err_property_not_found_forward_class)
548 << MemberName << QualType(OPT, 0);
549 Diag(IFace->getLocation(), diag::note_forward_class);
550 return ExprError();
551 }
Chris Lattner7f816522010-04-11 07:45:24 +0000552 // Search for a declared property first.
553 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
554 // Check whether we can reference this property.
555 if (DiagnoseUseOfDecl(PD, MemberLoc))
556 return ExprError();
557 QualType ResTy = PD->getType();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000558 ResTy = ResTy.getNonLValueExprType(Context);
Chris Lattner7f816522010-04-11 07:45:24 +0000559 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
560 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000561 if (Getter &&
562 (Getter->hasRelatedResultType()
563 || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
564 ResTy = getMessageSendResultType(QualType(OPT, 0), Getter, false,
565 Super);
566
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000567 if (Super)
568 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000569 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000570 MemberLoc,
571 SuperLoc, SuperType));
572 else
573 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000574 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000575 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000576 }
577 // Check protocols on qualified interfaces.
578 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
579 E = OPT->qual_end(); I != E; ++I)
580 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
581 // Check whether we can reference this property.
582 if (DiagnoseUseOfDecl(PD, MemberLoc))
583 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000584
585 QualType T = PD->getType();
586 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
587 T = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000588 if (Super)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000589 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000590 VK_LValue,
591 OK_ObjCProperty,
592 MemberLoc,
593 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000594 else
Douglas Gregor926df6c2011-06-11 01:09:30 +0000595 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000596 VK_LValue,
597 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000598 MemberLoc,
599 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000600 }
601 // If that failed, look for an "implicit" property by seeing if the nullary
602 // selector is implemented.
603
604 // FIXME: The logic for looking up nullary and unary selectors should be
605 // shared with the code in ActOnInstanceMessage.
606
607 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
608 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000609
610 // May be founf in property's qualified list.
611 if (!Getter)
612 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000613
614 // If this reference is in an @implementation, check for 'private' methods.
615 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000616 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000617
618 // Look through local category implementations associated with the class.
619 if (!Getter)
620 Getter = IFace->getCategoryInstanceMethod(Sel);
621 if (Getter) {
622 // Check if we can reference this property.
623 if (DiagnoseUseOfDecl(Getter, MemberLoc))
624 return ExprError();
625 }
626 // If we found a getter then this may be a valid dot-reference, we
627 // will look for the matching setter, in case it is needed.
628 Selector SetterSel =
629 SelectorTable::constructSetterName(PP.getIdentifierTable(),
630 PP.getSelectorTable(), Member);
631 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000632
633 // May be founf in property's qualified list.
634 if (!Setter)
635 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
636
Chris Lattner7f816522010-04-11 07:45:24 +0000637 if (!Setter) {
638 // If this reference is in an @implementation, also check for 'private'
639 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000640 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000641 }
642 // Look through local category implementations associated with the class.
643 if (!Setter)
644 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000645
Chris Lattner7f816522010-04-11 07:45:24 +0000646 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
647 return ExprError();
648
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000649 if (Getter || Setter) {
650 QualType PType;
651 if (Getter)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000652 PType = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000653 else {
654 ParmVarDecl *ArgDecl = *Setter->param_begin();
655 PType = ArgDecl->getType();
656 }
657
John McCall09431682010-11-18 19:01:18 +0000658 ExprValueKind VK = VK_LValue;
659 ExprObjectKind OK = OK_ObjCProperty;
660 if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
661 PType->isVoidType())
662 VK = VK_RValue, OK = OK_Ordinary;
663
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000664 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000665 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
666 PType, VK, OK,
667 MemberLoc,
668 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000669 else
John McCall12f78a62010-12-02 01:19:52 +0000670 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
671 PType, VK, OK,
672 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000673
Chris Lattner7f816522010-04-11 07:45:24 +0000674 }
675
676 // Attempt to correct for typos in property names.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000677 TypoCorrection Corrected = CorrectTypo(
678 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
679 NULL, IFace, false, CTC_NoKeywords, OPT);
680 if (ObjCPropertyDecl *Property =
681 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>()) {
682 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +0000683 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000684 << MemberName << QualType(OPT, 0) << TypoResult
685 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000686 Diag(Property->getLocation(), diag::note_previous_decl)
687 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000688 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
689 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000690 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000691 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000692 ObjCInterfaceDecl *ClassDeclared;
693 if (ObjCIvarDecl *Ivar =
694 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
695 QualType T = Ivar->getType();
696 if (const ObjCObjectPointerType * OBJPT =
697 T->getAsObjCInterfacePointerType()) {
698 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
699 if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
700 if (IFace->isForwardDecl()) {
701 Diag(MemberLoc, diag::err_property_not_as_forward_class)
Fariborz Jahanian2a96bf52011-02-17 17:30:05 +0000702 << MemberName << IFace;
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000703 Diag(IFace->getLocation(), diag::note_forward_class);
704 return ExprError();
705 }
706 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000707 Diag(MemberLoc,
708 diag::err_ivar_access_using_property_syntax_suggest)
709 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
710 << FixItHint::CreateReplacement(OpLoc, "->");
711 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000712 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000713
Chris Lattner7f816522010-04-11 07:45:24 +0000714 Diag(MemberLoc, diag::err_property_not_found)
715 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000716 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000717 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000718 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000719 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000720}
721
722
723
John McCall60d7b3a2010-08-24 06:29:42 +0000724ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000725ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
726 IdentifierInfo &propertyName,
727 SourceLocation receiverNameLoc,
728 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000730 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000731 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
732 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000733
734 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000735 if (IFace == 0) {
736 // If the "receiver" is 'super' in a method, handle it as an expression-like
737 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000738 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000739 IsSuper = true;
740
John McCall26743b22011-02-03 09:00:02 +0000741 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000742 if (CurMethod->isInstanceMethod()) {
743 QualType T =
744 Context.getObjCInterfaceType(CurMethod->getClassInterface());
745 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000746
747 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000748 /*BaseExpr*/0,
749 SourceLocation()/*OpLoc*/,
750 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000751 propertyNameLoc,
752 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000753 }
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Chris Lattnereb483eb2010-04-11 08:28:14 +0000755 // Otherwise, if this is a class method, try dispatching to our
756 // superclass.
757 IFace = CurMethod->getClassInterface()->getSuperClass();
758 }
John McCall26743b22011-02-03 09:00:02 +0000759 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000760
761 if (IFace == 0) {
762 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
763 return ExprError();
764 }
765 }
766
767 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000768 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000769 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000770
771 // If this reference is in an @implementation, check for 'private' methods.
772 if (!Getter)
773 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
774 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000775 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000776 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000777
778 if (Getter) {
779 // FIXME: refactor/share with ActOnMemberReference().
780 // Check if we can reference this property.
781 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
782 return ExprError();
783 }
Mike Stump1eb44332009-09-09 15:08:12 +0000784
Steve Naroff61f72cb2009-03-09 21:12:44 +0000785 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000786 Selector SetterSel =
787 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000788 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000789
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000790 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000791 if (!Setter) {
792 // If this reference is in an @implementation, also check for 'private'
793 // methods.
794 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
795 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000796 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000797 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000798 }
799 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000800 if (!Setter)
801 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000802
803 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
804 return ExprError();
805
806 if (Getter || Setter) {
807 QualType PType;
808
John McCall09431682010-11-18 19:01:18 +0000809 ExprValueKind VK = VK_LValue;
810 if (Getter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000811 PType = getMessageSendResultType(Context.getObjCInterfaceType(IFace),
812 Getter, true,
813 receiverNamePtr->isStr("super"));
John McCall09431682010-11-18 19:01:18 +0000814 if (!getLangOptions().CPlusPlus &&
815 !PType.hasQualifiers() && PType->isVoidType())
816 VK = VK_RValue;
817 } else {
Steve Naroff61f72cb2009-03-09 21:12:44 +0000818 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
819 E = Setter->param_end(); PI != E; ++PI)
820 PType = (*PI)->getType();
John McCall09431682010-11-18 19:01:18 +0000821 VK = VK_LValue;
Steve Naroff61f72cb2009-03-09 21:12:44 +0000822 }
John McCall09431682010-11-18 19:01:18 +0000823
824 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
825
Douglas Gregor926df6c2011-06-11 01:09:30 +0000826 if (IsSuper)
827 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
828 PType, VK, OK,
829 propertyNameLoc,
830 receiverNameLoc,
831 Context.getObjCInterfaceType(IFace)));
832
John McCall12f78a62010-12-02 01:19:52 +0000833 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
834 PType, VK, OK,
835 propertyNameLoc,
836 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000837 }
838 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
839 << &propertyName << Context.getObjCInterfaceType(IFace));
840}
841
Douglas Gregor47bd5432010-04-14 02:46:37 +0000842Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000843 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000844 SourceLocation NameLoc,
845 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000846 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000847 ParsedType &ReceiverType) {
848 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000849
Douglas Gregor47bd5432010-04-14 02:46:37 +0000850 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000851 // messaging super. If the identifier is "super" and there is a
852 // trailing dot, it's an instance message.
853 if (IsSuper && S->isInObjcMethodScope())
854 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000855
856 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
857 LookupName(Result, S);
858
859 switch (Result.getResultKind()) {
860 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000861 // Normal name lookup didn't find anything. If we're in an
862 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000863 // FIXME: This is a hack. Ivar lookup should be part of normal
864 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000865 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
866 ObjCInterfaceDecl *ClassDeclared;
867 if (Method->getClassInterface()->lookupInstanceVariable(Name,
868 ClassDeclared))
869 return ObjCInstanceMessage;
870 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000871
Douglas Gregor47bd5432010-04-14 02:46:37 +0000872 // Break out; we'll perform typo correction below.
873 break;
874
875 case LookupResult::NotFoundInCurrentInstantiation:
876 case LookupResult::FoundOverloaded:
877 case LookupResult::FoundUnresolvedValue:
878 case LookupResult::Ambiguous:
879 Result.suppressDiagnostics();
880 return ObjCInstanceMessage;
881
882 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000883 // If the identifier is a class or not, and there is a trailing dot,
884 // it's an instance message.
885 if (HasTrailingDot)
886 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000887 // We found something. If it's a type, then we have a class
888 // message. Otherwise, it's an instance message.
889 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000890 QualType T;
891 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
892 T = Context.getObjCInterfaceType(Class);
893 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
894 T = Context.getTypeDeclType(Type);
895 else
896 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000897
Douglas Gregor1569f952010-04-21 20:38:13 +0000898 // We have a class message, and T is the type we're
899 // messaging. Build source-location information for it.
900 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000901 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000902 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000903 }
904 }
905
Douglas Gregoraaf87162010-04-14 20:04:41 +0000906 // Determine our typo-correction context.
907 CorrectTypoContext CTC = CTC_Expression;
908 if (ObjCMethodDecl *Method = getCurMethodDecl())
909 if (Method->getClassInterface() &&
910 Method->getClassInterface()->getSuperClass())
911 CTC = CTC_ObjCMessageReceiver;
912
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000913 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
914 Result.getLookupKind(), S, NULL,
915 NULL, false, CTC)) {
916 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000917 // If we found a declaration, correct when it refers to an Objective-C
918 // class.
Douglas Gregor1569f952010-04-21 20:38:13 +0000919 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000920 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000921 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000922 << FixItHint::CreateReplacement(SourceRange(NameLoc),
923 ND->getNameAsString());
924 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000925 << Corrected.getCorrection();
Douglas Gregor47bd5432010-04-14 02:46:37 +0000926
Douglas Gregor1569f952010-04-21 20:38:13 +0000927 QualType T = Context.getObjCInterfaceType(Class);
928 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000929 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000930 return ObjCClassMessage;
931 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000932 } else if (Corrected.isKeyword() &&
933 Corrected.getCorrectionAsIdentifierInfo()->isStr("super")) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000934 // If we've found the keyword "super", this is a send to super.
935 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000936 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000937 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000938 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000939 }
940 }
941
942 // Fall back: let the parser try to parse it as an instance message.
943 return ObjCInstanceMessage;
944}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000945
John McCall60d7b3a2010-08-24 06:29:42 +0000946ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000947 SourceLocation SuperLoc,
948 Selector Sel,
949 SourceLocation LBracLoc,
950 SourceLocation SelectorLoc,
951 SourceLocation RBracLoc,
952 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000953 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000954 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000955 if (!Method) {
956 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
957 return ExprError();
958 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000959
Douglas Gregorf95861a2010-04-21 20:01:04 +0000960 ObjCInterfaceDecl *Class = Method->getClassInterface();
961 if (!Class) {
962 Diag(SuperLoc, diag::error_no_super_class_message)
963 << Method->getDeclName();
964 return ExprError();
965 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000966
Douglas Gregorf95861a2010-04-21 20:01:04 +0000967 ObjCInterfaceDecl *Super = Class->getSuperClass();
968 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000969 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000970 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
971 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000972 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000973 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000974
Douglas Gregorf95861a2010-04-21 20:01:04 +0000975 // We are in a method whose class has a superclass, so 'super'
976 // is acting as a keyword.
977 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +0000978 if (Sel.getMethodFamily() == OMF_dealloc)
979 ObjCShouldCallSuperDealloc = false;
980
Douglas Gregorf95861a2010-04-21 20:01:04 +0000981 // Since we are in an instance method, this is an instance
982 // message to the superclass instance.
983 QualType SuperTy = Context.getObjCInterfaceType(Super);
984 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +0000985 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000986 Sel, /*Method=*/0,
987 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000988 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000989
990 // Since we are in a class method, this is a class message to
991 // the superclass.
992 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
993 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000994 SuperLoc, Sel, /*Method=*/0,
995 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000996}
997
998/// \brief Build an Objective-C class message expression.
999///
1000/// This routine takes care of both normal class messages and
1001/// class messages to the superclass.
1002///
1003/// \param ReceiverTypeInfo Type source information that describes the
1004/// receiver of this message. This may be NULL, in which case we are
1005/// sending to the superclass and \p SuperLoc must be a valid source
1006/// location.
1007
1008/// \param ReceiverType The type of the object receiving the
1009/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1010/// type as that refers to. For a superclass send, this is the type of
1011/// the superclass.
1012///
1013/// \param SuperLoc The location of the "super" keyword in a
1014/// superclass message.
1015///
1016/// \param Sel The selector to which the message is being sent.
1017///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001018/// \param Method The method that this class message is invoking, if
1019/// already known.
1020///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001021/// \param LBracLoc The location of the opening square bracket ']'.
1022///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001023/// \param RBrac The location of the closing square bracket ']'.
1024///
1025/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001026ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001027 QualType ReceiverType,
1028 SourceLocation SuperLoc,
1029 Selector Sel,
1030 ObjCMethodDecl *Method,
1031 SourceLocation LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001032 SourceLocation SelectorLoc,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001033 SourceLocation RBracLoc,
1034 MultiExprArg ArgsIn) {
1035 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001036 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001037 if (LBracLoc.isInvalid()) {
1038 Diag(Loc, diag::err_missing_open_square_message_send)
1039 << FixItHint::CreateInsertion(Loc, "[");
1040 LBracLoc = Loc;
1041 }
1042
Douglas Gregor92e986e2010-04-22 16:44:27 +00001043 if (ReceiverType->isDependentType()) {
1044 // If the receiver type is dependent, we can't type-check anything
1045 // at this point. Build a dependent expression.
1046 unsigned NumArgs = ArgsIn.size();
1047 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1048 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001049 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1050 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001051 Sel, SelectorLoc, /*Method=*/0,
Douglas Gregor92e986e2010-04-22 16:44:27 +00001052 Args, NumArgs, RBracLoc));
1053 }
Chris Lattner15faee12010-04-12 05:38:43 +00001054
Douglas Gregor2725ca82010-04-21 19:57:20 +00001055 // Find the class to which we are sending this message.
1056 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001057 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1058 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001059 Diag(Loc, diag::err_invalid_receiver_class_message)
1060 << ReceiverType;
1061 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001062 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001063 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian02b0d652011-03-08 19:12:46 +00001064 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001065 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001066 if (!Method) {
1067 if (Class->isForwardDecl()) {
John McCallf85e1932011-06-15 23:02:42 +00001068 if (getLangOptions().ObjCAutoRefCount) {
1069 Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
1070 } else {
1071 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1072 }
1073
Douglas Gregorf49bb082010-04-22 17:01:48 +00001074 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001075 Method = LookupFactoryMethodInGlobalPool(Sel,
1076 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001077 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001078 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1079 << Method->getDeclName();
1080 }
1081 if (!Method)
1082 Method = Class->lookupClassMethod(Sel);
1083
1084 // If we have an implementation in scope, check "private" methods.
1085 if (!Method)
1086 Method = LookupPrivateClassMethod(Sel, Class);
1087
1088 if (Method && DiagnoseUseOfDecl(Method, Loc))
1089 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001090 }
Mike Stump1eb44332009-09-09 15:08:12 +00001091
Douglas Gregor2725ca82010-04-21 19:57:20 +00001092 // Check the argument types and determine the result type.
1093 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001094 ExprValueKind VK = VK_RValue;
1095
Douglas Gregor2725ca82010-04-21 19:57:20 +00001096 unsigned NumArgs = ArgsIn.size();
1097 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001098 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1099 SuperLoc.isValid(), LBracLoc, RBracLoc,
1100 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001101 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001102
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001103 if (Method && !Method->getResultType()->isVoidType() &&
1104 RequireCompleteType(LBracLoc, Method->getResultType(),
1105 diag::err_illegal_message_expr_incomplete_type))
1106 return ExprError();
1107
Douglas Gregor2725ca82010-04-21 19:57:20 +00001108 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001109 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001110 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001111 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001112 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001113 ReceiverType, Sel, SelectorLoc,
1114 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001115 else
John McCallf89e55a2010-11-18 06:31:45 +00001116 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001117 ReceiverTypeInfo, Sel, SelectorLoc,
1118 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001119 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001120}
1121
Douglas Gregor2725ca82010-04-21 19:57:20 +00001122// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001123// ArgExprs is optional - if it is present, the number of expressions
1124// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001125ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001126 ParsedType Receiver,
1127 Selector Sel,
1128 SourceLocation LBracLoc,
1129 SourceLocation SelectorLoc,
1130 SourceLocation RBracLoc,
1131 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001132 TypeSourceInfo *ReceiverTypeInfo;
1133 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1134 if (ReceiverType.isNull())
1135 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001136
Mike Stump1eb44332009-09-09 15:08:12 +00001137
Douglas Gregor2725ca82010-04-21 19:57:20 +00001138 if (!ReceiverTypeInfo)
1139 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1140
1141 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001142 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001143 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001144}
1145
1146/// \brief Build an Objective-C instance message expression.
1147///
1148/// This routine takes care of both normal instance messages and
1149/// instance messages to the superclass instance.
1150///
1151/// \param Receiver The expression that computes the object that will
1152/// receive this message. This may be empty, in which case we are
1153/// sending to the superclass instance and \p SuperLoc must be a valid
1154/// source location.
1155///
1156/// \param ReceiverType The (static) type of the object receiving the
1157/// message. When a \p Receiver expression is provided, this is the
1158/// same type as that expression. For a superclass instance send, this
1159/// is a pointer to the type of the superclass.
1160///
1161/// \param SuperLoc The location of the "super" keyword in a
1162/// superclass instance message.
1163///
1164/// \param Sel The selector to which the message is being sent.
1165///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001166/// \param Method The method that this instance message is invoking, if
1167/// already known.
1168///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001169/// \param LBracLoc The location of the opening square bracket ']'.
1170///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001171/// \param RBrac The location of the closing square bracket ']'.
1172///
1173/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001174ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001175 QualType ReceiverType,
1176 SourceLocation SuperLoc,
1177 Selector Sel,
1178 ObjCMethodDecl *Method,
1179 SourceLocation LBracLoc,
1180 SourceLocation SelectorLoc,
1181 SourceLocation RBracLoc,
1182 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001183 // The location of the receiver.
1184 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1185
1186 if (LBracLoc.isInvalid()) {
1187 Diag(Loc, diag::err_missing_open_square_message_send)
1188 << FixItHint::CreateInsertion(Loc, "[");
1189 LBracLoc = Loc;
1190 }
1191
Douglas Gregor2725ca82010-04-21 19:57:20 +00001192 // If we have a receiver expression, perform appropriate promotions
1193 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001194 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001195 if (Receiver->isTypeDependent()) {
1196 // If the receiver is type-dependent, we can't type-check anything
1197 // at this point. Build a dependent expression.
1198 unsigned NumArgs = ArgsIn.size();
1199 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1200 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1201 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001202 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001203 SelectorLoc, /*Method=*/0,
1204 Args, NumArgs, RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001205 }
1206
Douglas Gregor2725ca82010-04-21 19:57:20 +00001207 // If necessary, apply function/array conversion to the receiver.
1208 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001209 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1210 if (Result.isInvalid())
1211 return ExprError();
1212 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001213 ReceiverType = Receiver->getType();
1214 }
1215
Douglas Gregorf49bb082010-04-22 17:01:48 +00001216 if (!Method) {
1217 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001218 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001219 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001220 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1221 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001222 SourceRange(LBracLoc, RBracLoc),
1223 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001224 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001225 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001226 SourceRange(LBracLoc, RBracLoc),
1227 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001228 } else if (ReceiverType->isObjCClassType() ||
1229 ReceiverType->isObjCQualifiedClassType()) {
1230 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001231 // We allow sending a message to a qualified Class ("Class<foo>"), which
1232 // is ok as long as one of the protocols implements the selector (if not, warn).
1233 if (const ObjCObjectPointerType *QClassTy
1234 = ReceiverType->getAsObjCQualifiedClassType()) {
1235 // Search protocols for class methods.
1236 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1237 if (!Method) {
1238 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1239 // warn if instance method found for a Class message.
1240 if (Method) {
1241 Diag(Loc, diag::warn_instance_method_on_class_found)
1242 << Method->getSelector() << Sel;
1243 Diag(Method->getLocation(), diag::note_method_declared_at);
1244 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001245 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001246 } else {
1247 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1248 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1249 // First check the public methods in the class interface.
1250 Method = ClassDecl->lookupClassMethod(Sel);
1251
1252 if (!Method)
1253 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1254 }
1255 if (Method && DiagnoseUseOfDecl(Method, Loc))
1256 return ExprError();
1257 }
1258 if (!Method) {
1259 // If not messaging 'self', look for any factory method named 'Sel'.
1260 if (!Receiver || !isSelfExpr(Receiver)) {
1261 Method = LookupFactoryMethodInGlobalPool(Sel,
1262 SourceRange(LBracLoc, RBracLoc),
1263 true);
1264 if (!Method) {
1265 // If no class (factory) method was found, check if an _instance_
1266 // method of the same name exists in the root class only.
1267 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001268 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001269 true);
1270 if (Method)
1271 if (const ObjCInterfaceDecl *ID =
1272 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1273 if (ID->getSuperClass())
1274 Diag(Loc, diag::warn_root_inst_method_not_found)
1275 << Sel << SourceRange(LBracLoc, RBracLoc);
1276 }
1277 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001278 }
1279 }
1280 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001281 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001282 ObjCInterfaceDecl* ClassDecl = 0;
1283
1284 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1285 // long as one of the protocols implements the selector (if not, warn).
1286 if (const ObjCObjectPointerType *QIdTy
1287 = ReceiverType->getAsObjCQualifiedIdType()) {
1288 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001289 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1290 if (!Method)
1291 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001292 } else if (const ObjCObjectPointerType *OCIType
1293 = ReceiverType->getAsObjCInterfacePointerType()) {
1294 // We allow sending a message to a pointer to an interface (an object).
1295 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001296
1297 if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCount) {
1298 Diag(Loc, diag::err_arc_receiver_forward_instance)
1299 << OCIType->getPointeeType()
1300 << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperLoc));
1301 return ExprError();
1302 }
1303
Douglas Gregorf49bb082010-04-22 17:01:48 +00001304 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1305 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +00001306 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001307 Method = ClassDecl->lookupInstanceMethod(Sel);
1308
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001309 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001310 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001311 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1312
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001313 const ObjCInterfaceDecl *forwardClass = 0;
Douglas Gregorf49bb082010-04-22 17:01:48 +00001314 if (!Method) {
1315 // If we have implementations in scope, check "private" methods.
1316 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1317
John McCallf85e1932011-06-15 23:02:42 +00001318 if (!Method && getLangOptions().ObjCAutoRefCount) {
1319 Diag(Loc, diag::err_arc_may_not_respond)
1320 << OCIType->getPointeeType() << Sel;
1321 return ExprError();
1322 }
1323
Douglas Gregorf49bb082010-04-22 17:01:48 +00001324 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1325 // If we still haven't found a method, look in the global pool. This
1326 // behavior isn't very desirable, however we need it for GCC
1327 // compatibility. FIXME: should we deviate??
1328 if (OCIType->qual_empty()) {
1329 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001330 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001331 if (OCIType->getInterfaceDecl()->isForwardDecl())
1332 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001333 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001334 Diag(Loc, diag::warn_maynot_respond)
1335 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1336 }
1337 }
1338 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001339 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001340 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001341 } else if (!getLangOptions().ObjCAutoRefCount &&
1342 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001343 (ReceiverType->isPointerType() ||
1344 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001345 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001346 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001347 Diag(Loc, diag::warn_bad_receiver_type)
1348 << ReceiverType
1349 << Receiver->getSourceRange();
1350 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001351 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1352 CK_BitCast).take();
John McCall404cd162010-11-13 01:35:44 +00001353 else {
1354 // TODO: specialized warning on null receivers?
1355 bool IsNull = Receiver->isNullPointerConstant(Context,
1356 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001357 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1358 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001359 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001360 ReceiverType = Receiver->getType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00001361 }
John Wiegley429bb272011-04-08 18:41:53 +00001362 else {
1363 ExprResult ReceiverRes;
1364 if (getLangOptions().CPlusPlus)
1365 ReceiverRes = PerformContextuallyConvertToObjCId(Receiver);
1366 if (ReceiverRes.isUsable()) {
1367 Receiver = ReceiverRes.take();
1368 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
1369 Receiver = ICE->getSubExpr();
1370 ReceiverType = Receiver->getType();
1371 }
1372 return BuildInstanceMessage(Receiver,
1373 ReceiverType,
1374 SuperLoc,
1375 Sel,
1376 Method,
1377 LBracLoc,
1378 SelectorLoc,
1379 RBracLoc,
1380 move(ArgsIn));
1381 } else {
1382 // Reject other random receiver types (e.g. structs).
1383 Diag(Loc, diag::err_bad_receiver_type)
1384 << ReceiverType << Receiver->getSourceRange();
1385 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001386 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001387 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001388 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001389 }
Mike Stump1eb44332009-09-09 15:08:12 +00001390
Douglas Gregor2725ca82010-04-21 19:57:20 +00001391 // Check the message arguments.
1392 unsigned NumArgs = ArgsIn.size();
1393 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1394 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001395 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001396 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1397 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001398 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1399 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001400 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001401 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001402
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001403 if (Method && !Method->getResultType()->isVoidType() &&
1404 RequireCompleteType(LBracLoc, Method->getResultType(),
1405 diag::err_illegal_message_expr_incomplete_type))
1406 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001407
John McCallf85e1932011-06-15 23:02:42 +00001408 // In ARC, forbid the user from sending messages to
1409 // retain/release/autorelease/dealloc/retainCount explicitly.
1410 if (getLangOptions().ObjCAutoRefCount) {
1411 ObjCMethodFamily family =
1412 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1413 switch (family) {
1414 case OMF_init:
1415 if (Method)
1416 checkInitMethod(Method, ReceiverType);
1417
1418 case OMF_None:
1419 case OMF_alloc:
1420 case OMF_copy:
1421 case OMF_mutableCopy:
1422 case OMF_new:
1423 case OMF_self:
1424 break;
1425
1426 case OMF_dealloc:
1427 case OMF_retain:
1428 case OMF_release:
1429 case OMF_autorelease:
1430 case OMF_retainCount:
1431 Diag(Loc, diag::err_arc_illegal_explicit_message)
1432 << Sel << SelectorLoc;
1433 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001434
1435 case OMF_performSelector:
1436 if (Method && NumArgs >= 1) {
1437 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1438 Selector ArgSel = SelExp->getSelector();
1439 ObjCMethodDecl *SelMethod =
1440 LookupInstanceMethodInGlobalPool(ArgSel,
1441 SelExp->getSourceRange());
1442 if (!SelMethod)
1443 SelMethod =
1444 LookupFactoryMethodInGlobalPool(ArgSel,
1445 SelExp->getSourceRange());
1446 if (SelMethod) {
1447 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1448 switch (SelFamily) {
1449 case OMF_alloc:
1450 case OMF_copy:
1451 case OMF_mutableCopy:
1452 case OMF_new:
1453 case OMF_self:
1454 case OMF_init:
1455 // Issue error, unless ns_returns_not_retained.
1456 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1457 // selector names a +1 method
1458 Diag(SelectorLoc,
1459 diag::err_arc_perform_selector_retains);
1460 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1461 }
1462 break;
1463 default:
1464 // +0 call. OK. unless ns_returns_retained.
1465 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1466 // selector names a +1 method
1467 Diag(SelectorLoc,
1468 diag::err_arc_perform_selector_retains);
1469 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1470 }
1471 break;
1472 }
1473 }
1474 } else {
1475 // error (may leak).
1476 Diag(SelectorLoc, diag::warn_arc_perform_selector_leaks);
1477 Diag(Args[0]->getExprLoc(), diag::note_used_here);
1478 }
1479 }
1480 break;
John McCallf85e1932011-06-15 23:02:42 +00001481 }
1482 }
1483
Douglas Gregor2725ca82010-04-21 19:57:20 +00001484 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001485 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001486 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001487 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001488 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001489 ReceiverType, Sel, SelectorLoc, Method,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001490 Args, NumArgs, RBracLoc);
1491 else
John McCallf89e55a2010-11-18 06:31:45 +00001492 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001493 Receiver, Sel, SelectorLoc, Method,
1494 Args, NumArgs, RBracLoc);
John McCallf85e1932011-06-15 23:02:42 +00001495
1496 if (getLangOptions().ObjCAutoRefCount) {
1497 // In ARC, annotate delegate init calls.
1498 if (Result->getMethodFamily() == OMF_init &&
1499 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
1500 // Only consider init calls *directly* in init implementations,
1501 // not within blocks.
1502 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1503 if (method && method->getMethodFamily() == OMF_init) {
1504 // The implicit assignment to self means we also don't want to
1505 // consume the result.
1506 Result->setDelegateInitCall(true);
1507 return Owned(Result);
1508 }
1509 }
1510
1511 // In ARC, check for message sends which are likely to introduce
1512 // retain cycles.
1513 checkRetainCycles(Result);
1514 }
1515
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001516 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001517}
1518
1519// ActOnInstanceMessage - used for both unary and keyword messages.
1520// ArgExprs is optional - if it is present, the number of expressions
1521// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001522ExprResult Sema::ActOnInstanceMessage(Scope *S,
1523 Expr *Receiver,
1524 Selector Sel,
1525 SourceLocation LBracLoc,
1526 SourceLocation SelectorLoc,
1527 SourceLocation RBracLoc,
1528 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001529 if (!Receiver)
1530 return ExprError();
1531
John McCall9ae2f072010-08-23 23:25:46 +00001532 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001533 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001534 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001535}
Chris Lattnereca7be62008-04-07 05:30:13 +00001536
John McCallf85e1932011-06-15 23:02:42 +00001537enum ARCConversionTypeClass {
1538 ACTC_none,
1539 ACTC_retainable,
1540 ACTC_indirectRetainable
1541};
1542static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
1543 ARCConversionTypeClass ACTC = ACTC_retainable;
1544
1545 // Ignore an outermost reference type.
1546 if (const ReferenceType *ref = type->getAs<ReferenceType>())
1547 type = ref->getPointeeType();
1548
1549 // Drill through pointers and arrays recursively.
1550 while (true) {
1551 if (const PointerType *ptr = type->getAs<PointerType>()) {
1552 type = ptr->getPointeeType();
1553 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1554 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1555 } else {
1556 break;
1557 }
1558 ACTC = ACTC_indirectRetainable;
1559 }
1560
1561 if (!type->isObjCRetainableType()) return ACTC_none;
1562 return ACTC;
1563}
1564
1565namespace {
1566 /// Return true if the given expression can be reasonably converted
1567 /// between a retainable pointer type and a C pointer type.
1568 struct ARCCastChecker : StmtVisitor<ARCCastChecker, bool> {
1569 ASTContext &Context;
1570 ARCCastChecker(ASTContext &Context) : Context(Context) {}
1571 bool VisitStmt(Stmt *s) {
1572 return false;
1573 }
1574 bool VisitExpr(Expr *e) {
1575 return e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
1576 }
1577
1578 bool VisitParenExpr(ParenExpr *e) {
1579 return Visit(e->getSubExpr());
1580 }
1581 bool VisitCastExpr(CastExpr *e) {
1582 switch (e->getCastKind()) {
1583 case CK_NullToPointer:
1584 return true;
1585 case CK_NoOp:
1586 case CK_LValueToRValue:
1587 case CK_BitCast:
1588 case CK_AnyPointerToObjCPointerCast:
1589 case CK_AnyPointerToBlockPointerCast:
1590 return Visit(e->getSubExpr());
1591 default:
1592 return false;
1593 }
1594 }
1595 bool VisitUnaryExtension(UnaryOperator *e) {
1596 return Visit(e->getSubExpr());
1597 }
1598 bool VisitBinComma(BinaryOperator *e) {
1599 return Visit(e->getRHS());
1600 }
1601 bool VisitConditionalOperator(ConditionalOperator *e) {
1602 // Conditional operators are okay if both sides are okay.
1603 return Visit(e->getTrueExpr()) && Visit(e->getFalseExpr());
1604 }
1605 bool VisitObjCStringLiteral(ObjCStringLiteral *e) {
1606 // Always white-list Objective-C string literals.
1607 return true;
1608 }
1609 bool VisitStmtExpr(StmtExpr *e) {
1610 return Visit(e->getSubStmt()->body_back());
1611 }
1612 bool VisitDeclRefExpr(DeclRefExpr *e) {
1613 // White-list references to global extern strings from system
1614 // headers.
1615 if (VarDecl *var = dyn_cast<VarDecl>(e->getDecl()))
1616 if (var->getStorageClass() == SC_Extern &&
1617 var->getType().isConstQualified() &&
1618 Context.getSourceManager().isInSystemHeader(var->getLocation()))
1619 return true;
1620 return false;
1621 }
1622 };
1623}
1624
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001625bool
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001626Sema::ValidObjCARCNoBridgeCastExpr(Expr *&Exp, QualType castType) {
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001627 Expr *NewExp = Exp->IgnoreParenCasts();
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001628
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001629 if (!isa<ObjCMessageExpr>(NewExp) && !isa<ObjCPropertyRefExpr>(NewExp)
1630 && !isa<CallExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001631 return false;
1632 ObjCMethodDecl *method = 0;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001633 bool MethodReturnsPlusOne = false;
1634
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001635 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(NewExp)) {
1636 method = PRE->getExplicitProperty()->getGetterMethodDecl();
1637 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001638 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001639 method = ME->getMethodDecl();
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001640 else {
1641 CallExpr *CE = cast<CallExpr>(NewExp);
1642 Decl *CallDecl = CE->getCalleeDecl();
1643 if (!CallDecl)
1644 return false;
1645 if (CallDecl->hasAttr<CFReturnsNotRetainedAttr>())
1646 return true;
1647 MethodReturnsPlusOne = CallDecl->hasAttr<CFReturnsRetainedAttr>();
1648 if (!MethodReturnsPlusOne) {
1649 if (NamedDecl *ND = dyn_cast<NamedDecl>(CallDecl))
1650 if (const IdentifierInfo *Id = ND->getIdentifier())
1651 if (Id->isStr("__builtin___CFStringMakeConstantString"))
1652 return true;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001653 }
1654 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001655
1656 if (!MethodReturnsPlusOne) {
1657 if (!method)
1658 return false;
1659 if (method->hasAttr<CFReturnsNotRetainedAttr>())
1660 return true;
1661 MethodReturnsPlusOne = method->hasAttr<CFReturnsRetainedAttr>();
1662 if (!MethodReturnsPlusOne) {
1663 ObjCMethodFamily family = method->getSelector().getMethodFamily();
1664 switch (family) {
1665 case OMF_alloc:
1666 case OMF_copy:
1667 case OMF_mutableCopy:
1668 case OMF_new:
1669 MethodReturnsPlusOne = true;
1670 break;
1671 default:
1672 break;
1673 }
1674 }
1675 }
1676
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001677 if (MethodReturnsPlusOne) {
1678 TypeSourceInfo *TSInfo =
1679 Context.getTrivialTypeSourceInfo(castType, SourceLocation());
1680 ExprResult ExpRes = BuildObjCBridgedCast(SourceLocation(), OBC_BridgeTransfer,
1681 SourceLocation(), TSInfo, Exp);
1682 Exp = ExpRes.take();
1683 }
1684 return true;
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001685}
1686
John McCallf85e1932011-06-15 23:02:42 +00001687void
1688Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001689 Expr *&castExpr, CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00001690 QualType castExprType = castExpr->getType();
1691
1692 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1693 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
1694 if (exprACTC == castACTC) return;
Fariborz Jahanian8295b7b2011-06-22 16:36:45 +00001695 if (exprACTC && castType->isIntegralType(Context)) return;
John McCallf85e1932011-06-15 23:02:42 +00001696
1697 // Allow casts between pointers to lifetime types (e.g., __strong id*)
1698 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1699 // must be explicit.
1700 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
1701 if (const PointerType *CastExprPtr = castExprType->getAs<PointerType>()) {
1702 QualType CastPointee = CastPtr->getPointeeType();
1703 QualType CastExprPointee = CastExprPtr->getPointeeType();
1704 if ((CCK != CCK_ImplicitConversion &&
1705 CastPointee->isObjCIndirectLifetimeType() &&
1706 CastExprPointee->isVoidType()) ||
1707 (CastPointee->isVoidType() &&
1708 CastExprPointee->isObjCIndirectLifetimeType()))
1709 return;
1710 }
1711 }
1712
1713 if (ARCCastChecker(Context).Visit(castExpr))
1714 return;
1715
1716 SourceLocation loc =
1717 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
1718
1719 if (makeUnavailableInSystemHeader(loc,
1720 "converts between Objective-C and C pointers in -fobjc-arc"))
1721 return;
1722
John McCall71c482c2011-06-17 06:50:50 +00001723 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00001724 switch (exprACTC) {
1725 case ACTC_none:
1726 srcKind = (castExprType->isPointerType() ? 1 : 0);
1727 break;
1728 case ACTC_retainable:
1729 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1730 break;
1731 case ACTC_indirectRetainable:
1732 srcKind = 4;
1733 break;
1734 }
1735
1736 if (CCK == CCK_CStyleCast) {
1737 // Check whether this could be fixed with a bridge cast.
1738 SourceLocation AfterLParen = PP.getLocForEndOfToken(castRange.getBegin());
1739 SourceLocation NoteLoc = AfterLParen.isValid()? AfterLParen : loc;
1740
1741 if (castType->isObjCARCBridgableType() &&
1742 castExprType->isCARCBridgableType()) {
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001743 // explicit unbridged casts are allowed if the source of the cast is a
1744 // message sent to an objc method (or property access)
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001745 if (ValidObjCARCNoBridgeCastExpr(castExpr, castType))
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001746 return;
John McCallf85e1932011-06-15 23:02:42 +00001747 Diag(loc, diag::err_arc_cast_requires_bridge)
1748 << 2
1749 << castExprType
1750 << (castType->isBlockPointerType()? 1 : 0)
1751 << castType
1752 << castRange
1753 << castExpr->getSourceRange();
1754 Diag(NoteLoc, diag::note_arc_bridge)
1755 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1756 Diag(NoteLoc, diag::note_arc_bridge_transfer)
1757 << castExprType
1758 << FixItHint::CreateInsertion(AfterLParen, "__bridge_transfer ");
1759
1760 return;
1761 }
1762
1763 if (castType->isCARCBridgableType() &&
1764 castExprType->isObjCARCBridgableType()){
1765 Diag(loc, diag::err_arc_cast_requires_bridge)
1766 << (castExprType->isBlockPointerType()? 1 : 0)
1767 << castExprType
1768 << 2
1769 << castType
1770 << castRange
1771 << castExpr->getSourceRange();
1772
1773 Diag(NoteLoc, diag::note_arc_bridge)
1774 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1775 Diag(NoteLoc, diag::note_arc_bridge_retained)
1776 << castType
1777 << FixItHint::CreateInsertion(AfterLParen, "__bridge_retained ");
1778 return;
1779 }
1780 }
1781
1782 Diag(loc, diag::err_arc_mismatched_cast)
1783 << (CCK != CCK_ImplicitConversion) << srcKind << castExprType << castType
1784 << castRange << castExpr->getSourceRange();
1785}
1786
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00001787bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
1788 QualType exprType) {
1789 QualType canCastType =
1790 Context.getCanonicalType(castType).getUnqualifiedType();
1791 QualType canExprType =
1792 Context.getCanonicalType(exprType).getUnqualifiedType();
1793 if (isa<ObjCObjectPointerType>(canCastType) &&
1794 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
1795 canExprType->isObjCObjectPointerType()) {
1796 if (const ObjCObjectPointerType *ObjT =
1797 canExprType->getAs<ObjCObjectPointerType>())
1798 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
1799 return false;
1800 }
1801 return true;
1802}
1803
John McCall7e5e5f42011-07-07 06:58:02 +00001804/// Look for an ObjCReclaimReturnedObject cast and destroy it.
1805static Expr *maybeUndoReclaimObject(Expr *e) {
1806 // For now, we just undo operands that are *immediately* reclaim
1807 // expressions, which prevents the vast majority of potential
1808 // problems here. To catch them all, we'd need to rebuild arbitrary
1809 // value-propagating subexpressions --- we can't reliably rebuild
1810 // in-place because of expression sharing.
1811 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
1812 if (ice->getCastKind() == CK_ObjCReclaimReturnedObject)
1813 return ice->getSubExpr();
1814
1815 return e;
1816}
1817
John McCallf85e1932011-06-15 23:02:42 +00001818ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
1819 ObjCBridgeCastKind Kind,
1820 SourceLocation BridgeKeywordLoc,
1821 TypeSourceInfo *TSInfo,
1822 Expr *SubExpr) {
1823 QualType T = TSInfo->getType();
1824 QualType FromType = SubExpr->getType();
1825
1826 bool MustConsume = false;
1827 if (T->isDependentType() || SubExpr->isTypeDependent()) {
1828 // Okay: we'll build a dependent expression type.
1829 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
1830 // Casting CF -> id
1831 switch (Kind) {
1832 case OBC_Bridge:
1833 break;
1834
1835 case OBC_BridgeRetained:
1836 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1837 << 2
1838 << FromType
1839 << (T->isBlockPointerType()? 1 : 0)
1840 << T
1841 << SubExpr->getSourceRange()
1842 << Kind;
1843 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1844 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
1845 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
1846 << FromType
1847 << FixItHint::CreateReplacement(BridgeKeywordLoc,
1848 "__bridge_transfer ");
1849
1850 Kind = OBC_Bridge;
1851 break;
1852
1853 case OBC_BridgeTransfer:
1854 // We must consume the Objective-C object produced by the cast.
1855 MustConsume = true;
1856 break;
1857 }
1858 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
1859 // Okay: id -> CF
1860 switch (Kind) {
1861 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00001862 // Reclaiming a value that's going to be __bridge-casted to CF
1863 // is very dangerous, so we don't do it.
1864 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00001865 break;
1866
1867 case OBC_BridgeRetained:
1868 // Produce the object before casting it.
1869 SubExpr = ImplicitCastExpr::Create(Context, FromType,
1870 CK_ObjCProduceObject,
1871 SubExpr, 0, VK_RValue);
1872 break;
1873
1874 case OBC_BridgeTransfer:
1875 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1876 << (FromType->isBlockPointerType()? 1 : 0)
1877 << FromType
1878 << 2
1879 << T
1880 << SubExpr->getSourceRange()
1881 << Kind;
1882
1883 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1884 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
1885 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
1886 << T
1887 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
1888
1889 Kind = OBC_Bridge;
1890 break;
1891 }
1892 } else {
1893 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
1894 << FromType << T << Kind
1895 << SubExpr->getSourceRange()
1896 << TSInfo->getTypeLoc().getSourceRange();
1897 return ExprError();
1898 }
1899
1900 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind,
1901 BridgeKeywordLoc,
1902 TSInfo, SubExpr);
1903
1904 if (MustConsume) {
1905 ExprNeedsCleanups = true;
1906 Result = ImplicitCastExpr::Create(Context, T, CK_ObjCConsumeObject, Result,
1907 0, VK_RValue);
1908 }
1909
1910 return Result;
1911}
1912
1913ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
1914 SourceLocation LParenLoc,
1915 ObjCBridgeCastKind Kind,
1916 SourceLocation BridgeKeywordLoc,
1917 ParsedType Type,
1918 SourceLocation RParenLoc,
1919 Expr *SubExpr) {
1920 TypeSourceInfo *TSInfo = 0;
1921 QualType T = GetTypeFromParser(Type, &TSInfo);
1922 if (!TSInfo)
1923 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
1924 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
1925 SubExpr);
1926}