blob: 51b5e4fb63b03dba602c257e0fa6d49a0aa0f36a [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 Gregor5c16d632011-09-09 20:05:21 +0000274static QualType stripObjCInstanceType(ASTContext &Context, QualType T) {
275 if (T == Context.getObjCInstanceType())
276 return Context.getObjCIdType();
277
278 return T;
279}
280
Douglas Gregor926df6c2011-06-11 01:09:30 +0000281QualType Sema::getMessageSendResultType(QualType ReceiverType,
282 ObjCMethodDecl *Method,
283 bool isClassMessage, bool isSuperMessage) {
284 assert(Method && "Must have a method");
285 if (!Method->hasRelatedResultType())
286 return Method->getSendResultType();
287
288 // If a method has a related return type:
289 // - if the method found is an instance method, but the message send
290 // was a class message send, T is the declared return type of the method
291 // found
292 if (Method->isInstanceMethod() && isClassMessage)
Douglas Gregor5c16d632011-09-09 20:05:21 +0000293 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000294
295 // - if the receiver is super, T is a pointer to the class of the
296 // enclosing method definition
297 if (isSuperMessage) {
298 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
299 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
300 return Context.getObjCObjectPointerType(
301 Context.getObjCInterfaceType(Class));
302 }
303
304 // - if the receiver is the name of a class U, T is a pointer to U
305 if (ReceiverType->getAs<ObjCInterfaceType>() ||
306 ReceiverType->isObjCQualifiedInterfaceType())
307 return Context.getObjCObjectPointerType(ReceiverType);
308 // - if the receiver is of type Class or qualified Class type,
309 // T is the declared return type of the method.
310 if (ReceiverType->isObjCClassType() ||
311 ReceiverType->isObjCQualifiedClassType())
Douglas Gregor5c16d632011-09-09 20:05:21 +0000312 return stripObjCInstanceType(Context, Method->getSendResultType());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000313
314 // - if the receiver is id, qualified id, Class, or qualified Class, T
315 // is the receiver type, otherwise
316 // - T is the type of the receiver expression.
317 return ReceiverType;
318}
John McCall26743b22011-02-03 09:00:02 +0000319
Douglas Gregor926df6c2011-06-11 01:09:30 +0000320void Sema::EmitRelatedResultTypeNote(const Expr *E) {
321 E = E->IgnoreParenImpCasts();
322 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
323 if (!MsgSend)
324 return;
325
326 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
327 if (!Method)
328 return;
329
330 if (!Method->hasRelatedResultType())
331 return;
332
333 if (Context.hasSameUnqualifiedType(Method->getResultType()
334 .getNonReferenceType(),
335 MsgSend->getType()))
336 return;
337
Douglas Gregore97179c2011-09-08 01:46:34 +0000338 if (!Context.hasSameUnqualifiedType(Method->getResultType(),
339 Context.getObjCInstanceType()))
340 return;
341
Douglas Gregor926df6c2011-06-11 01:09:30 +0000342 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
343 << Method->isInstanceMethod() << Method->getSelector()
344 << MsgSend->getType();
345}
346
347bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
348 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000349 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000350 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000351 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000352 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000353 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000354 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000355 for (unsigned i = 0; i != NumArgs; i++) {
356 if (Args[i]->isTypeDependent())
357 continue;
358
John Wiegley429bb272011-04-08 18:41:53 +0000359 ExprResult Result = DefaultArgumentPromotion(Args[i]);
360 if (Result.isInvalid())
361 return true;
362 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000363 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000364
John McCallf85e1932011-06-15 23:02:42 +0000365 unsigned DiagID;
366 if (getLangOptions().ObjCAutoRefCount)
367 DiagID = diag::err_arc_method_not_found;
368 else
369 DiagID = isClassMessage ? diag::warn_class_method_not_found
370 : diag::warn_inst_method_not_found;
John McCall819e7452011-08-31 20:57:36 +0000371 if (!getLangOptions().DebuggerSupport)
372 Diag(lbrac, DiagID)
373 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +0000374
375 // In debuggers, we want to use __unknown_anytype for these
376 // results so that clients can cast them.
377 if (getLangOptions().DebuggerSupport) {
378 ReturnType = Context.UnknownAnyTy;
379 } else {
380 ReturnType = Context.getObjCIdType();
381 }
John McCallf89e55a2010-11-18 06:31:45 +0000382 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000383 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000384 }
Mike Stump1eb44332009-09-09 15:08:12 +0000385
Douglas Gregor926df6c2011-06-11 01:09:30 +0000386 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
387 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000388 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000390 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000391 // Method might have more arguments than selector indicates. This is due
392 // to addition of c-style arguments in method.
393 if (Method->param_size() > Sel.getNumArgs())
394 NumNamedArgs = Method->param_size();
395 // FIXME. This need be cleaned up.
396 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000397 Diag(lbrac, diag::err_typecheck_call_too_few_args)
398 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000399 return false;
400 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000401
Chris Lattner312531a2009-04-12 08:11:20 +0000402 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000403 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000404 // We can't do any type-checking on a type-dependent argument.
405 if (Args[i]->isTypeDependent())
406 continue;
407
Chris Lattner85a932e2008-01-04 22:32:30 +0000408 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000409
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000410 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000411 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000413 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
414 Param->getType(),
415 PDiag(diag::err_call_incomplete_argument)
416 << argExpr->getSourceRange()))
417 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000418
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000419 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
420 Param);
John McCall3fa5cae2010-10-26 07:05:15 +0000421 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000422 if (ArgE.isInvalid())
423 IsError = true;
424 else
425 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000426 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000427
428 // Promote additional arguments to variadic methods.
429 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000430 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
431 if (Args[i]->isTypeDependent())
432 continue;
433
John Wiegley429bb272011-04-08 18:41:53 +0000434 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
435 IsError |= Arg.isInvalid();
436 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000437 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000438 } else {
439 // Check for extra arguments to non-variadic methods.
440 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000441 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000442 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000443 << 2 /*method*/ << NumNamedArgs << NumArgs
444 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000445 << SourceRange(Args[NumNamedArgs]->getLocStart(),
446 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000447 }
448 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000449 // diagnose nonnull arguments.
450 for (specific_attr_iterator<NonNullAttr>
451 i = Method->specific_attr_begin<NonNullAttr>(),
452 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
453 CheckNonNullArguments(*i, Args, lbrac);
454 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000455
Douglas Gregor2725ca82010-04-21 19:57:20 +0000456 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000457 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000458}
459
Douglas Gregorc737acb2011-09-27 16:10:05 +0000460bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000461 // 'self' is objc 'self' in an objc method only.
Fariborz Jahanianb4602102011-03-28 16:23:34 +0000462 DeclContext *DC = CurContext;
463 while (isa<BlockDecl>(DC))
464 DC = DC->getParent();
465 if (DC && !isa<ObjCMethodDecl>(DC))
Douglas Gregorc737acb2011-09-27 16:10:05 +0000466 return false;
John McCallf85e1932011-06-15 23:02:42 +0000467 receiver = receiver->IgnoreParenLValueCasts();
468 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000469 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
Douglas Gregorc737acb2011-09-27 16:10:05 +0000470 return true;
471 return false;
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000472}
473
Steve Narofff1afaf62009-02-26 15:55:06 +0000474// Helper method for ActOnClassMethod/ActOnInstanceMethod.
475// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000476// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000477// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000478ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000479 ObjCInterfaceDecl *ClassDecl) {
480 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000481 // lookup in class and all superclasses
482 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000483 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000484 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000485
Steve Naroff5609ec02009-03-08 18:56:13 +0000486 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000487 if (!Method)
488 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Steve Naroff5609ec02009-03-08 18:56:13 +0000490 // Before we give up, check if the selector is an instance method.
491 // But only in the root. This matches gcc's behaviour and what the
492 // runtime expects.
493 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000494 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000495 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000496 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000497 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000498 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Steve Naroff5609ec02009-03-08 18:56:13 +0000501 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000502 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000503 return Method;
504}
505
506ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
507 ObjCInterfaceDecl *ClassDecl) {
508 ObjCMethodDecl *Method = 0;
509 while (ClassDecl && !Method) {
510 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000511 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000512 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Steve Naroff5609ec02009-03-08 18:56:13 +0000514 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000515 if (!Method)
516 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000517 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000518 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000519 return Method;
520}
521
Fariborz Jahanian61478062011-03-09 20:18:06 +0000522/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
523/// list of a qualified objective pointer type.
524ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
525 const ObjCObjectPointerType *OPT,
526 bool Instance)
527{
528 ObjCMethodDecl *MD = 0;
529 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
530 E = OPT->qual_end(); I != E; ++I) {
531 ObjCProtocolDecl *PROTO = (*I);
532 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
533 return MD;
534 }
535 }
536 return 0;
537}
538
Chris Lattner7f816522010-04-11 07:45:24 +0000539/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
540/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000541ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000542HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000543 Expr *BaseExpr, SourceLocation OpLoc,
544 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000545 SourceLocation MemberLoc,
546 SourceLocation SuperLoc, QualType SuperType,
547 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000548 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
549 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000550
551 if (MemberName.getNameKind() != DeclarationName::Identifier) {
552 Diag(MemberLoc, diag::err_invalid_property_name)
553 << MemberName << QualType(OPT, 0);
554 return ExprError();
555 }
556
Chris Lattner7f816522010-04-11 07:45:24 +0000557 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
558
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000559 if (IFace->isForwardDecl()) {
560 Diag(MemberLoc, diag::err_property_not_found_forward_class)
561 << MemberName << QualType(OPT, 0);
562 Diag(IFace->getLocation(), diag::note_forward_class);
563 return ExprError();
564 }
Chris Lattner7f816522010-04-11 07:45:24 +0000565 // Search for a declared property first.
566 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
567 // Check whether we can reference this property.
568 if (DiagnoseUseOfDecl(PD, MemberLoc))
569 return ExprError();
570 QualType ResTy = PD->getType();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000571 ResTy = ResTy.getNonLValueExprType(Context);
Chris Lattner7f816522010-04-11 07:45:24 +0000572 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
573 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000574 if (Getter &&
575 (Getter->hasRelatedResultType()
576 || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
577 ResTy = getMessageSendResultType(QualType(OPT, 0), Getter, false,
578 Super);
579
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000580 if (Super)
581 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000582 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000583 MemberLoc,
584 SuperLoc, SuperType));
585 else
586 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000587 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000588 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000589 }
590 // Check protocols on qualified interfaces.
591 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
592 E = OPT->qual_end(); I != E; ++I)
593 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
594 // Check whether we can reference this property.
595 if (DiagnoseUseOfDecl(PD, MemberLoc))
596 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000597
598 QualType T = PD->getType();
599 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
600 T = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000601 if (Super)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000602 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000603 VK_LValue,
604 OK_ObjCProperty,
605 MemberLoc,
606 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000607 else
Douglas Gregor926df6c2011-06-11 01:09:30 +0000608 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000609 VK_LValue,
610 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000611 MemberLoc,
612 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000613 }
614 // If that failed, look for an "implicit" property by seeing if the nullary
615 // selector is implemented.
616
617 // FIXME: The logic for looking up nullary and unary selectors should be
618 // shared with the code in ActOnInstanceMessage.
619
620 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
621 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000622
623 // May be founf in property's qualified list.
624 if (!Getter)
625 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000626
627 // If this reference is in an @implementation, check for 'private' methods.
628 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000629 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000630
631 // Look through local category implementations associated with the class.
632 if (!Getter)
633 Getter = IFace->getCategoryInstanceMethod(Sel);
634 if (Getter) {
635 // Check if we can reference this property.
636 if (DiagnoseUseOfDecl(Getter, MemberLoc))
637 return ExprError();
638 }
639 // If we found a getter then this may be a valid dot-reference, we
640 // will look for the matching setter, in case it is needed.
641 Selector SetterSel =
642 SelectorTable::constructSetterName(PP.getIdentifierTable(),
643 PP.getSelectorTable(), Member);
644 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000645
646 // May be founf in property's qualified list.
647 if (!Setter)
648 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
649
Chris Lattner7f816522010-04-11 07:45:24 +0000650 if (!Setter) {
651 // If this reference is in an @implementation, also check for 'private'
652 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000653 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000654 }
655 // Look through local category implementations associated with the class.
656 if (!Setter)
657 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000658
Chris Lattner7f816522010-04-11 07:45:24 +0000659 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
660 return ExprError();
661
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000662 if (Getter || Setter) {
663 QualType PType;
664 if (Getter)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000665 PType = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000666 else {
667 ParmVarDecl *ArgDecl = *Setter->param_begin();
668 PType = ArgDecl->getType();
669 }
670
John McCall09431682010-11-18 19:01:18 +0000671 ExprValueKind VK = VK_LValue;
672 ExprObjectKind OK = OK_ObjCProperty;
673 if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
674 PType->isVoidType())
675 VK = VK_RValue, OK = OK_Ordinary;
676
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000677 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000678 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
679 PType, VK, OK,
680 MemberLoc,
681 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000682 else
John McCall12f78a62010-12-02 01:19:52 +0000683 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
684 PType, VK, OK,
685 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000686
Chris Lattner7f816522010-04-11 07:45:24 +0000687 }
688
689 // Attempt to correct for typos in property names.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000690 TypoCorrection Corrected = CorrectTypo(
691 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
692 NULL, IFace, false, CTC_NoKeywords, OPT);
693 if (ObjCPropertyDecl *Property =
694 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>()) {
695 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +0000696 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000697 << MemberName << QualType(OPT, 0) << TypoResult
698 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000699 Diag(Property->getLocation(), diag::note_previous_decl)
700 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000701 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
702 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000703 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000704 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000705 ObjCInterfaceDecl *ClassDeclared;
706 if (ObjCIvarDecl *Ivar =
707 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
708 QualType T = Ivar->getType();
709 if (const ObjCObjectPointerType * OBJPT =
710 T->getAsObjCInterfacePointerType()) {
711 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
712 if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
713 if (IFace->isForwardDecl()) {
714 Diag(MemberLoc, diag::err_property_not_as_forward_class)
Fariborz Jahanian2a96bf52011-02-17 17:30:05 +0000715 << MemberName << IFace;
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000716 Diag(IFace->getLocation(), diag::note_forward_class);
717 return ExprError();
718 }
719 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000720 Diag(MemberLoc,
721 diag::err_ivar_access_using_property_syntax_suggest)
722 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
723 << FixItHint::CreateReplacement(OpLoc, "->");
724 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000725 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000726
Chris Lattner7f816522010-04-11 07:45:24 +0000727 Diag(MemberLoc, diag::err_property_not_found)
728 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000729 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000730 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000731 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000732 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000733}
734
735
736
John McCall60d7b3a2010-08-24 06:29:42 +0000737ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000738ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
739 IdentifierInfo &propertyName,
740 SourceLocation receiverNameLoc,
741 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000743 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000744 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
745 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000746
747 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000748 if (IFace == 0) {
749 // If the "receiver" is 'super' in a method, handle it as an expression-like
750 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000751 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000752 IsSuper = true;
753
John McCall26743b22011-02-03 09:00:02 +0000754 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000755 if (CurMethod->isInstanceMethod()) {
756 QualType T =
757 Context.getObjCInterfaceType(CurMethod->getClassInterface());
758 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000759
760 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000761 /*BaseExpr*/0,
762 SourceLocation()/*OpLoc*/,
763 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000764 propertyNameLoc,
765 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000766 }
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Chris Lattnereb483eb2010-04-11 08:28:14 +0000768 // Otherwise, if this is a class method, try dispatching to our
769 // superclass.
770 IFace = CurMethod->getClassInterface()->getSuperClass();
771 }
John McCall26743b22011-02-03 09:00:02 +0000772 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000773
774 if (IFace == 0) {
775 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
776 return ExprError();
777 }
778 }
779
780 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000781 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000782 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000783
784 // If this reference is in an @implementation, check for 'private' methods.
785 if (!Getter)
786 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
787 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000788 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000789 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000790
791 if (Getter) {
792 // FIXME: refactor/share with ActOnMemberReference().
793 // Check if we can reference this property.
794 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
795 return ExprError();
796 }
Mike Stump1eb44332009-09-09 15:08:12 +0000797
Steve Naroff61f72cb2009-03-09 21:12:44 +0000798 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000799 Selector SetterSel =
800 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000801 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000803 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000804 if (!Setter) {
805 // If this reference is in an @implementation, also check for 'private'
806 // methods.
807 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
808 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000809 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000810 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000811 }
812 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000813 if (!Setter)
814 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000815
816 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
817 return ExprError();
818
819 if (Getter || Setter) {
820 QualType PType;
821
John McCall09431682010-11-18 19:01:18 +0000822 ExprValueKind VK = VK_LValue;
823 if (Getter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000824 PType = getMessageSendResultType(Context.getObjCInterfaceType(IFace),
825 Getter, true,
826 receiverNamePtr->isStr("super"));
John McCall09431682010-11-18 19:01:18 +0000827 if (!getLangOptions().CPlusPlus &&
828 !PType.hasQualifiers() && PType->isVoidType())
829 VK = VK_RValue;
830 } else {
Steve Naroff61f72cb2009-03-09 21:12:44 +0000831 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
832 E = Setter->param_end(); PI != E; ++PI)
833 PType = (*PI)->getType();
John McCall09431682010-11-18 19:01:18 +0000834 VK = VK_LValue;
Steve Naroff61f72cb2009-03-09 21:12:44 +0000835 }
John McCall09431682010-11-18 19:01:18 +0000836
837 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
838
Douglas Gregor926df6c2011-06-11 01:09:30 +0000839 if (IsSuper)
840 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
841 PType, VK, OK,
842 propertyNameLoc,
843 receiverNameLoc,
844 Context.getObjCInterfaceType(IFace)));
845
John McCall12f78a62010-12-02 01:19:52 +0000846 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
847 PType, VK, OK,
848 propertyNameLoc,
849 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000850 }
851 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
852 << &propertyName << Context.getObjCInterfaceType(IFace));
853}
854
Douglas Gregor47bd5432010-04-14 02:46:37 +0000855Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000856 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000857 SourceLocation NameLoc,
858 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000859 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000860 ParsedType &ReceiverType) {
861 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000862
Douglas Gregor47bd5432010-04-14 02:46:37 +0000863 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000864 // messaging super. If the identifier is "super" and there is a
865 // trailing dot, it's an instance message.
866 if (IsSuper && S->isInObjcMethodScope())
867 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000868
869 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
870 LookupName(Result, S);
871
872 switch (Result.getResultKind()) {
873 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000874 // Normal name lookup didn't find anything. If we're in an
875 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000876 // FIXME: This is a hack. Ivar lookup should be part of normal
877 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000878 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
879 ObjCInterfaceDecl *ClassDeclared;
880 if (Method->getClassInterface()->lookupInstanceVariable(Name,
881 ClassDeclared))
882 return ObjCInstanceMessage;
883 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000884
Douglas Gregor47bd5432010-04-14 02:46:37 +0000885 // Break out; we'll perform typo correction below.
886 break;
887
888 case LookupResult::NotFoundInCurrentInstantiation:
889 case LookupResult::FoundOverloaded:
890 case LookupResult::FoundUnresolvedValue:
891 case LookupResult::Ambiguous:
892 Result.suppressDiagnostics();
893 return ObjCInstanceMessage;
894
895 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000896 // If the identifier is a class or not, and there is a trailing dot,
897 // it's an instance message.
898 if (HasTrailingDot)
899 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000900 // We found something. If it's a type, then we have a class
901 // message. Otherwise, it's an instance message.
902 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000903 QualType T;
904 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
905 T = Context.getObjCInterfaceType(Class);
906 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
907 T = Context.getTypeDeclType(Type);
908 else
909 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000910
Douglas Gregor1569f952010-04-21 20:38:13 +0000911 // We have a class message, and T is the type we're
912 // messaging. Build source-location information for it.
913 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000914 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000915 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000916 }
917 }
918
Douglas Gregoraaf87162010-04-14 20:04:41 +0000919 // Determine our typo-correction context.
920 CorrectTypoContext CTC = CTC_Expression;
921 if (ObjCMethodDecl *Method = getCurMethodDecl())
922 if (Method->getClassInterface() &&
923 Method->getClassInterface()->getSuperClass())
924 CTC = CTC_ObjCMessageReceiver;
925
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000926 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
927 Result.getLookupKind(), S, NULL,
928 NULL, false, CTC)) {
929 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000930 // If we found a declaration, correct when it refers to an Objective-C
931 // class.
Douglas Gregor1569f952010-04-21 20:38:13 +0000932 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000933 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000934 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000935 << FixItHint::CreateReplacement(SourceRange(NameLoc),
936 ND->getNameAsString());
937 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000938 << Corrected.getCorrection();
Douglas Gregor47bd5432010-04-14 02:46:37 +0000939
Douglas Gregor1569f952010-04-21 20:38:13 +0000940 QualType T = Context.getObjCInterfaceType(Class);
941 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000942 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000943 return ObjCClassMessage;
944 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000945 } else if (Corrected.isKeyword() &&
946 Corrected.getCorrectionAsIdentifierInfo()->isStr("super")) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000947 // If we've found the keyword "super", this is a send to super.
948 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000949 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000950 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000951 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000952 }
953 }
954
955 // Fall back: let the parser try to parse it as an instance message.
956 return ObjCInstanceMessage;
957}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000958
John McCall60d7b3a2010-08-24 06:29:42 +0000959ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000960 SourceLocation SuperLoc,
961 Selector Sel,
962 SourceLocation LBracLoc,
963 SourceLocation SelectorLoc,
964 SourceLocation RBracLoc,
965 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000966 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000967 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000968 if (!Method) {
969 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
970 return ExprError();
971 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000972
Douglas Gregorf95861a2010-04-21 20:01:04 +0000973 ObjCInterfaceDecl *Class = Method->getClassInterface();
974 if (!Class) {
975 Diag(SuperLoc, diag::error_no_super_class_message)
976 << Method->getDeclName();
977 return ExprError();
978 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000979
Douglas Gregorf95861a2010-04-21 20:01:04 +0000980 ObjCInterfaceDecl *Super = Class->getSuperClass();
981 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000982 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000983 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
984 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000985 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000986 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000987
Douglas Gregorf95861a2010-04-21 20:01:04 +0000988 // We are in a method whose class has a superclass, so 'super'
989 // is acting as a keyword.
990 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +0000991 if (Sel.getMethodFamily() == OMF_dealloc)
992 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +0000993 if (Sel.getMethodFamily() == OMF_finalize)
994 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +0000995
Douglas Gregorf95861a2010-04-21 20:01:04 +0000996 // Since we are in an instance method, this is an instance
997 // message to the superclass instance.
998 QualType SuperTy = Context.getObjCInterfaceType(Super);
999 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +00001000 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001001 Sel, /*Method=*/0,
1002 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001003 }
Douglas Gregorf95861a2010-04-21 20:01:04 +00001004
1005 // Since we are in a class method, this is a class message to
1006 // the superclass.
1007 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
1008 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001009 SuperLoc, Sel, /*Method=*/0,
1010 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001011}
1012
1013/// \brief Build an Objective-C class message expression.
1014///
1015/// This routine takes care of both normal class messages and
1016/// class messages to the superclass.
1017///
1018/// \param ReceiverTypeInfo Type source information that describes the
1019/// receiver of this message. This may be NULL, in which case we are
1020/// sending to the superclass and \p SuperLoc must be a valid source
1021/// location.
1022
1023/// \param ReceiverType The type of the object receiving the
1024/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1025/// type as that refers to. For a superclass send, this is the type of
1026/// the superclass.
1027///
1028/// \param SuperLoc The location of the "super" keyword in a
1029/// superclass message.
1030///
1031/// \param Sel The selector to which the message is being sent.
1032///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001033/// \param Method The method that this class message is invoking, if
1034/// already known.
1035///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001036/// \param LBracLoc The location of the opening square bracket ']'.
1037///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001038/// \param RBrac The location of the closing square bracket ']'.
1039///
1040/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001041ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001042 QualType ReceiverType,
1043 SourceLocation SuperLoc,
1044 Selector Sel,
1045 ObjCMethodDecl *Method,
1046 SourceLocation LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001047 SourceLocation SelectorLoc,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001048 SourceLocation RBracLoc,
1049 MultiExprArg ArgsIn) {
1050 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001051 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001052 if (LBracLoc.isInvalid()) {
1053 Diag(Loc, diag::err_missing_open_square_message_send)
1054 << FixItHint::CreateInsertion(Loc, "[");
1055 LBracLoc = Loc;
1056 }
1057
Douglas Gregor92e986e2010-04-22 16:44:27 +00001058 if (ReceiverType->isDependentType()) {
1059 // If the receiver type is dependent, we can't type-check anything
1060 // at this point. Build a dependent expression.
1061 unsigned NumArgs = ArgsIn.size();
1062 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1063 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001064 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1065 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001066 Sel, SelectorLoc, /*Method=*/0,
Douglas Gregor92e986e2010-04-22 16:44:27 +00001067 Args, NumArgs, RBracLoc));
1068 }
Chris Lattner15faee12010-04-12 05:38:43 +00001069
Douglas Gregor2725ca82010-04-21 19:57:20 +00001070 // Find the class to which we are sending this message.
1071 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001072 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1073 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001074 Diag(Loc, diag::err_invalid_receiver_class_message)
1075 << ReceiverType;
1076 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001077 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001078 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian02b0d652011-03-08 19:12:46 +00001079 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001080 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001081 if (!Method) {
1082 if (Class->isForwardDecl()) {
John McCallf85e1932011-06-15 23:02:42 +00001083 if (getLangOptions().ObjCAutoRefCount) {
1084 Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
1085 } else {
1086 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1087 }
1088
Douglas Gregorf49bb082010-04-22 17:01:48 +00001089 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001090 Method = LookupFactoryMethodInGlobalPool(Sel,
1091 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001092 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001093 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1094 << Method->getDeclName();
1095 }
1096 if (!Method)
1097 Method = Class->lookupClassMethod(Sel);
1098
1099 // If we have an implementation in scope, check "private" methods.
1100 if (!Method)
1101 Method = LookupPrivateClassMethod(Sel, Class);
1102
1103 if (Method && DiagnoseUseOfDecl(Method, Loc))
1104 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001105 }
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Douglas Gregor2725ca82010-04-21 19:57:20 +00001107 // Check the argument types and determine the result type.
1108 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001109 ExprValueKind VK = VK_RValue;
1110
Douglas Gregor2725ca82010-04-21 19:57:20 +00001111 unsigned NumArgs = ArgsIn.size();
1112 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001113 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1114 SuperLoc.isValid(), LBracLoc, RBracLoc,
1115 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001116 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001117
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001118 if (Method && !Method->getResultType()->isVoidType() &&
1119 RequireCompleteType(LBracLoc, Method->getResultType(),
1120 diag::err_illegal_message_expr_incomplete_type))
1121 return ExprError();
1122
Douglas Gregor2725ca82010-04-21 19:57:20 +00001123 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001124 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001125 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001126 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001127 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001128 ReceiverType, Sel, SelectorLoc,
1129 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001130 else
John McCallf89e55a2010-11-18 06:31:45 +00001131 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001132 ReceiverTypeInfo, Sel, SelectorLoc,
1133 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001134 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001135}
1136
Douglas Gregor2725ca82010-04-21 19:57:20 +00001137// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001138// ArgExprs is optional - if it is present, the number of expressions
1139// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001140ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001141 ParsedType Receiver,
1142 Selector Sel,
1143 SourceLocation LBracLoc,
1144 SourceLocation SelectorLoc,
1145 SourceLocation RBracLoc,
1146 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001147 TypeSourceInfo *ReceiverTypeInfo;
1148 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1149 if (ReceiverType.isNull())
1150 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Mike Stump1eb44332009-09-09 15:08:12 +00001152
Douglas Gregor2725ca82010-04-21 19:57:20 +00001153 if (!ReceiverTypeInfo)
1154 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1155
1156 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001157 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001158 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001159}
1160
1161/// \brief Build an Objective-C instance message expression.
1162///
1163/// This routine takes care of both normal instance messages and
1164/// instance messages to the superclass instance.
1165///
1166/// \param Receiver The expression that computes the object that will
1167/// receive this message. This may be empty, in which case we are
1168/// sending to the superclass instance and \p SuperLoc must be a valid
1169/// source location.
1170///
1171/// \param ReceiverType The (static) type of the object receiving the
1172/// message. When a \p Receiver expression is provided, this is the
1173/// same type as that expression. For a superclass instance send, this
1174/// is a pointer to the type of the superclass.
1175///
1176/// \param SuperLoc The location of the "super" keyword in a
1177/// superclass instance message.
1178///
1179/// \param Sel The selector to which the message is being sent.
1180///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001181/// \param Method The method that this instance message is invoking, if
1182/// already known.
1183///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001184/// \param LBracLoc The location of the opening square bracket ']'.
1185///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001186/// \param RBrac The location of the closing square bracket ']'.
1187///
1188/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001189ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001190 QualType ReceiverType,
1191 SourceLocation SuperLoc,
1192 Selector Sel,
1193 ObjCMethodDecl *Method,
1194 SourceLocation LBracLoc,
1195 SourceLocation SelectorLoc,
1196 SourceLocation RBracLoc,
1197 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001198 // The location of the receiver.
1199 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1200
1201 if (LBracLoc.isInvalid()) {
1202 Diag(Loc, diag::err_missing_open_square_message_send)
1203 << FixItHint::CreateInsertion(Loc, "[");
1204 LBracLoc = Loc;
1205 }
1206
Douglas Gregor2725ca82010-04-21 19:57:20 +00001207 // If we have a receiver expression, perform appropriate promotions
1208 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001209 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001210 if (Receiver->isTypeDependent()) {
1211 // If the receiver is type-dependent, we can't type-check anything
1212 // at this point. Build a dependent expression.
1213 unsigned NumArgs = ArgsIn.size();
1214 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1215 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1216 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001217 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001218 SelectorLoc, /*Method=*/0,
1219 Args, NumArgs, RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001220 }
1221
Douglas Gregor2725ca82010-04-21 19:57:20 +00001222 // If necessary, apply function/array conversion to the receiver.
1223 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001224 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1225 if (Result.isInvalid())
1226 return ExprError();
1227 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001228 ReceiverType = Receiver->getType();
1229 }
1230
Douglas Gregorf49bb082010-04-22 17:01:48 +00001231 if (!Method) {
1232 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001233 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001234 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001235 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1236 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001237 SourceRange(LBracLoc, RBracLoc),
1238 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001239 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001240 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001241 SourceRange(LBracLoc, RBracLoc),
1242 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001243 } else if (ReceiverType->isObjCClassType() ||
1244 ReceiverType->isObjCQualifiedClassType()) {
1245 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001246 // We allow sending a message to a qualified Class ("Class<foo>"), which
1247 // is ok as long as one of the protocols implements the selector (if not, warn).
1248 if (const ObjCObjectPointerType *QClassTy
1249 = ReceiverType->getAsObjCQualifiedClassType()) {
1250 // Search protocols for class methods.
1251 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1252 if (!Method) {
1253 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1254 // warn if instance method found for a Class message.
1255 if (Method) {
1256 Diag(Loc, diag::warn_instance_method_on_class_found)
1257 << Method->getSelector() << Sel;
1258 Diag(Method->getLocation(), diag::note_method_declared_at);
1259 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001260 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001261 } else {
1262 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1263 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1264 // First check the public methods in the class interface.
1265 Method = ClassDecl->lookupClassMethod(Sel);
1266
1267 if (!Method)
1268 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1269 }
1270 if (Method && DiagnoseUseOfDecl(Method, Loc))
1271 return ExprError();
1272 }
1273 if (!Method) {
1274 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregorc737acb2011-09-27 16:10:05 +00001275 if (!Receiver || !isSelfExpr(Receiver)) {
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001276 Method = LookupFactoryMethodInGlobalPool(Sel,
1277 SourceRange(LBracLoc, RBracLoc),
1278 true);
1279 if (!Method) {
1280 // If no class (factory) method was found, check if an _instance_
1281 // method of the same name exists in the root class only.
1282 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001283 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001284 true);
1285 if (Method)
1286 if (const ObjCInterfaceDecl *ID =
1287 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1288 if (ID->getSuperClass())
1289 Diag(Loc, diag::warn_root_inst_method_not_found)
1290 << Sel << SourceRange(LBracLoc, RBracLoc);
1291 }
1292 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001293 }
1294 }
1295 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001296 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001297 ObjCInterfaceDecl* ClassDecl = 0;
1298
1299 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1300 // long as one of the protocols implements the selector (if not, warn).
1301 if (const ObjCObjectPointerType *QIdTy
1302 = ReceiverType->getAsObjCQualifiedIdType()) {
1303 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001304 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1305 if (!Method)
1306 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001307 } else if (const ObjCObjectPointerType *OCIType
1308 = ReceiverType->getAsObjCInterfacePointerType()) {
1309 // We allow sending a message to a pointer to an interface (an object).
1310 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001311
1312 if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCount) {
1313 Diag(Loc, diag::err_arc_receiver_forward_instance)
1314 << OCIType->getPointeeType()
1315 << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperLoc));
1316 return ExprError();
1317 }
1318
Douglas Gregorf49bb082010-04-22 17:01:48 +00001319 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1320 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +00001321 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001322 Method = ClassDecl->lookupInstanceMethod(Sel);
1323
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001324 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001325 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001326 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1327
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001328 const ObjCInterfaceDecl *forwardClass = 0;
Douglas Gregorf49bb082010-04-22 17:01:48 +00001329 if (!Method) {
1330 // If we have implementations in scope, check "private" methods.
1331 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1332
John McCallf85e1932011-06-15 23:02:42 +00001333 if (!Method && getLangOptions().ObjCAutoRefCount) {
1334 Diag(Loc, diag::err_arc_may_not_respond)
1335 << OCIType->getPointeeType() << Sel;
1336 return ExprError();
1337 }
1338
Douglas Gregorc737acb2011-09-27 16:10:05 +00001339 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001340 // If we still haven't found a method, look in the global pool. This
1341 // behavior isn't very desirable, however we need it for GCC
1342 // compatibility. FIXME: should we deviate??
1343 if (OCIType->qual_empty()) {
1344 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001345 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001346 if (OCIType->getInterfaceDecl()->isForwardDecl())
1347 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001348 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001349 Diag(Loc, diag::warn_maynot_respond)
1350 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1351 }
1352 }
1353 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001354 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001355 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001356 } else if (!getLangOptions().ObjCAutoRefCount &&
1357 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001358 (ReceiverType->isPointerType() ||
1359 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001360 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001361 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001362 Diag(Loc, diag::warn_bad_receiver_type)
1363 << ReceiverType
1364 << Receiver->getSourceRange();
1365 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001366 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00001367 CK_CPointerToObjCPointerCast).take();
John McCall404cd162010-11-13 01:35:44 +00001368 else {
1369 // TODO: specialized warning on null receivers?
1370 bool IsNull = Receiver->isNullPointerConstant(Context,
1371 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001372 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1373 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001374 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001375 ReceiverType = Receiver->getType();
John McCall0bcc9bc2011-09-09 06:11:02 +00001376 } else {
John Wiegley429bb272011-04-08 18:41:53 +00001377 ExprResult ReceiverRes;
1378 if (getLangOptions().CPlusPlus)
John McCall0bcc9bc2011-09-09 06:11:02 +00001379 ReceiverRes = PerformContextuallyConvertToObjCPointer(Receiver);
John Wiegley429bb272011-04-08 18:41:53 +00001380 if (ReceiverRes.isUsable()) {
1381 Receiver = ReceiverRes.take();
John Wiegley429bb272011-04-08 18:41:53 +00001382 return BuildInstanceMessage(Receiver,
1383 ReceiverType,
1384 SuperLoc,
1385 Sel,
1386 Method,
1387 LBracLoc,
1388 SelectorLoc,
1389 RBracLoc,
1390 move(ArgsIn));
1391 } else {
1392 // Reject other random receiver types (e.g. structs).
1393 Diag(Loc, diag::err_bad_receiver_type)
1394 << ReceiverType << Receiver->getSourceRange();
1395 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001396 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001397 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001398 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001399 }
Mike Stump1eb44332009-09-09 15:08:12 +00001400
Douglas Gregor2725ca82010-04-21 19:57:20 +00001401 // Check the message arguments.
1402 unsigned NumArgs = ArgsIn.size();
1403 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1404 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001405 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001406 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1407 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001408 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1409 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001410 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001411 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001412
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001413 if (Method && !Method->getResultType()->isVoidType() &&
1414 RequireCompleteType(LBracLoc, Method->getResultType(),
1415 diag::err_illegal_message_expr_incomplete_type))
1416 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001417
John McCallf85e1932011-06-15 23:02:42 +00001418 // In ARC, forbid the user from sending messages to
1419 // retain/release/autorelease/dealloc/retainCount explicitly.
1420 if (getLangOptions().ObjCAutoRefCount) {
1421 ObjCMethodFamily family =
1422 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1423 switch (family) {
1424 case OMF_init:
1425 if (Method)
1426 checkInitMethod(Method, ReceiverType);
1427
1428 case OMF_None:
1429 case OMF_alloc:
1430 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00001431 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00001432 case OMF_mutableCopy:
1433 case OMF_new:
1434 case OMF_self:
1435 break;
1436
1437 case OMF_dealloc:
1438 case OMF_retain:
1439 case OMF_release:
1440 case OMF_autorelease:
1441 case OMF_retainCount:
1442 Diag(Loc, diag::err_arc_illegal_explicit_message)
1443 << Sel << SelectorLoc;
1444 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001445
1446 case OMF_performSelector:
1447 if (Method && NumArgs >= 1) {
1448 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1449 Selector ArgSel = SelExp->getSelector();
1450 ObjCMethodDecl *SelMethod =
1451 LookupInstanceMethodInGlobalPool(ArgSel,
1452 SelExp->getSourceRange());
1453 if (!SelMethod)
1454 SelMethod =
1455 LookupFactoryMethodInGlobalPool(ArgSel,
1456 SelExp->getSourceRange());
1457 if (SelMethod) {
1458 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1459 switch (SelFamily) {
1460 case OMF_alloc:
1461 case OMF_copy:
1462 case OMF_mutableCopy:
1463 case OMF_new:
1464 case OMF_self:
1465 case OMF_init:
1466 // Issue error, unless ns_returns_not_retained.
1467 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1468 // selector names a +1 method
1469 Diag(SelectorLoc,
1470 diag::err_arc_perform_selector_retains);
1471 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1472 }
1473 break;
1474 default:
1475 // +0 call. OK. unless ns_returns_retained.
1476 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1477 // selector names a +1 method
1478 Diag(SelectorLoc,
1479 diag::err_arc_perform_selector_retains);
1480 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1481 }
1482 break;
1483 }
1484 }
1485 } else {
1486 // error (may leak).
1487 Diag(SelectorLoc, diag::warn_arc_perform_selector_leaks);
1488 Diag(Args[0]->getExprLoc(), diag::note_used_here);
1489 }
1490 }
1491 break;
John McCallf85e1932011-06-15 23:02:42 +00001492 }
1493 }
1494
Douglas Gregor2725ca82010-04-21 19:57:20 +00001495 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001496 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001497 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001498 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001499 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001500 ReceiverType, Sel, SelectorLoc, Method,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001501 Args, NumArgs, RBracLoc);
1502 else
John McCallf89e55a2010-11-18 06:31:45 +00001503 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001504 Receiver, Sel, SelectorLoc, Method,
1505 Args, NumArgs, RBracLoc);
John McCallf85e1932011-06-15 23:02:42 +00001506
1507 if (getLangOptions().ObjCAutoRefCount) {
1508 // In ARC, annotate delegate init calls.
1509 if (Result->getMethodFamily() == OMF_init &&
Douglas Gregorc737acb2011-09-27 16:10:05 +00001510 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
John McCallf85e1932011-06-15 23:02:42 +00001511 // Only consider init calls *directly* in init implementations,
1512 // not within blocks.
1513 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1514 if (method && method->getMethodFamily() == OMF_init) {
1515 // The implicit assignment to self means we also don't want to
1516 // consume the result.
1517 Result->setDelegateInitCall(true);
1518 return Owned(Result);
1519 }
1520 }
1521
1522 // In ARC, check for message sends which are likely to introduce
1523 // retain cycles.
1524 checkRetainCycles(Result);
1525 }
1526
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001527 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001528}
1529
1530// ActOnInstanceMessage - used for both unary and keyword messages.
1531// ArgExprs is optional - if it is present, the number of expressions
1532// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001533ExprResult Sema::ActOnInstanceMessage(Scope *S,
1534 Expr *Receiver,
1535 Selector Sel,
1536 SourceLocation LBracLoc,
1537 SourceLocation SelectorLoc,
1538 SourceLocation RBracLoc,
1539 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001540 if (!Receiver)
1541 return ExprError();
1542
John McCall9ae2f072010-08-23 23:25:46 +00001543 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001544 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001545 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001546}
Chris Lattnereca7be62008-04-07 05:30:13 +00001547
John McCallf85e1932011-06-15 23:02:42 +00001548enum ARCConversionTypeClass {
1549 ACTC_none,
1550 ACTC_retainable,
1551 ACTC_indirectRetainable
1552};
1553static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
1554 ARCConversionTypeClass ACTC = ACTC_retainable;
1555
1556 // Ignore an outermost reference type.
1557 if (const ReferenceType *ref = type->getAs<ReferenceType>())
1558 type = ref->getPointeeType();
1559
1560 // Drill through pointers and arrays recursively.
1561 while (true) {
1562 if (const PointerType *ptr = type->getAs<PointerType>()) {
1563 type = ptr->getPointeeType();
1564 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1565 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1566 } else {
1567 break;
1568 }
1569 ACTC = ACTC_indirectRetainable;
1570 }
1571
1572 if (!type->isObjCRetainableType()) return ACTC_none;
1573 return ACTC;
1574}
1575
1576namespace {
1577 /// Return true if the given expression can be reasonably converted
1578 /// between a retainable pointer type and a C pointer type.
1579 struct ARCCastChecker : StmtVisitor<ARCCastChecker, bool> {
1580 ASTContext &Context;
1581 ARCCastChecker(ASTContext &Context) : Context(Context) {}
1582 bool VisitStmt(Stmt *s) {
1583 return false;
1584 }
1585 bool VisitExpr(Expr *e) {
1586 return e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
1587 }
1588
1589 bool VisitParenExpr(ParenExpr *e) {
1590 return Visit(e->getSubExpr());
1591 }
1592 bool VisitCastExpr(CastExpr *e) {
1593 switch (e->getCastKind()) {
1594 case CK_NullToPointer:
1595 return true;
1596 case CK_NoOp:
1597 case CK_LValueToRValue:
1598 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00001599 case CK_CPointerToObjCPointerCast:
1600 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00001601 case CK_AnyPointerToBlockPointerCast:
1602 return Visit(e->getSubExpr());
1603 default:
1604 return false;
1605 }
1606 }
1607 bool VisitUnaryExtension(UnaryOperator *e) {
1608 return Visit(e->getSubExpr());
1609 }
1610 bool VisitBinComma(BinaryOperator *e) {
1611 return Visit(e->getRHS());
1612 }
1613 bool VisitConditionalOperator(ConditionalOperator *e) {
1614 // Conditional operators are okay if both sides are okay.
1615 return Visit(e->getTrueExpr()) && Visit(e->getFalseExpr());
1616 }
1617 bool VisitObjCStringLiteral(ObjCStringLiteral *e) {
1618 // Always white-list Objective-C string literals.
1619 return true;
1620 }
1621 bool VisitStmtExpr(StmtExpr *e) {
1622 return Visit(e->getSubStmt()->body_back());
1623 }
1624 bool VisitDeclRefExpr(DeclRefExpr *e) {
1625 // White-list references to global extern strings from system
1626 // headers.
1627 if (VarDecl *var = dyn_cast<VarDecl>(e->getDecl()))
1628 if (var->getStorageClass() == SC_Extern &&
1629 var->getType().isConstQualified() &&
1630 Context.getSourceManager().isInSystemHeader(var->getLocation()))
1631 return true;
1632 return false;
1633 }
1634 };
1635}
1636
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001637bool
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001638Sema::ValidObjCARCNoBridgeCastExpr(Expr *&Exp, QualType castType) {
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001639 Expr *NewExp = Exp->IgnoreParenCasts();
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001640
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001641 if (!isa<ObjCMessageExpr>(NewExp) && !isa<ObjCPropertyRefExpr>(NewExp)
1642 && !isa<CallExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001643 return false;
1644 ObjCMethodDecl *method = 0;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001645 bool MethodReturnsPlusOne = false;
1646
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001647 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(NewExp)) {
1648 method = PRE->getExplicitProperty()->getGetterMethodDecl();
1649 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001650 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001651 method = ME->getMethodDecl();
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001652 else {
1653 CallExpr *CE = cast<CallExpr>(NewExp);
1654 Decl *CallDecl = CE->getCalleeDecl();
1655 if (!CallDecl)
1656 return false;
1657 if (CallDecl->hasAttr<CFReturnsNotRetainedAttr>())
1658 return true;
1659 MethodReturnsPlusOne = CallDecl->hasAttr<CFReturnsRetainedAttr>();
1660 if (!MethodReturnsPlusOne) {
1661 if (NamedDecl *ND = dyn_cast<NamedDecl>(CallDecl))
1662 if (const IdentifierInfo *Id = ND->getIdentifier())
1663 if (Id->isStr("__builtin___CFStringMakeConstantString"))
1664 return true;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001665 }
1666 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001667
1668 if (!MethodReturnsPlusOne) {
1669 if (!method)
1670 return false;
1671 if (method->hasAttr<CFReturnsNotRetainedAttr>())
1672 return true;
1673 MethodReturnsPlusOne = method->hasAttr<CFReturnsRetainedAttr>();
1674 if (!MethodReturnsPlusOne) {
1675 ObjCMethodFamily family = method->getSelector().getMethodFamily();
1676 switch (family) {
1677 case OMF_alloc:
1678 case OMF_copy:
1679 case OMF_mutableCopy:
1680 case OMF_new:
1681 MethodReturnsPlusOne = true;
1682 break;
1683 default:
1684 break;
1685 }
1686 }
1687 }
1688
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001689 if (MethodReturnsPlusOne) {
1690 TypeSourceInfo *TSInfo =
1691 Context.getTrivialTypeSourceInfo(castType, SourceLocation());
1692 ExprResult ExpRes = BuildObjCBridgedCast(SourceLocation(), OBC_BridgeTransfer,
1693 SourceLocation(), TSInfo, Exp);
1694 Exp = ExpRes.take();
1695 }
1696 return true;
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001697}
1698
John McCallf85e1932011-06-15 23:02:42 +00001699void
1700Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001701 Expr *&castExpr, CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00001702 QualType castExprType = castExpr->getType();
1703
1704 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1705 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
1706 if (exprACTC == castACTC) return;
Fariborz Jahanian8295b7b2011-06-22 16:36:45 +00001707 if (exprACTC && castType->isIntegralType(Context)) return;
John McCallf85e1932011-06-15 23:02:42 +00001708
1709 // Allow casts between pointers to lifetime types (e.g., __strong id*)
1710 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1711 // must be explicit.
1712 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
1713 if (const PointerType *CastExprPtr = castExprType->getAs<PointerType>()) {
1714 QualType CastPointee = CastPtr->getPointeeType();
1715 QualType CastExprPointee = CastExprPtr->getPointeeType();
1716 if ((CCK != CCK_ImplicitConversion &&
1717 CastPointee->isObjCIndirectLifetimeType() &&
1718 CastExprPointee->isVoidType()) ||
1719 (CastPointee->isVoidType() &&
1720 CastExprPointee->isObjCIndirectLifetimeType()))
1721 return;
1722 }
1723 }
1724
1725 if (ARCCastChecker(Context).Visit(castExpr))
1726 return;
1727
1728 SourceLocation loc =
1729 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
1730
1731 if (makeUnavailableInSystemHeader(loc,
1732 "converts between Objective-C and C pointers in -fobjc-arc"))
1733 return;
1734
John McCall71c482c2011-06-17 06:50:50 +00001735 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00001736 switch (exprACTC) {
1737 case ACTC_none:
1738 srcKind = (castExprType->isPointerType() ? 1 : 0);
1739 break;
1740 case ACTC_retainable:
1741 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1742 break;
1743 case ACTC_indirectRetainable:
1744 srcKind = 4;
1745 break;
1746 }
1747
1748 if (CCK == CCK_CStyleCast) {
1749 // Check whether this could be fixed with a bridge cast.
1750 SourceLocation AfterLParen = PP.getLocForEndOfToken(castRange.getBegin());
1751 SourceLocation NoteLoc = AfterLParen.isValid()? AfterLParen : loc;
1752
1753 if (castType->isObjCARCBridgableType() &&
1754 castExprType->isCARCBridgableType()) {
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001755 // explicit unbridged casts are allowed if the source of the cast is a
1756 // message sent to an objc method (or property access)
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001757 if (ValidObjCARCNoBridgeCastExpr(castExpr, castType))
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001758 return;
John McCallf85e1932011-06-15 23:02:42 +00001759 Diag(loc, diag::err_arc_cast_requires_bridge)
1760 << 2
1761 << castExprType
1762 << (castType->isBlockPointerType()? 1 : 0)
1763 << castType
1764 << castRange
1765 << castExpr->getSourceRange();
1766 Diag(NoteLoc, diag::note_arc_bridge)
1767 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1768 Diag(NoteLoc, diag::note_arc_bridge_transfer)
1769 << castExprType
1770 << FixItHint::CreateInsertion(AfterLParen, "__bridge_transfer ");
1771
1772 return;
1773 }
1774
1775 if (castType->isCARCBridgableType() &&
1776 castExprType->isObjCARCBridgableType()){
1777 Diag(loc, diag::err_arc_cast_requires_bridge)
1778 << (castExprType->isBlockPointerType()? 1 : 0)
1779 << castExprType
1780 << 2
1781 << castType
1782 << castRange
1783 << castExpr->getSourceRange();
1784
1785 Diag(NoteLoc, diag::note_arc_bridge)
1786 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1787 Diag(NoteLoc, diag::note_arc_bridge_retained)
1788 << castType
1789 << FixItHint::CreateInsertion(AfterLParen, "__bridge_retained ");
1790 return;
1791 }
1792 }
1793
1794 Diag(loc, diag::err_arc_mismatched_cast)
1795 << (CCK != CCK_ImplicitConversion) << srcKind << castExprType << castType
1796 << castRange << castExpr->getSourceRange();
1797}
1798
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00001799bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
1800 QualType exprType) {
1801 QualType canCastType =
1802 Context.getCanonicalType(castType).getUnqualifiedType();
1803 QualType canExprType =
1804 Context.getCanonicalType(exprType).getUnqualifiedType();
1805 if (isa<ObjCObjectPointerType>(canCastType) &&
1806 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
1807 canExprType->isObjCObjectPointerType()) {
1808 if (const ObjCObjectPointerType *ObjT =
1809 canExprType->getAs<ObjCObjectPointerType>())
1810 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
1811 return false;
1812 }
1813 return true;
1814}
1815
John McCall7e5e5f42011-07-07 06:58:02 +00001816/// Look for an ObjCReclaimReturnedObject cast and destroy it.
1817static Expr *maybeUndoReclaimObject(Expr *e) {
1818 // For now, we just undo operands that are *immediately* reclaim
1819 // expressions, which prevents the vast majority of potential
1820 // problems here. To catch them all, we'd need to rebuild arbitrary
1821 // value-propagating subexpressions --- we can't reliably rebuild
1822 // in-place because of expression sharing.
1823 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
John McCall33e56f32011-09-10 06:18:15 +00001824 if (ice->getCastKind() == CK_ARCReclaimReturnedObject)
John McCall7e5e5f42011-07-07 06:58:02 +00001825 return ice->getSubExpr();
1826
1827 return e;
1828}
1829
John McCallf85e1932011-06-15 23:02:42 +00001830ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
1831 ObjCBridgeCastKind Kind,
1832 SourceLocation BridgeKeywordLoc,
1833 TypeSourceInfo *TSInfo,
1834 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00001835 ExprResult SubResult = UsualUnaryConversions(SubExpr);
1836 if (SubResult.isInvalid()) return ExprError();
1837 SubExpr = SubResult.take();
1838
John McCallf85e1932011-06-15 23:02:42 +00001839 QualType T = TSInfo->getType();
1840 QualType FromType = SubExpr->getType();
1841
John McCall1d9b3b22011-09-09 05:25:32 +00001842 CastKind CK;
1843
John McCallf85e1932011-06-15 23:02:42 +00001844 bool MustConsume = false;
1845 if (T->isDependentType() || SubExpr->isTypeDependent()) {
1846 // Okay: we'll build a dependent expression type.
John McCall1d9b3b22011-09-09 05:25:32 +00001847 CK = CK_Dependent;
John McCallf85e1932011-06-15 23:02:42 +00001848 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
1849 // Casting CF -> id
John McCall1d9b3b22011-09-09 05:25:32 +00001850 CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast
1851 : CK_CPointerToObjCPointerCast);
John McCallf85e1932011-06-15 23:02:42 +00001852 switch (Kind) {
1853 case OBC_Bridge:
1854 break;
1855
1856 case OBC_BridgeRetained:
1857 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1858 << 2
1859 << FromType
1860 << (T->isBlockPointerType()? 1 : 0)
1861 << T
1862 << SubExpr->getSourceRange()
1863 << Kind;
1864 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1865 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
1866 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
1867 << FromType
1868 << FixItHint::CreateReplacement(BridgeKeywordLoc,
1869 "__bridge_transfer ");
1870
1871 Kind = OBC_Bridge;
1872 break;
1873
1874 case OBC_BridgeTransfer:
1875 // We must consume the Objective-C object produced by the cast.
1876 MustConsume = true;
1877 break;
1878 }
1879 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
1880 // Okay: id -> CF
John McCall1d9b3b22011-09-09 05:25:32 +00001881 CK = CK_BitCast;
John McCallf85e1932011-06-15 23:02:42 +00001882 switch (Kind) {
1883 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00001884 // Reclaiming a value that's going to be __bridge-casted to CF
1885 // is very dangerous, so we don't do it.
1886 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00001887 break;
1888
1889 case OBC_BridgeRetained:
1890 // Produce the object before casting it.
1891 SubExpr = ImplicitCastExpr::Create(Context, FromType,
John McCall33e56f32011-09-10 06:18:15 +00001892 CK_ARCProduceObject,
John McCallf85e1932011-06-15 23:02:42 +00001893 SubExpr, 0, VK_RValue);
1894 break;
1895
1896 case OBC_BridgeTransfer:
1897 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1898 << (FromType->isBlockPointerType()? 1 : 0)
1899 << FromType
1900 << 2
1901 << T
1902 << SubExpr->getSourceRange()
1903 << Kind;
1904
1905 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1906 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
1907 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
1908 << T
1909 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
1910
1911 Kind = OBC_Bridge;
1912 break;
1913 }
1914 } else {
1915 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
1916 << FromType << T << Kind
1917 << SubExpr->getSourceRange()
1918 << TSInfo->getTypeLoc().getSourceRange();
1919 return ExprError();
1920 }
1921
John McCall1d9b3b22011-09-09 05:25:32 +00001922 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK,
John McCallf85e1932011-06-15 23:02:42 +00001923 BridgeKeywordLoc,
1924 TSInfo, SubExpr);
1925
1926 if (MustConsume) {
1927 ExprNeedsCleanups = true;
John McCall33e56f32011-09-10 06:18:15 +00001928 Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result,
John McCallf85e1932011-06-15 23:02:42 +00001929 0, VK_RValue);
1930 }
1931
1932 return Result;
1933}
1934
1935ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
1936 SourceLocation LParenLoc,
1937 ObjCBridgeCastKind Kind,
1938 SourceLocation BridgeKeywordLoc,
1939 ParsedType Type,
1940 SourceLocation RParenLoc,
1941 Expr *SubExpr) {
1942 TypeSourceInfo *TSInfo = 0;
1943 QualType T = GetTypeFromParser(Type, &TSInfo);
1944 if (!TSInfo)
1945 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
1946 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
1947 SubExpr);
1948}