blob: f7f00f3f91b3f476c3e1af878799b69dd93b1fb8 [file] [log] [blame]
Chris Lattner85a932e2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000016#include "clang/Sema/Scope.h"
John McCall26743b22011-02-03 09:00:02 +000017#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000018#include "clang/Sema/Initialization.h"
Chris Lattner85a932e2008-01-04 22:32:30 +000019#include "clang/AST/ASTContext.h"
20#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000021#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000022#include "clang/AST/StmtVisitor.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000023#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000024#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000025#include "clang/Lex/Preprocessor.h"
26
Chris Lattner85a932e2008-01-04 22:32:30 +000027using namespace clang;
John McCall26743b22011-02-03 09:00:02 +000028using namespace sema;
Chris Lattner85a932e2008-01-04 22:32:30 +000029
John McCallf312b1e2010-08-26 23:41:50 +000030ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
31 Expr **strings,
32 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000033 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
34
Chris Lattnerf4b136f2009-02-18 06:13:04 +000035 // Most ObjC strings are formed out of a single piece. However, we *can*
36 // have strings formed out of multiple @ strings with multiple pptokens in
37 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
38 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner39c28bb2009-02-18 06:48:40 +000039 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000040
Chris Lattnerf4b136f2009-02-18 06:13:04 +000041 // If we have a multi-part string, merge it all together.
42 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000043 // Concatenate objc strings.
Chris Lattner39c28bb2009-02-18 06:48:40 +000044 llvm::SmallString<128> StrBuf;
Chris Lattner5f9e2722011-07-23 10:55:15 +000045 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000046
Chris Lattner726e1682009-02-18 05:49:11 +000047 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000048 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000049
Douglas Gregor5cee1192011-07-27 05:40:30 +000050 // ObjC strings can't be wide or UTF.
51 if (!S->isAscii()) {
Chris Lattnerf4b136f2009-02-18 06:13:04 +000052 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
53 << S->getSourceRange();
54 return true;
55 }
Mike Stump1eb44332009-09-09 15:08:12 +000056
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +000057 // Append the string.
58 StrBuf += S->getString();
Mike Stump1eb44332009-09-09 15:08:12 +000059
Chris Lattner39c28bb2009-02-18 06:48:40 +000060 // Get the locations of the string tokens.
61 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattner85a932e2008-01-04 22:32:30 +000062 }
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattner39c28bb2009-02-18 06:48:40 +000064 // Create the aggregate string with the appropriate content and location
65 // information.
Jay Foad65aa6882011-06-21 15:13:30 +000066 S = StringLiteral::Create(Context, StrBuf,
Douglas Gregor5cee1192011-07-27 05:40:30 +000067 StringLiteral::Ascii, /*Pascal=*/false,
Chris Lattner2085fd62009-02-18 06:40:38 +000068 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000069 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000070 }
Mike Stump1eb44332009-09-09 15:08:12 +000071
Chris Lattner69039812009-02-18 06:01:06 +000072 // Verify that this composite string is acceptable for ObjC strings.
73 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000074 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000075
76 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000077 // the NSString interface is seen in this translation unit. Note: We
78 // don't use NSConstantString, since the runtime team considers this
79 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000080 QualType Ty = Context.getObjCConstantStringInterface();
81 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000082 Ty = Context.getObjCObjectPointerType(Ty);
Fariborz Jahanian8a437762010-04-23 23:19:04 +000083 } else if (getLangOptions().NoConstantCFStrings) {
Fariborz Jahanian4c733072010-10-19 17:19:29 +000084 IdentifierInfo *NSIdent=0;
85 std::string StringClass(getLangOptions().ObjCConstantStringClass);
86
87 if (StringClass.empty())
88 NSIdent = &Context.Idents.get("NSConstantString");
89 else
90 NSIdent = &Context.Idents.get(StringClass);
91
Fariborz Jahanian8a437762010-04-23 23:19:04 +000092 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
93 LookupOrdinaryName);
94 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
95 Context.setObjCConstantStringInterface(StrIF);
96 Ty = Context.getObjCConstantStringInterface();
97 Ty = Context.getObjCObjectPointerType(Ty);
98 } else {
99 // If there is no NSConstantString interface defined then treat this
100 // as error and recover from it.
101 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
102 << S->getSourceRange();
103 Ty = Context.getObjCIdType();
104 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000105 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000106 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +0000107 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
108 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000109 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
110 Context.setObjCConstantStringInterface(StrIF);
111 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000112 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000113 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000114 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000115 // strings as untyped objects and let the runtime figure it out later.
116 Ty = Context.getObjCIdType();
117 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Chris Lattnerf4b136f2009-02-18 06:13:04 +0000120 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +0000121}
122
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000123ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000124 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000125 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000126 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000127 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000128 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000129 StrTy = Context.DependentTy;
130 else {
Fariborz Jahanian6c916152011-06-16 22:34:44 +0000131 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
132 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000133 if (RequireCompleteType(AtLoc, EncodedType,
134 PDiag(diag::err_incomplete_type_objc_at_encode)
135 << EncodedTypeInfo->getTypeLoc().getSourceRange()))
136 return ExprError();
137
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000138 std::string Str;
139 Context.getObjCEncodingForType(EncodedType, Str);
140
141 // The type of @encode is the same as the type of the corresponding string,
142 // which is an array type.
143 StrTy = Context.CharTy;
144 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000145 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000146 StrTy.addConst();
147 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
148 ArrayType::Normal, 0);
149 }
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Douglas Gregor81d34662010-04-20 15:39:42 +0000151 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000152}
153
John McCallf312b1e2010-08-26 23:41:50 +0000154ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
155 SourceLocation EncodeLoc,
156 SourceLocation LParenLoc,
157 ParsedType ty,
158 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000159 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000160 TypeSourceInfo *TInfo;
161 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
162 if (!TInfo)
163 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
164 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000165
Douglas Gregor81d34662010-04-20 15:39:42 +0000166 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000167}
168
John McCallf312b1e2010-08-26 23:41:50 +0000169ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
170 SourceLocation AtLoc,
171 SourceLocation SelLoc,
172 SourceLocation LParenLoc,
173 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000174 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000175 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000176 if (!Method)
177 Method = LookupFactoryMethodInGlobalPool(Sel,
178 SourceRange(LParenLoc, RParenLoc));
179 if (!Method)
180 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian4c91d892011-07-13 19:05:43 +0000181
182 if (!Method ||
183 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
184 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
185 = ReferencedSelectors.find(Sel);
186 if (Pos == ReferencedSelectors.end())
187 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
188 }
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000189
John McCallf85e1932011-06-15 23:02:42 +0000190 // In ARC, forbid the user from using @selector for
191 // retain/release/autorelease/dealloc/retainCount.
192 if (getLangOptions().ObjCAutoRefCount) {
193 switch (Sel.getMethodFamily()) {
194 case OMF_retain:
195 case OMF_release:
196 case OMF_autorelease:
197 case OMF_retainCount:
198 case OMF_dealloc:
199 Diag(AtLoc, diag::err_arc_illegal_selector) <<
200 Sel << SourceRange(LParenLoc, RParenLoc);
201 break;
202
203 case OMF_None:
204 case OMF_alloc:
205 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +0000206 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +0000207 case OMF_init:
208 case OMF_mutableCopy:
209 case OMF_new:
210 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +0000211 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +0000212 break;
213 }
214 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000215 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000216 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000217}
218
John McCallf312b1e2010-08-26 23:41:50 +0000219ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
220 SourceLocation AtLoc,
221 SourceLocation ProtoLoc,
222 SourceLocation LParenLoc,
223 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000224 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000225 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000226 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000227 return true;
228 }
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000230 QualType Ty = Context.getObjCProtoType();
231 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000232 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000233 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000234 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000235}
236
John McCall26743b22011-02-03 09:00:02 +0000237/// Try to capture an implicit reference to 'self'.
238ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
239 // Ignore block scopes: we can capture through them.
240 DeclContext *DC = CurContext;
241 while (true) {
242 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
243 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
244 else break;
245 }
246
247 // If we're not in an ObjC method, error out. Note that, unlike the
248 // C++ case, we don't require an instance method --- class methods
249 // still have a 'self', and we really do still need to capture it!
250 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
251 if (!method)
252 return 0;
253
254 ImplicitParamDecl *self = method->getSelfDecl();
255 assert(self && "capturing 'self' in non-definition?");
256
257 // Mark that we're closing on 'this' in all the block scopes, if applicable.
258 for (unsigned idx = FunctionScopes.size() - 1;
259 isa<BlockScopeInfo>(FunctionScopes[idx]);
John McCall6b5a61b2011-02-07 10:33:21 +0000260 --idx) {
261 BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
262 unsigned &captureIndex = blockScope->CaptureMap[self];
263 if (captureIndex) break;
264
265 bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
266 blockScope->Captures.push_back(
267 BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
268 captureIndex = blockScope->Captures.size(); // +1
269 }
John McCall26743b22011-02-03 09:00:02 +0000270
271 return method;
272}
273
Douglas Gregor926df6c2011-06-11 01:09:30 +0000274QualType Sema::getMessageSendResultType(QualType ReceiverType,
275 ObjCMethodDecl *Method,
276 bool isClassMessage, bool isSuperMessage) {
277 assert(Method && "Must have a method");
278 if (!Method->hasRelatedResultType())
279 return Method->getSendResultType();
280
281 // If a method has a related return type:
282 // - if the method found is an instance method, but the message send
283 // was a class message send, T is the declared return type of the method
284 // found
285 if (Method->isInstanceMethod() && isClassMessage)
286 return Method->getSendResultType();
287
288 // - if the receiver is super, T is a pointer to the class of the
289 // enclosing method definition
290 if (isSuperMessage) {
291 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
292 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
293 return Context.getObjCObjectPointerType(
294 Context.getObjCInterfaceType(Class));
295 }
296
297 // - if the receiver is the name of a class U, T is a pointer to U
298 if (ReceiverType->getAs<ObjCInterfaceType>() ||
299 ReceiverType->isObjCQualifiedInterfaceType())
300 return Context.getObjCObjectPointerType(ReceiverType);
301 // - if the receiver is of type Class or qualified Class type,
302 // T is the declared return type of the method.
303 if (ReceiverType->isObjCClassType() ||
304 ReceiverType->isObjCQualifiedClassType())
305 return Method->getSendResultType();
306
307 // - if the receiver is id, qualified id, Class, or qualified Class, T
308 // is the receiver type, otherwise
309 // - T is the type of the receiver expression.
310 return ReceiverType;
311}
John McCall26743b22011-02-03 09:00:02 +0000312
Douglas Gregor926df6c2011-06-11 01:09:30 +0000313void Sema::EmitRelatedResultTypeNote(const Expr *E) {
314 E = E->IgnoreParenImpCasts();
315 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
316 if (!MsgSend)
317 return;
318
319 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
320 if (!Method)
321 return;
322
323 if (!Method->hasRelatedResultType())
324 return;
325
326 if (Context.hasSameUnqualifiedType(Method->getResultType()
327 .getNonReferenceType(),
328 MsgSend->getType()))
329 return;
330
Douglas Gregore97179c2011-09-08 01:46:34 +0000331 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
332 Context.getObjCInstanceType()))
333 return;
334
Douglas Gregor926df6c2011-06-11 01:09:30 +0000335 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
336 << Method->isInstanceMethod() << Method->getSelector()
337 << MsgSend->getType();
338}
339
340bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
341 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000342 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000343 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000344 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000345 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000346 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000347 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000348 for (unsigned i = 0; i != NumArgs; i++) {
349 if (Args[i]->isTypeDependent())
350 continue;
351
John Wiegley429bb272011-04-08 18:41:53 +0000352 ExprResult Result = DefaultArgumentPromotion(Args[i]);
353 if (Result.isInvalid())
354 return true;
355 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000356 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000357
John McCallf85e1932011-06-15 23:02:42 +0000358 unsigned DiagID;
359 if (getLangOptions().ObjCAutoRefCount)
360 DiagID = diag::err_arc_method_not_found;
361 else
362 DiagID = isClassMessage ? diag::warn_class_method_not_found
363 : diag::warn_inst_method_not_found;
John McCall819e7452011-08-31 20:57:36 +0000364 if (!getLangOptions().DebuggerSupport)
365 Diag(lbrac, DiagID)
366 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +0000367
368 // In debuggers, we want to use __unknown_anytype for these
369 // results so that clients can cast them.
370 if (getLangOptions().DebuggerSupport) {
371 ReturnType = Context.UnknownAnyTy;
372 } else {
373 ReturnType = Context.getObjCIdType();
374 }
John McCallf89e55a2010-11-18 06:31:45 +0000375 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000376 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000377 }
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Douglas Gregor926df6c2011-06-11 01:09:30 +0000379 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
380 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000381 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000382
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000383 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000384 // Method might have more arguments than selector indicates. This is due
385 // to addition of c-style arguments in method.
386 if (Method->param_size() > Sel.getNumArgs())
387 NumNamedArgs = Method->param_size();
388 // FIXME. This need be cleaned up.
389 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000390 Diag(lbrac, diag::err_typecheck_call_too_few_args)
391 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000392 return false;
393 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000394
Chris Lattner312531a2009-04-12 08:11:20 +0000395 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000396 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000397 // We can't do any type-checking on a type-dependent argument.
398 if (Args[i]->isTypeDependent())
399 continue;
400
Chris Lattner85a932e2008-01-04 22:32:30 +0000401 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000402
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000403 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000404 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000405
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000406 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
407 Param->getType(),
408 PDiag(diag::err_call_incomplete_argument)
409 << argExpr->getSourceRange()))
410 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000411
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000412 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
413 Param);
John McCall3fa5cae2010-10-26 07:05:15 +0000414 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000415 if (ArgE.isInvalid())
416 IsError = true;
417 else
418 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000419 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000420
421 // Promote additional arguments to variadic methods.
422 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000423 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
424 if (Args[i]->isTypeDependent())
425 continue;
426
John Wiegley429bb272011-04-08 18:41:53 +0000427 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
428 IsError |= Arg.isInvalid();
429 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000430 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000431 } else {
432 // Check for extra arguments to non-variadic methods.
433 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000434 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000435 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000436 << 2 /*method*/ << NumNamedArgs << NumArgs
437 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000438 << SourceRange(Args[NumNamedArgs]->getLocStart(),
439 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000440 }
441 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000442 // diagnose nonnull arguments.
443 for (specific_attr_iterator<NonNullAttr>
444 i = Method->specific_attr_begin<NonNullAttr>(),
445 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
446 CheckNonNullArguments(*i, Args, lbrac);
447 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000448
Douglas Gregor2725ca82010-04-21 19:57:20 +0000449 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000450 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000451}
452
John McCallf85e1932011-06-15 23:02:42 +0000453bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000454 // 'self' is objc 'self' in an objc method only.
Fariborz Jahanianb4602102011-03-28 16:23:34 +0000455 DeclContext *DC = CurContext;
456 while (isa<BlockDecl>(DC))
457 DC = DC->getParent();
458 if (DC && !isa<ObjCMethodDecl>(DC))
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000459 return false;
John McCallf85e1932011-06-15 23:02:42 +0000460 receiver = receiver->IgnoreParenLValueCasts();
461 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000462 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
463 return true;
464 return false;
465}
466
Steve Narofff1afaf62009-02-26 15:55:06 +0000467// Helper method for ActOnClassMethod/ActOnInstanceMethod.
468// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000469// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000470// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000471ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000472 ObjCInterfaceDecl *ClassDecl) {
473 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000474 // lookup in class and all superclasses
475 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000476 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000477 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Steve Naroff5609ec02009-03-08 18:56:13 +0000479 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000480 if (!Method)
481 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Steve Naroff5609ec02009-03-08 18:56:13 +0000483 // Before we give up, check if the selector is an instance method.
484 // But only in the root. This matches gcc's behaviour and what the
485 // runtime expects.
486 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000487 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000488 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000489 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000490 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000491 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
492 }
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Steve Naroff5609ec02009-03-08 18:56:13 +0000494 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000495 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000496 return Method;
497}
498
499ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
500 ObjCInterfaceDecl *ClassDecl) {
501 ObjCMethodDecl *Method = 0;
502 while (ClassDecl && !Method) {
503 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000504 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000505 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000506
Steve Naroff5609ec02009-03-08 18:56:13 +0000507 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000508 if (!Method)
509 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000510 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000511 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000512 return Method;
513}
514
Fariborz Jahanian61478062011-03-09 20:18:06 +0000515/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
516/// list of a qualified objective pointer type.
517ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
518 const ObjCObjectPointerType *OPT,
519 bool Instance)
520{
521 ObjCMethodDecl *MD = 0;
522 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
523 E = OPT->qual_end(); I != E; ++I) {
524 ObjCProtocolDecl *PROTO = (*I);
525 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
526 return MD;
527 }
528 }
529 return 0;
530}
531
Chris Lattner7f816522010-04-11 07:45:24 +0000532/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
533/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000534ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000535HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000536 Expr *BaseExpr, SourceLocation OpLoc,
537 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000538 SourceLocation MemberLoc,
539 SourceLocation SuperLoc, QualType SuperType,
540 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000541 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
542 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000543
544 if (MemberName.getNameKind() != DeclarationName::Identifier) {
545 Diag(MemberLoc, diag::err_invalid_property_name)
546 << MemberName << QualType(OPT, 0);
547 return ExprError();
548 }
549
Chris Lattner7f816522010-04-11 07:45:24 +0000550 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
551
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000552 if (IFace->isForwardDecl()) {
553 Diag(MemberLoc, diag::err_property_not_found_forward_class)
554 << MemberName << QualType(OPT, 0);
555 Diag(IFace->getLocation(), diag::note_forward_class);
556 return ExprError();
557 }
Chris Lattner7f816522010-04-11 07:45:24 +0000558 // Search for a declared property first.
559 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
560 // Check whether we can reference this property.
561 if (DiagnoseUseOfDecl(PD, MemberLoc))
562 return ExprError();
563 QualType ResTy = PD->getType();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000564 ResTy = ResTy.getNonLValueExprType(Context);
Chris Lattner7f816522010-04-11 07:45:24 +0000565 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
566 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000567 if (Getter &&
568 (Getter->hasRelatedResultType()
569 || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
570 ResTy = getMessageSendResultType(QualType(OPT, 0), Getter, false,
571 Super);
572
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000573 if (Super)
574 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000575 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000576 MemberLoc,
577 SuperLoc, SuperType));
578 else
579 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000580 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000581 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000582 }
583 // Check protocols on qualified interfaces.
584 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
585 E = OPT->qual_end(); I != E; ++I)
586 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
587 // Check whether we can reference this property.
588 if (DiagnoseUseOfDecl(PD, MemberLoc))
589 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000590
591 QualType T = PD->getType();
592 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
593 T = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000594 if (Super)
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,
598 MemberLoc,
599 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000600 else
Douglas Gregor926df6c2011-06-11 01:09:30 +0000601 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000602 VK_LValue,
603 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000604 MemberLoc,
605 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000606 }
607 // If that failed, look for an "implicit" property by seeing if the nullary
608 // selector is implemented.
609
610 // FIXME: The logic for looking up nullary and unary selectors should be
611 // shared with the code in ActOnInstanceMessage.
612
613 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
614 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000615
616 // May be founf in property's qualified list.
617 if (!Getter)
618 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000619
620 // If this reference is in an @implementation, check for 'private' methods.
621 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000622 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000623
624 // Look through local category implementations associated with the class.
625 if (!Getter)
626 Getter = IFace->getCategoryInstanceMethod(Sel);
627 if (Getter) {
628 // Check if we can reference this property.
629 if (DiagnoseUseOfDecl(Getter, MemberLoc))
630 return ExprError();
631 }
632 // If we found a getter then this may be a valid dot-reference, we
633 // will look for the matching setter, in case it is needed.
634 Selector SetterSel =
635 SelectorTable::constructSetterName(PP.getIdentifierTable(),
636 PP.getSelectorTable(), Member);
637 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000638
639 // May be founf in property's qualified list.
640 if (!Setter)
641 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
642
Chris Lattner7f816522010-04-11 07:45:24 +0000643 if (!Setter) {
644 // If this reference is in an @implementation, also check for 'private'
645 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000646 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000647 }
648 // Look through local category implementations associated with the class.
649 if (!Setter)
650 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000651
Chris Lattner7f816522010-04-11 07:45:24 +0000652 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
653 return ExprError();
654
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000655 if (Getter || Setter) {
656 QualType PType;
657 if (Getter)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000658 PType = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000659 else {
660 ParmVarDecl *ArgDecl = *Setter->param_begin();
661 PType = ArgDecl->getType();
662 }
663
John McCall09431682010-11-18 19:01:18 +0000664 ExprValueKind VK = VK_LValue;
665 ExprObjectKind OK = OK_ObjCProperty;
666 if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
667 PType->isVoidType())
668 VK = VK_RValue, OK = OK_Ordinary;
669
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000670 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000671 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
672 PType, VK, OK,
673 MemberLoc,
674 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000675 else
John McCall12f78a62010-12-02 01:19:52 +0000676 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
677 PType, VK, OK,
678 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000679
Chris Lattner7f816522010-04-11 07:45:24 +0000680 }
681
682 // Attempt to correct for typos in property names.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000683 TypoCorrection Corrected = CorrectTypo(
684 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
685 NULL, IFace, false, CTC_NoKeywords, OPT);
686 if (ObjCPropertyDecl *Property =
687 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>()) {
688 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +0000689 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000690 << MemberName << QualType(OPT, 0) << TypoResult
691 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000692 Diag(Property->getLocation(), diag::note_previous_decl)
693 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000694 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
695 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000696 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000697 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000698 ObjCInterfaceDecl *ClassDeclared;
699 if (ObjCIvarDecl *Ivar =
700 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
701 QualType T = Ivar->getType();
702 if (const ObjCObjectPointerType * OBJPT =
703 T->getAsObjCInterfacePointerType()) {
704 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
705 if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
706 if (IFace->isForwardDecl()) {
707 Diag(MemberLoc, diag::err_property_not_as_forward_class)
Fariborz Jahanian2a96bf52011-02-17 17:30:05 +0000708 << MemberName << IFace;
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000709 Diag(IFace->getLocation(), diag::note_forward_class);
710 return ExprError();
711 }
712 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000713 Diag(MemberLoc,
714 diag::err_ivar_access_using_property_syntax_suggest)
715 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
716 << FixItHint::CreateReplacement(OpLoc, "->");
717 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000718 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000719
Chris Lattner7f816522010-04-11 07:45:24 +0000720 Diag(MemberLoc, diag::err_property_not_found)
721 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000722 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000723 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000724 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000725 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000726}
727
728
729
John McCall60d7b3a2010-08-24 06:29:42 +0000730ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000731ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
732 IdentifierInfo &propertyName,
733 SourceLocation receiverNameLoc,
734 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000736 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000737 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
738 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000739
740 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000741 if (IFace == 0) {
742 // If the "receiver" is 'super' in a method, handle it as an expression-like
743 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000744 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000745 IsSuper = true;
746
John McCall26743b22011-02-03 09:00:02 +0000747 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000748 if (CurMethod->isInstanceMethod()) {
749 QualType T =
750 Context.getObjCInterfaceType(CurMethod->getClassInterface());
751 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000752
753 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000754 /*BaseExpr*/0,
755 SourceLocation()/*OpLoc*/,
756 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000757 propertyNameLoc,
758 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000759 }
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Chris Lattnereb483eb2010-04-11 08:28:14 +0000761 // Otherwise, if this is a class method, try dispatching to our
762 // superclass.
763 IFace = CurMethod->getClassInterface()->getSuperClass();
764 }
John McCall26743b22011-02-03 09:00:02 +0000765 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000766
767 if (IFace == 0) {
768 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
769 return ExprError();
770 }
771 }
772
773 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000774 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000775 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000776
777 // If this reference is in an @implementation, check for 'private' methods.
778 if (!Getter)
779 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
780 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000781 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000782 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000783
784 if (Getter) {
785 // FIXME: refactor/share with ActOnMemberReference().
786 // Check if we can reference this property.
787 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
788 return ExprError();
789 }
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Steve Naroff61f72cb2009-03-09 21:12:44 +0000791 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000792 Selector SetterSel =
793 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000794 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000795
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000796 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000797 if (!Setter) {
798 // If this reference is in an @implementation, also check for 'private'
799 // methods.
800 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
801 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000802 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000803 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000804 }
805 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000806 if (!Setter)
807 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000808
809 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
810 return ExprError();
811
812 if (Getter || Setter) {
813 QualType PType;
814
John McCall09431682010-11-18 19:01:18 +0000815 ExprValueKind VK = VK_LValue;
816 if (Getter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000817 PType = getMessageSendResultType(Context.getObjCInterfaceType(IFace),
818 Getter, true,
819 receiverNamePtr->isStr("super"));
John McCall09431682010-11-18 19:01:18 +0000820 if (!getLangOptions().CPlusPlus &&
821 !PType.hasQualifiers() && PType->isVoidType())
822 VK = VK_RValue;
823 } else {
Steve Naroff61f72cb2009-03-09 21:12:44 +0000824 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
825 E = Setter->param_end(); PI != E; ++PI)
826 PType = (*PI)->getType();
John McCall09431682010-11-18 19:01:18 +0000827 VK = VK_LValue;
Steve Naroff61f72cb2009-03-09 21:12:44 +0000828 }
John McCall09431682010-11-18 19:01:18 +0000829
830 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
831
Douglas Gregor926df6c2011-06-11 01:09:30 +0000832 if (IsSuper)
833 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
834 PType, VK, OK,
835 propertyNameLoc,
836 receiverNameLoc,
837 Context.getObjCInterfaceType(IFace)));
838
John McCall12f78a62010-12-02 01:19:52 +0000839 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
840 PType, VK, OK,
841 propertyNameLoc,
842 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000843 }
844 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
845 << &propertyName << Context.getObjCInterfaceType(IFace));
846}
847
Douglas Gregor47bd5432010-04-14 02:46:37 +0000848Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000849 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000850 SourceLocation NameLoc,
851 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000852 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000853 ParsedType &ReceiverType) {
854 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000855
Douglas Gregor47bd5432010-04-14 02:46:37 +0000856 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000857 // messaging super. If the identifier is "super" and there is a
858 // trailing dot, it's an instance message.
859 if (IsSuper && S->isInObjcMethodScope())
860 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000861
862 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
863 LookupName(Result, S);
864
865 switch (Result.getResultKind()) {
866 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000867 // Normal name lookup didn't find anything. If we're in an
868 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000869 // FIXME: This is a hack. Ivar lookup should be part of normal
870 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000871 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
872 ObjCInterfaceDecl *ClassDeclared;
873 if (Method->getClassInterface()->lookupInstanceVariable(Name,
874 ClassDeclared))
875 return ObjCInstanceMessage;
876 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000877
Douglas Gregor47bd5432010-04-14 02:46:37 +0000878 // Break out; we'll perform typo correction below.
879 break;
880
881 case LookupResult::NotFoundInCurrentInstantiation:
882 case LookupResult::FoundOverloaded:
883 case LookupResult::FoundUnresolvedValue:
884 case LookupResult::Ambiguous:
885 Result.suppressDiagnostics();
886 return ObjCInstanceMessage;
887
888 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000889 // If the identifier is a class or not, and there is a trailing dot,
890 // it's an instance message.
891 if (HasTrailingDot)
892 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000893 // We found something. If it's a type, then we have a class
894 // message. Otherwise, it's an instance message.
895 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000896 QualType T;
897 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
898 T = Context.getObjCInterfaceType(Class);
899 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
900 T = Context.getTypeDeclType(Type);
901 else
902 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000903
Douglas Gregor1569f952010-04-21 20:38:13 +0000904 // We have a class message, and T is the type we're
905 // messaging. Build source-location information for it.
906 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000907 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000908 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000909 }
910 }
911
Douglas Gregoraaf87162010-04-14 20:04:41 +0000912 // Determine our typo-correction context.
913 CorrectTypoContext CTC = CTC_Expression;
914 if (ObjCMethodDecl *Method = getCurMethodDecl())
915 if (Method->getClassInterface() &&
916 Method->getClassInterface()->getSuperClass())
917 CTC = CTC_ObjCMessageReceiver;
918
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000919 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
920 Result.getLookupKind(), S, NULL,
921 NULL, false, CTC)) {
922 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000923 // If we found a declaration, correct when it refers to an Objective-C
924 // class.
Douglas Gregor1569f952010-04-21 20:38:13 +0000925 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000926 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000927 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000928 << FixItHint::CreateReplacement(SourceRange(NameLoc),
929 ND->getNameAsString());
930 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000931 << Corrected.getCorrection();
Douglas Gregor47bd5432010-04-14 02:46:37 +0000932
Douglas Gregor1569f952010-04-21 20:38:13 +0000933 QualType T = Context.getObjCInterfaceType(Class);
934 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000935 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000936 return ObjCClassMessage;
937 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000938 } else if (Corrected.isKeyword() &&
939 Corrected.getCorrectionAsIdentifierInfo()->isStr("super")) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000940 // If we've found the keyword "super", this is a send to super.
941 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000942 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000943 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000944 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000945 }
946 }
947
948 // Fall back: let the parser try to parse it as an instance message.
949 return ObjCInstanceMessage;
950}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000951
John McCall60d7b3a2010-08-24 06:29:42 +0000952ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000953 SourceLocation SuperLoc,
954 Selector Sel,
955 SourceLocation LBracLoc,
956 SourceLocation SelectorLoc,
957 SourceLocation RBracLoc,
958 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000959 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000960 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000961 if (!Method) {
962 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
963 return ExprError();
964 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000965
Douglas Gregorf95861a2010-04-21 20:01:04 +0000966 ObjCInterfaceDecl *Class = Method->getClassInterface();
967 if (!Class) {
968 Diag(SuperLoc, diag::error_no_super_class_message)
969 << Method->getDeclName();
970 return ExprError();
971 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000972
Douglas Gregorf95861a2010-04-21 20:01:04 +0000973 ObjCInterfaceDecl *Super = Class->getSuperClass();
974 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000975 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000976 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
977 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000978 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000979 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000980
Douglas Gregorf95861a2010-04-21 20:01:04 +0000981 // We are in a method whose class has a superclass, so 'super'
982 // is acting as a keyword.
983 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +0000984 if (Sel.getMethodFamily() == OMF_dealloc)
985 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +0000986 if (Sel.getMethodFamily() == OMF_finalize)
987 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +0000988
Douglas Gregorf95861a2010-04-21 20:01:04 +0000989 // Since we are in an instance method, this is an instance
990 // message to the superclass instance.
991 QualType SuperTy = Context.getObjCInterfaceType(Super);
992 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +0000993 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000994 Sel, /*Method=*/0,
995 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000996 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000997
998 // Since we are in a class method, this is a class message to
999 // the superclass.
1000 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1001 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001002 SuperLoc, Sel, /*Method=*/0,
1003 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001004}
1005
1006/// \brief Build an Objective-C class message expression.
1007///
1008/// This routine takes care of both normal class messages and
1009/// class messages to the superclass.
1010///
1011/// \param ReceiverTypeInfo Type source information that describes the
1012/// receiver of this message. This may be NULL, in which case we are
1013/// sending to the superclass and \p SuperLoc must be a valid source
1014/// location.
1015
1016/// \param ReceiverType The type of the object receiving the
1017/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1018/// type as that refers to. For a superclass send, this is the type of
1019/// the superclass.
1020///
1021/// \param SuperLoc The location of the "super" keyword in a
1022/// superclass message.
1023///
1024/// \param Sel The selector to which the message is being sent.
1025///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001026/// \param Method The method that this class message is invoking, if
1027/// already known.
1028///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001029/// \param LBracLoc The location of the opening square bracket ']'.
1030///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001031/// \param RBrac The location of the closing square bracket ']'.
1032///
1033/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001034ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001035 QualType ReceiverType,
1036 SourceLocation SuperLoc,
1037 Selector Sel,
1038 ObjCMethodDecl *Method,
1039 SourceLocation LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001040 SourceLocation SelectorLoc,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001041 SourceLocation RBracLoc,
1042 MultiExprArg ArgsIn) {
1043 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001044 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001045 if (LBracLoc.isInvalid()) {
1046 Diag(Loc, diag::err_missing_open_square_message_send)
1047 << FixItHint::CreateInsertion(Loc, "[");
1048 LBracLoc = Loc;
1049 }
1050
Douglas Gregor92e986e2010-04-22 16:44:27 +00001051 if (ReceiverType->isDependentType()) {
1052 // If the receiver type is dependent, we can't type-check anything
1053 // at this point. Build a dependent expression.
1054 unsigned NumArgs = ArgsIn.size();
1055 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1056 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001057 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1058 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001059 Sel, SelectorLoc, /*Method=*/0,
Douglas Gregor92e986e2010-04-22 16:44:27 +00001060 Args, NumArgs, RBracLoc));
1061 }
Chris Lattner15faee12010-04-12 05:38:43 +00001062
Douglas Gregor2725ca82010-04-21 19:57:20 +00001063 // Find the class to which we are sending this message.
1064 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001065 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1066 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001067 Diag(Loc, diag::err_invalid_receiver_class_message)
1068 << ReceiverType;
1069 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001070 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001071 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian02b0d652011-03-08 19:12:46 +00001072 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001073 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001074 if (!Method) {
1075 if (Class->isForwardDecl()) {
John McCallf85e1932011-06-15 23:02:42 +00001076 if (getLangOptions().ObjCAutoRefCount) {
1077 Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
1078 } else {
1079 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1080 }
1081
Douglas Gregorf49bb082010-04-22 17:01:48 +00001082 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001083 Method = LookupFactoryMethodInGlobalPool(Sel,
1084 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001085 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001086 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1087 << Method->getDeclName();
1088 }
1089 if (!Method)
1090 Method = Class->lookupClassMethod(Sel);
1091
1092 // If we have an implementation in scope, check "private" methods.
1093 if (!Method)
1094 Method = LookupPrivateClassMethod(Sel, Class);
1095
1096 if (Method && DiagnoseUseOfDecl(Method, Loc))
1097 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001098 }
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Douglas Gregor2725ca82010-04-21 19:57:20 +00001100 // Check the argument types and determine the result type.
1101 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001102 ExprValueKind VK = VK_RValue;
1103
Douglas Gregor2725ca82010-04-21 19:57:20 +00001104 unsigned NumArgs = ArgsIn.size();
1105 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001106 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1107 SuperLoc.isValid(), LBracLoc, RBracLoc,
1108 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001109 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001110
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001111 if (Method && !Method->getResultType()->isVoidType() &&
1112 RequireCompleteType(LBracLoc, Method->getResultType(),
1113 diag::err_illegal_message_expr_incomplete_type))
1114 return ExprError();
1115
Douglas Gregor2725ca82010-04-21 19:57:20 +00001116 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001117 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001118 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001119 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001120 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001121 ReceiverType, Sel, SelectorLoc,
1122 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001123 else
John McCallf89e55a2010-11-18 06:31:45 +00001124 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001125 ReceiverTypeInfo, Sel, SelectorLoc,
1126 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001127 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001128}
1129
Douglas Gregor2725ca82010-04-21 19:57:20 +00001130// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001131// ArgExprs is optional - if it is present, the number of expressions
1132// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001133ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001134 ParsedType Receiver,
1135 Selector Sel,
1136 SourceLocation LBracLoc,
1137 SourceLocation SelectorLoc,
1138 SourceLocation RBracLoc,
1139 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001140 TypeSourceInfo *ReceiverTypeInfo;
1141 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1142 if (ReceiverType.isNull())
1143 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001144
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Douglas Gregor2725ca82010-04-21 19:57:20 +00001146 if (!ReceiverTypeInfo)
1147 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1148
1149 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001150 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001151 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001152}
1153
1154/// \brief Build an Objective-C instance message expression.
1155///
1156/// This routine takes care of both normal instance messages and
1157/// instance messages to the superclass instance.
1158///
1159/// \param Receiver The expression that computes the object that will
1160/// receive this message. This may be empty, in which case we are
1161/// sending to the superclass instance and \p SuperLoc must be a valid
1162/// source location.
1163///
1164/// \param ReceiverType The (static) type of the object receiving the
1165/// message. When a \p Receiver expression is provided, this is the
1166/// same type as that expression. For a superclass instance send, this
1167/// is a pointer to the type of the superclass.
1168///
1169/// \param SuperLoc The location of the "super" keyword in a
1170/// superclass instance message.
1171///
1172/// \param Sel The selector to which the message is being sent.
1173///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001174/// \param Method The method that this instance message is invoking, if
1175/// already known.
1176///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001177/// \param LBracLoc The location of the opening square bracket ']'.
1178///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001179/// \param RBrac The location of the closing square bracket ']'.
1180///
1181/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001182ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001183 QualType ReceiverType,
1184 SourceLocation SuperLoc,
1185 Selector Sel,
1186 ObjCMethodDecl *Method,
1187 SourceLocation LBracLoc,
1188 SourceLocation SelectorLoc,
1189 SourceLocation RBracLoc,
1190 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001191 // The location of the receiver.
1192 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1193
1194 if (LBracLoc.isInvalid()) {
1195 Diag(Loc, diag::err_missing_open_square_message_send)
1196 << FixItHint::CreateInsertion(Loc, "[");
1197 LBracLoc = Loc;
1198 }
1199
Douglas Gregor2725ca82010-04-21 19:57:20 +00001200 // If we have a receiver expression, perform appropriate promotions
1201 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001202 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001203 if (Receiver->isTypeDependent()) {
1204 // If the receiver is type-dependent, we can't type-check anything
1205 // at this point. Build a dependent expression.
1206 unsigned NumArgs = ArgsIn.size();
1207 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1208 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1209 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001210 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001211 SelectorLoc, /*Method=*/0,
1212 Args, NumArgs, RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001213 }
1214
Douglas Gregor2725ca82010-04-21 19:57:20 +00001215 // If necessary, apply function/array conversion to the receiver.
1216 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001217 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1218 if (Result.isInvalid())
1219 return ExprError();
1220 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001221 ReceiverType = Receiver->getType();
1222 }
1223
Douglas Gregorf49bb082010-04-22 17:01:48 +00001224 if (!Method) {
1225 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001226 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001227 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001228 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1229 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001230 SourceRange(LBracLoc, RBracLoc),
1231 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001232 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001233 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001234 SourceRange(LBracLoc, RBracLoc),
1235 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001236 } else if (ReceiverType->isObjCClassType() ||
1237 ReceiverType->isObjCQualifiedClassType()) {
1238 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001239 // We allow sending a message to a qualified Class ("Class<foo>"), which
1240 // is ok as long as one of the protocols implements the selector (if not, warn).
1241 if (const ObjCObjectPointerType *QClassTy
1242 = ReceiverType->getAsObjCQualifiedClassType()) {
1243 // Search protocols for class methods.
1244 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1245 if (!Method) {
1246 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1247 // warn if instance method found for a Class message.
1248 if (Method) {
1249 Diag(Loc, diag::warn_instance_method_on_class_found)
1250 << Method->getSelector() << Sel;
1251 Diag(Method->getLocation(), diag::note_method_declared_at);
1252 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001253 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001254 } else {
1255 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1256 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1257 // First check the public methods in the class interface.
1258 Method = ClassDecl->lookupClassMethod(Sel);
1259
1260 if (!Method)
1261 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1262 }
1263 if (Method && DiagnoseUseOfDecl(Method, Loc))
1264 return ExprError();
1265 }
1266 if (!Method) {
1267 // If not messaging 'self', look for any factory method named 'Sel'.
1268 if (!Receiver || !isSelfExpr(Receiver)) {
1269 Method = LookupFactoryMethodInGlobalPool(Sel,
1270 SourceRange(LBracLoc, RBracLoc),
1271 true);
1272 if (!Method) {
1273 // If no class (factory) method was found, check if an _instance_
1274 // method of the same name exists in the root class only.
1275 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001276 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001277 true);
1278 if (Method)
1279 if (const ObjCInterfaceDecl *ID =
1280 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1281 if (ID->getSuperClass())
1282 Diag(Loc, diag::warn_root_inst_method_not_found)
1283 << Sel << SourceRange(LBracLoc, RBracLoc);
1284 }
1285 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001286 }
1287 }
1288 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001289 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001290 ObjCInterfaceDecl* ClassDecl = 0;
1291
1292 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1293 // long as one of the protocols implements the selector (if not, warn).
1294 if (const ObjCObjectPointerType *QIdTy
1295 = ReceiverType->getAsObjCQualifiedIdType()) {
1296 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001297 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1298 if (!Method)
1299 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001300 } else if (const ObjCObjectPointerType *OCIType
1301 = ReceiverType->getAsObjCInterfacePointerType()) {
1302 // We allow sending a message to a pointer to an interface (an object).
1303 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001304
1305 if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCount) {
1306 Diag(Loc, diag::err_arc_receiver_forward_instance)
1307 << OCIType->getPointeeType()
1308 << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperLoc));
1309 return ExprError();
1310 }
1311
Douglas Gregorf49bb082010-04-22 17:01:48 +00001312 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1313 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +00001314 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001315 Method = ClassDecl->lookupInstanceMethod(Sel);
1316
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001317 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001318 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001319 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1320
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001321 const ObjCInterfaceDecl *forwardClass = 0;
Douglas Gregorf49bb082010-04-22 17:01:48 +00001322 if (!Method) {
1323 // If we have implementations in scope, check "private" methods.
1324 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1325
John McCallf85e1932011-06-15 23:02:42 +00001326 if (!Method && getLangOptions().ObjCAutoRefCount) {
1327 Diag(Loc, diag::err_arc_may_not_respond)
1328 << OCIType->getPointeeType() << Sel;
1329 return ExprError();
1330 }
1331
Douglas Gregorf49bb082010-04-22 17:01:48 +00001332 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1333 // If we still haven't found a method, look in the global pool. This
1334 // behavior isn't very desirable, however we need it for GCC
1335 // compatibility. FIXME: should we deviate??
1336 if (OCIType->qual_empty()) {
1337 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001338 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001339 if (OCIType->getInterfaceDecl()->isForwardDecl())
1340 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001341 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001342 Diag(Loc, diag::warn_maynot_respond)
1343 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1344 }
1345 }
1346 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001347 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001348 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001349 } else if (!getLangOptions().ObjCAutoRefCount &&
1350 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001351 (ReceiverType->isPointerType() ||
1352 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001353 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001354 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001355 Diag(Loc, diag::warn_bad_receiver_type)
1356 << ReceiverType
1357 << Receiver->getSourceRange();
1358 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001359 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00001360 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00001361 else {
1362 // TODO: specialized warning on null receivers?
1363 bool IsNull = Receiver->isNullPointerConstant(Context,
1364 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001365 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1366 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001367 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001368 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00001369 } else {
John Wiegley429bb272011-04-08 18:41:53 +00001370 ExprResult ReceiverRes;
1371 if (getLangOptions().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00001372 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00001373 if (ReceiverRes.isUsable()) {
1374 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00001375 return BuildInstanceMessage(Receiver,
1376 ReceiverType,
1377 SuperLoc,
1378 Sel,
1379 Method,
1380 LBracLoc,
1381 SelectorLoc,
1382 RBracLoc,
1383 move(ArgsIn));
1384 } else {
1385 // Reject other random receiver types (e.g. structs).
1386 Diag(Loc, diag::err_bad_receiver_type)
1387 << ReceiverType << Receiver->getSourceRange();
1388 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001389 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001390 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001391 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001392 }
Mike Stump1eb44332009-09-09 15:08:12 +00001393
Douglas Gregor2725ca82010-04-21 19:57:20 +00001394 // Check the message arguments.
1395 unsigned NumArgs = ArgsIn.size();
1396 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1397 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001398 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001399 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1400 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001401 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1402 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001403 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001404 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001405
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001406 if (Method && !Method->getResultType()->isVoidType() &&
1407 RequireCompleteType(LBracLoc, Method->getResultType(),
1408 diag::err_illegal_message_expr_incomplete_type))
1409 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001410
John McCallf85e1932011-06-15 23:02:42 +00001411 // In ARC, forbid the user from sending messages to
1412 // retain/release/autorelease/dealloc/retainCount explicitly.
1413 if (getLangOptions().ObjCAutoRefCount) {
1414 ObjCMethodFamily family =
1415 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1416 switch (family) {
1417 case OMF_init:
1418 if (Method)
1419 checkInitMethod(Method, ReceiverType);
1420
1421 case OMF_None:
1422 case OMF_alloc:
1423 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00001424 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00001425 case OMF_mutableCopy:
1426 case OMF_new:
1427 case OMF_self:
1428 break;
1429
1430 case OMF_dealloc:
1431 case OMF_retain:
1432 case OMF_release:
1433 case OMF_autorelease:
1434 case OMF_retainCount:
1435 Diag(Loc, diag::err_arc_illegal_explicit_message)
1436 << Sel << SelectorLoc;
1437 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001438
1439 case OMF_performSelector:
1440 if (Method && NumArgs >= 1) {
1441 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1442 Selector ArgSel = SelExp->getSelector();
1443 ObjCMethodDecl *SelMethod =
1444 LookupInstanceMethodInGlobalPool(ArgSel,
1445 SelExp->getSourceRange());
1446 if (!SelMethod)
1447 SelMethod =
1448 LookupFactoryMethodInGlobalPool(ArgSel,
1449 SelExp->getSourceRange());
1450 if (SelMethod) {
1451 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1452 switch (SelFamily) {
1453 case OMF_alloc:
1454 case OMF_copy:
1455 case OMF_mutableCopy:
1456 case OMF_new:
1457 case OMF_self:
1458 case OMF_init:
1459 // Issue error, unless ns_returns_not_retained.
1460 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1461 // selector names a +1 method
1462 Diag(SelectorLoc,
1463 diag::err_arc_perform_selector_retains);
1464 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1465 }
1466 break;
1467 default:
1468 // +0 call. OK. unless ns_returns_retained.
1469 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1470 // selector names a +1 method
1471 Diag(SelectorLoc,
1472 diag::err_arc_perform_selector_retains);
1473 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1474 }
1475 break;
1476 }
1477 }
1478 } else {
1479 // error (may leak).
1480 Diag(SelectorLoc, diag::warn_arc_perform_selector_leaks);
1481 Diag(Args[0]->getExprLoc(), diag::note_used_here);
1482 }
1483 }
1484 break;
John McCallf85e1932011-06-15 23:02:42 +00001485 }
1486 }
1487
Douglas Gregor2725ca82010-04-21 19:57:20 +00001488 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001489 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001490 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001491 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001492 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001493 ReceiverType, Sel, SelectorLoc, Method,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001494 Args, NumArgs, RBracLoc);
1495 else
John McCallf89e55a2010-11-18 06:31:45 +00001496 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001497 Receiver, Sel, SelectorLoc, Method,
1498 Args, NumArgs, RBracLoc);
John McCallf85e1932011-06-15 23:02:42 +00001499
1500 if (getLangOptions().ObjCAutoRefCount) {
1501 // In ARC, annotate delegate init calls.
1502 if (Result->getMethodFamily() == OMF_init &&
1503 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
1504 // Only consider init calls *directly* in init implementations,
1505 // not within blocks.
1506 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1507 if (method && method->getMethodFamily() == OMF_init) {
1508 // The implicit assignment to self means we also don't want to
1509 // consume the result.
1510 Result->setDelegateInitCall(true);
1511 return Owned(Result);
1512 }
1513 }
1514
1515 // In ARC, check for message sends which are likely to introduce
1516 // retain cycles.
1517 checkRetainCycles(Result);
1518 }
1519
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001520 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001521}
1522
1523// ActOnInstanceMessage - used for both unary and keyword messages.
1524// ArgExprs is optional - if it is present, the number of expressions
1525// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001526ExprResult Sema::ActOnInstanceMessage(Scope *S,
1527 Expr *Receiver,
1528 Selector Sel,
1529 SourceLocation LBracLoc,
1530 SourceLocation SelectorLoc,
1531 SourceLocation RBracLoc,
1532 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001533 if (!Receiver)
1534 return ExprError();
1535
John McCall9ae2f072010-08-23 23:25:46 +00001536 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001537 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001538 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001539}
Chris Lattnereca7be62008-04-07 05:30:13 +00001540
John McCallf85e1932011-06-15 23:02:42 +00001541enum ARCConversionTypeClass {
1542 ACTC_none,
1543 ACTC_retainable,
1544 ACTC_indirectRetainable
1545};
1546static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
1547 ARCConversionTypeClass ACTC = ACTC_retainable;
1548
1549 // Ignore an outermost reference type.
1550 if (const ReferenceType *ref = type->getAs<ReferenceType>())
1551 type = ref->getPointeeType();
1552
1553 // Drill through pointers and arrays recursively.
1554 while (true) {
1555 if (const PointerType *ptr = type->getAs<PointerType>()) {
1556 type = ptr->getPointeeType();
1557 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1558 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1559 } else {
1560 break;
1561 }
1562 ACTC = ACTC_indirectRetainable;
1563 }
1564
1565 if (!type->isObjCRetainableType()) return ACTC_none;
1566 return ACTC;
1567}
1568
1569namespace {
1570 /// Return true if the given expression can be reasonably converted
1571 /// between a retainable pointer type and a C pointer type.
1572 struct ARCCastChecker : StmtVisitor<ARCCastChecker, bool> {
1573 ASTContext &Context;
1574 ARCCastChecker(ASTContext &Context) : Context(Context) {}
1575 bool VisitStmt(Stmt *s) {
1576 return false;
1577 }
1578 bool VisitExpr(Expr *e) {
1579 return e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
1580 }
1581
1582 bool VisitParenExpr(ParenExpr *e) {
1583 return Visit(e->getSubExpr());
1584 }
1585 bool VisitCastExpr(CastExpr *e) {
1586 switch (e->getCastKind()) {
1587 case CK_NullToPointer:
1588 return true;
1589 case CK_NoOp:
1590 case CK_LValueToRValue:
1591 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00001592 case CK_CPointerToObjCPointerCast:
1593 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00001594 case CK_AnyPointerToBlockPointerCast:
1595 return Visit(e->getSubExpr());
1596 default:
1597 return false;
1598 }
1599 }
1600 bool VisitUnaryExtension(UnaryOperator *e) {
1601 return Visit(e->getSubExpr());
1602 }
1603 bool VisitBinComma(BinaryOperator *e) {
1604 return Visit(e->getRHS());
1605 }
1606 bool VisitConditionalOperator(ConditionalOperator *e) {
1607 // Conditional operators are okay if both sides are okay.
1608 return Visit(e->getTrueExpr()) && Visit(e->getFalseExpr());
1609 }
1610 bool VisitObjCStringLiteral(ObjCStringLiteral *e) {
1611 // Always white-list Objective-C string literals.
1612 return true;
1613 }
1614 bool VisitStmtExpr(StmtExpr *e) {
1615 return Visit(e->getSubStmt()->body_back());
1616 }
1617 bool VisitDeclRefExpr(DeclRefExpr *e) {
1618 // White-list references to global extern strings from system
1619 // headers.
1620 if (VarDecl *var = dyn_cast<VarDecl>(e->getDecl()))
1621 if (var->getStorageClass() == SC_Extern &&
1622 var->getType().isConstQualified() &&
1623 Context.getSourceManager().isInSystemHeader(var->getLocation()))
1624 return true;
1625 return false;
1626 }
1627 };
1628}
1629
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001630bool
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001631Sema::ValidObjCARCNoBridgeCastExpr(Expr *&Exp, QualType castType) {
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001632 Expr *NewExp = Exp->IgnoreParenCasts();
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001633
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001634 if (!isa<ObjCMessageExpr>(NewExp) && !isa<ObjCPropertyRefExpr>(NewExp)
1635 && !isa<CallExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001636 return false;
1637 ObjCMethodDecl *method = 0;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001638 bool MethodReturnsPlusOne = false;
1639
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001640 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(NewExp)) {
1641 method = PRE->getExplicitProperty()->getGetterMethodDecl();
1642 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001643 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001644 method = ME->getMethodDecl();
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001645 else {
1646 CallExpr *CE = cast<CallExpr>(NewExp);
1647 Decl *CallDecl = CE->getCalleeDecl();
1648 if (!CallDecl)
1649 return false;
1650 if (CallDecl->hasAttr<CFReturnsNotRetainedAttr>())
1651 return true;
1652 MethodReturnsPlusOne = CallDecl->hasAttr<CFReturnsRetainedAttr>();
1653 if (!MethodReturnsPlusOne) {
1654 if (NamedDecl *ND = dyn_cast<NamedDecl>(CallDecl))
1655 if (const IdentifierInfo *Id = ND->getIdentifier())
1656 if (Id->isStr("__builtin___CFStringMakeConstantString"))
1657 return true;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001658 }
1659 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001660
1661 if (!MethodReturnsPlusOne) {
1662 if (!method)
1663 return false;
1664 if (method->hasAttr<CFReturnsNotRetainedAttr>())
1665 return true;
1666 MethodReturnsPlusOne = method->hasAttr<CFReturnsRetainedAttr>();
1667 if (!MethodReturnsPlusOne) {
1668 ObjCMethodFamily family = method->getSelector().getMethodFamily();
1669 switch (family) {
1670 case OMF_alloc:
1671 case OMF_copy:
1672 case OMF_mutableCopy:
1673 case OMF_new:
1674 MethodReturnsPlusOne = true;
1675 break;
1676 default:
1677 break;
1678 }
1679 }
1680 }
1681
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001682 if (MethodReturnsPlusOne) {
1683 TypeSourceInfo *TSInfo =
1684 Context.getTrivialTypeSourceInfo(castType, SourceLocation());
1685 ExprResult ExpRes = BuildObjCBridgedCast(SourceLocation(), OBC_BridgeTransfer,
1686 SourceLocation(), TSInfo, Exp);
1687 Exp = ExpRes.take();
1688 }
1689 return true;
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001690}
1691
John McCallf85e1932011-06-15 23:02:42 +00001692void
1693Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001694 Expr *&castExpr, CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00001695 QualType castExprType = castExpr->getType();
1696
1697 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1698 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
1699 if (exprACTC == castACTC) return;
Fariborz Jahanian8295b7b2011-06-22 16:36:45 +00001700 if (exprACTC && castType->isIntegralType(Context)) return;
John McCallf85e1932011-06-15 23:02:42 +00001701
1702 // Allow casts between pointers to lifetime types (e.g., __strong id*)
1703 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1704 // must be explicit.
1705 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
1706 if (const PointerType *CastExprPtr = castExprType->getAs<PointerType>()) {
1707 QualType CastPointee = CastPtr->getPointeeType();
1708 QualType CastExprPointee = CastExprPtr->getPointeeType();
1709 if ((CCK != CCK_ImplicitConversion &&
1710 CastPointee->isObjCIndirectLifetimeType() &&
1711 CastExprPointee->isVoidType()) ||
1712 (CastPointee->isVoidType() &&
1713 CastExprPointee->isObjCIndirectLifetimeType()))
1714 return;
1715 }
1716 }
1717
1718 if (ARCCastChecker(Context).Visit(castExpr))
1719 return;
1720
1721 SourceLocation loc =
1722 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
1723
1724 if (makeUnavailableInSystemHeader(loc,
1725 "converts between Objective-C and C pointers in -fobjc-arc"))
1726 return;
1727
John McCall71c482c2011-06-17 06:50:50 +00001728 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00001729 switch (exprACTC) {
1730 case ACTC_none:
1731 srcKind = (castExprType->isPointerType() ? 1 : 0);
1732 break;
1733 case ACTC_retainable:
1734 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1735 break;
1736 case ACTC_indirectRetainable:
1737 srcKind = 4;
1738 break;
1739 }
1740
1741 if (CCK == CCK_CStyleCast) {
1742 // Check whether this could be fixed with a bridge cast.
1743 SourceLocation AfterLParen = PP.getLocForEndOfToken(castRange.getBegin());
1744 SourceLocation NoteLoc = AfterLParen.isValid()? AfterLParen : loc;
1745
1746 if (castType->isObjCARCBridgableType() &&
1747 castExprType->isCARCBridgableType()) {
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001748 // explicit unbridged casts are allowed if the source of the cast is a
1749 // message sent to an objc method (or property access)
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001750 if (ValidObjCARCNoBridgeCastExpr(castExpr, castType))
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001751 return;
John McCallf85e1932011-06-15 23:02:42 +00001752 Diag(loc, diag::err_arc_cast_requires_bridge)
1753 << 2
1754 << castExprType
1755 << (castType->isBlockPointerType()? 1 : 0)
1756 << castType
1757 << castRange
1758 << castExpr->getSourceRange();
1759 Diag(NoteLoc, diag::note_arc_bridge)
1760 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1761 Diag(NoteLoc, diag::note_arc_bridge_transfer)
1762 << castExprType
1763 << FixItHint::CreateInsertion(AfterLParen, "__bridge_transfer ");
1764
1765 return;
1766 }
1767
1768 if (castType->isCARCBridgableType() &&
1769 castExprType->isObjCARCBridgableType()){
1770 Diag(loc, diag::err_arc_cast_requires_bridge)
1771 << (castExprType->isBlockPointerType()? 1 : 0)
1772 << castExprType
1773 << 2
1774 << castType
1775 << castRange
1776 << castExpr->getSourceRange();
1777
1778 Diag(NoteLoc, diag::note_arc_bridge)
1779 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1780 Diag(NoteLoc, diag::note_arc_bridge_retained)
1781 << castType
1782 << FixItHint::CreateInsertion(AfterLParen, "__bridge_retained ");
1783 return;
1784 }
1785 }
1786
1787 Diag(loc, diag::err_arc_mismatched_cast)
1788 << (CCK != CCK_ImplicitConversion) << srcKind << castExprType << castType
1789 << castRange << castExpr->getSourceRange();
1790}
1791
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00001792bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
1793 QualType exprType) {
1794 QualType canCastType =
1795 Context.getCanonicalType(castType).getUnqualifiedType();
1796 QualType canExprType =
1797 Context.getCanonicalType(exprType).getUnqualifiedType();
1798 if (isa<ObjCObjectPointerType>(canCastType) &&
1799 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
1800 canExprType->isObjCObjectPointerType()) {
1801 if (const ObjCObjectPointerType *ObjT =
1802 canExprType->getAs<ObjCObjectPointerType>())
1803 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
1804 return false;
1805 }
1806 return true;
1807}
1808
John McCall7e5e5f42011-07-07 06:58:02 +00001809/// Look for an ObjCReclaimReturnedObject cast and destroy it.
1810static Expr *maybeUndoReclaimObject(Expr *e) {
1811 // For now, we just undo operands that are *immediately* reclaim
1812 // expressions, which prevents the vast majority of potential
1813 // problems here. To catch them all, we'd need to rebuild arbitrary
1814 // value-propagating subexpressions --- we can't reliably rebuild
1815 // in-place because of expression sharing.
1816 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
1817 if (ice->getCastKind() == CK_ObjCReclaimReturnedObject)
1818 return ice->getSubExpr();
1819
1820 return e;
1821}
1822
John McCallf85e1932011-06-15 23:02:42 +00001823ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
1824 ObjCBridgeCastKind Kind,
1825 SourceLocation BridgeKeywordLoc,
1826 TypeSourceInfo *TSInfo,
1827 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00001828 ExprResult SubResult = UsualUnaryConversions(SubExpr);
1829 if (SubResult.isInvalid()) return ExprError();
1830 SubExpr = SubResult.take();
1831
John McCallf85e1932011-06-15 23:02:42 +00001832 QualType T = TSInfo->getType();
1833 QualType FromType = SubExpr->getType();
1834
John McCall1d9b3b22011-09-09 05:25:32 +00001835 CastKind CK;
1836
John McCallf85e1932011-06-15 23:02:42 +00001837 bool MustConsume = false;
1838 if (T->isDependentType() || SubExpr->isTypeDependent()) {
1839 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00001840 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00001841 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
1842 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00001843 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
1844 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00001845 switch (Kind) {
1846 case OBC_Bridge:
1847 break;
1848
1849 case OBC_BridgeRetained:
1850 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1851 << 2
1852 << FromType
1853 << (T->isBlockPointerType()? 1 : 0)
1854 << T
1855 << SubExpr->getSourceRange()
1856 << Kind;
1857 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1858 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
1859 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
1860 << FromType
1861 << FixItHint::CreateReplacement(BridgeKeywordLoc,
1862 "__bridge_transfer ");
1863
1864 Kind = OBC_Bridge;
1865 break;
1866
1867 case OBC_BridgeTransfer:
1868 // We must consume the Objective-C object produced by the cast.
1869 MustConsume = true;
1870 break;
1871 }
1872 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
1873 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00001874 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00001875 switch (Kind) {
1876 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00001877 // Reclaiming a value that's going to be __bridge-casted to CF
1878 // is very dangerous, so we don't do it.
1879 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00001880 break;
1881
1882 case OBC_BridgeRetained:
1883 // Produce the object before casting it.
1884 SubExpr = ImplicitCastExpr::Create(Context, FromType,
1885 CK_ObjCProduceObject,
1886 SubExpr, 0, VK_RValue);
1887 break;
1888
1889 case OBC_BridgeTransfer:
1890 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1891 << (FromType->isBlockPointerType()? 1 : 0)
1892 << FromType
1893 << 2
1894 << T
1895 << SubExpr->getSourceRange()
1896 << Kind;
1897
1898 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1899 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
1900 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
1901 << T
1902 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
1903
1904 Kind = OBC_Bridge;
1905 break;
1906 }
1907 } else {
1908 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
1909 << FromType << T << Kind
1910 << SubExpr->getSourceRange()
1911 << TSInfo->getTypeLoc().getSourceRange();
1912 return ExprError();
1913 }
1914
John McCall1d9b3b22011-09-09 05:25:32 +00001915 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00001916 BridgeKeywordLoc,
1917 TSInfo, SubExpr);
1918
1919 if (MustConsume) {
1920 ExprNeedsCleanups = true;
1921 Result = ImplicitCastExpr::Create(Context, T, CK_ObjCConsumeObject, Result,
1922 0, VK_RValue);
1923 }
1924
1925 return Result;
1926}
1927
1928ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
1929 SourceLocation LParenLoc,
1930 ObjCBridgeCastKind Kind,
1931 SourceLocation BridgeKeywordLoc,
1932 ParsedType Type,
1933 SourceLocation RParenLoc,
1934 Expr *SubExpr) {
1935 TypeSourceInfo *TSInfo = 0;
1936 QualType T = GetTypeFromParser(Type, &TSInfo);
1937 if (!TSInfo)
1938 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
1939 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
1940 SubExpr);
1941}