blob: 3df6d3f96e431f1bfbf1fc8cca2eb155f5f19f32 [file] [log] [blame]
Chris Lattner85a932e2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000016#include "clang/Sema/Scope.h"
John McCall26743b22011-02-03 09:00:02 +000017#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000018#include "clang/Sema/Initialization.h"
Chris Lattner85a932e2008-01-04 22:32:30 +000019#include "clang/AST/ASTContext.h"
20#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000021#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000022#include "clang/AST/StmtVisitor.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000023#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000024#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000025#include "clang/Lex/Preprocessor.h"
26
Chris Lattner85a932e2008-01-04 22:32:30 +000027using namespace clang;
John McCall26743b22011-02-03 09:00:02 +000028using namespace sema;
Chris Lattner85a932e2008-01-04 22:32:30 +000029
John McCallf312b1e2010-08-26 23:41:50 +000030ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
31 Expr **strings,
32 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000033 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
34
Chris Lattnerf4b136f2009-02-18 06:13:04 +000035 // Most ObjC strings are formed out of a single piece. However, we *can*
36 // have strings formed out of multiple @ strings with multiple pptokens in
37 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
38 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner39c28bb2009-02-18 06:48:40 +000039 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000040
Chris Lattnerf4b136f2009-02-18 06:13:04 +000041 // If we have a multi-part string, merge it all together.
42 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000043 // Concatenate objc strings.
Chris Lattner39c28bb2009-02-18 06:48:40 +000044 llvm::SmallString<128> StrBuf;
45 llvm::SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000046
Chris Lattner726e1682009-02-18 05:49:11 +000047 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000048 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000049
Chris Lattner39c28bb2009-02-18 06:48:40 +000050 // ObjC strings can't be wide.
Chris Lattnerf4b136f2009-02-18 06:13:04 +000051 if (S->isWide()) {
52 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
53 << S->getSourceRange();
54 return true;
55 }
Mike Stump1eb44332009-09-09 15:08:12 +000056
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +000057 // Append the string.
58 StrBuf += S->getString();
Mike Stump1eb44332009-09-09 15:08:12 +000059
Chris Lattner39c28bb2009-02-18 06:48:40 +000060 // Get the locations of the string tokens.
61 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattner85a932e2008-01-04 22:32:30 +000062 }
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattner39c28bb2009-02-18 06:48:40 +000064 // Create the aggregate string with the appropriate content and location
65 // information.
Jay Foad65aa6882011-06-21 15:13:30 +000066 S = StringLiteral::Create(Context, StrBuf,
Anders Carlsson3e2193c2011-04-14 00:40:03 +000067 /*Wide=*/false, /*Pascal=*/false,
Chris Lattner2085fd62009-02-18 06:40:38 +000068 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000069 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000070 }
Mike Stump1eb44332009-09-09 15:08:12 +000071
Chris Lattner69039812009-02-18 06:01:06 +000072 // Verify that this composite string is acceptable for ObjC strings.
73 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000074 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000075
76 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000077 // the NSString interface is seen in this translation unit. Note: We
78 // don't use NSConstantString, since the runtime team considers this
79 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000080 QualType Ty = Context.getObjCConstantStringInterface();
81 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000082 Ty = Context.getObjCObjectPointerType(Ty);
Fariborz Jahanian8a437762010-04-23 23:19:04 +000083 } else if (getLangOptions().NoConstantCFStrings) {
Fariborz Jahanian4c733072010-10-19 17:19:29 +000084 IdentifierInfo *NSIdent=0;
85 std::string StringClass(getLangOptions().ObjCConstantStringClass);
86
87 if (StringClass.empty())
88 NSIdent = &Context.Idents.get("NSConstantString");
89 else
90 NSIdent = &Context.Idents.get(StringClass);
91
Fariborz Jahanian8a437762010-04-23 23:19:04 +000092 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
93 LookupOrdinaryName);
94 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
95 Context.setObjCConstantStringInterface(StrIF);
96 Ty = Context.getObjCConstantStringInterface();
97 Ty = Context.getObjCObjectPointerType(Ty);
98 } else {
99 // If there is no NSConstantString interface defined then treat this
100 // as error and recover from it.
101 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
102 << S->getSourceRange();
103 Ty = Context.getObjCIdType();
104 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000105 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000106 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +0000107 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
108 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000109 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
110 Context.setObjCConstantStringInterface(StrIF);
111 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000112 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000113 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000114 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000115 // strings as untyped objects and let the runtime figure it out later.
116 Ty = Context.getObjCIdType();
117 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Chris Lattnerf4b136f2009-02-18 06:13:04 +0000120 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +0000121}
122
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000123ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000124 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000125 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000126 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000127 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000128 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000129 StrTy = Context.DependentTy;
130 else {
Fariborz Jahanian6c916152011-06-16 22:34:44 +0000131 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
132 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000133 if (RequireCompleteType(AtLoc, EncodedType,
134 PDiag(diag::err_incomplete_type_objc_at_encode)
135 << EncodedTypeInfo->getTypeLoc().getSourceRange()))
136 return ExprError();
137
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000138 std::string Str;
139 Context.getObjCEncodingForType(EncodedType, Str);
140
141 // The type of @encode is the same as the type of the corresponding string,
142 // which is an array type.
143 StrTy = Context.CharTy;
144 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000145 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000146 StrTy.addConst();
147 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
148 ArrayType::Normal, 0);
149 }
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Douglas Gregor81d34662010-04-20 15:39:42 +0000151 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000152}
153
John McCallf312b1e2010-08-26 23:41:50 +0000154ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
155 SourceLocation EncodeLoc,
156 SourceLocation LParenLoc,
157 ParsedType ty,
158 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000159 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000160 TypeSourceInfo *TInfo;
161 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
162 if (!TInfo)
163 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
164 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000165
Douglas Gregor81d34662010-04-20 15:39:42 +0000166 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000167}
168
John McCallf312b1e2010-08-26 23:41:50 +0000169ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
170 SourceLocation AtLoc,
171 SourceLocation SelLoc,
172 SourceLocation LParenLoc,
173 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000174 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000175 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000176 if (!Method)
177 Method = LookupFactoryMethodInGlobalPool(Sel,
178 SourceRange(LParenLoc, RParenLoc));
179 if (!Method)
180 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
181
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000182 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
183 = ReferencedSelectors.find(Sel);
184 if (Pos == ReferencedSelectors.end())
185 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
186
John McCallf85e1932011-06-15 23:02:42 +0000187 // In ARC, forbid the user from using @selector for
188 // retain/release/autorelease/dealloc/retainCount.
189 if (getLangOptions().ObjCAutoRefCount) {
190 switch (Sel.getMethodFamily()) {
191 case OMF_retain:
192 case OMF_release:
193 case OMF_autorelease:
194 case OMF_retainCount:
195 case OMF_dealloc:
196 Diag(AtLoc, diag::err_arc_illegal_selector) <<
197 Sel << SourceRange(LParenLoc, RParenLoc);
198 break;
199
200 case OMF_None:
201 case OMF_alloc:
202 case OMF_copy:
203 case OMF_init:
204 case OMF_mutableCopy:
205 case OMF_new:
206 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +0000207 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +0000208 break;
209 }
210 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000211 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000212 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000213}
214
John McCallf312b1e2010-08-26 23:41:50 +0000215ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
216 SourceLocation AtLoc,
217 SourceLocation ProtoLoc,
218 SourceLocation LParenLoc,
219 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000220 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000221 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000222 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000223 return true;
224 }
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000226 QualType Ty = Context.getObjCProtoType();
227 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000228 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000229 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000230 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000231}
232
John McCall26743b22011-02-03 09:00:02 +0000233/// Try to capture an implicit reference to 'self'.
234ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
235 // Ignore block scopes: we can capture through them.
236 DeclContext *DC = CurContext;
237 while (true) {
238 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
239 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
240 else break;
241 }
242
243 // If we're not in an ObjC method, error out. Note that, unlike the
244 // C++ case, we don't require an instance method --- class methods
245 // still have a 'self', and we really do still need to capture it!
246 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
247 if (!method)
248 return 0;
249
250 ImplicitParamDecl *self = method->getSelfDecl();
251 assert(self && "capturing 'self' in non-definition?");
252
253 // Mark that we're closing on 'this' in all the block scopes, if applicable.
254 for (unsigned idx = FunctionScopes.size() - 1;
255 isa<BlockScopeInfo>(FunctionScopes[idx]);
John McCall6b5a61b2011-02-07 10:33:21 +0000256 --idx) {
257 BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
258 unsigned &captureIndex = blockScope->CaptureMap[self];
259 if (captureIndex) break;
260
261 bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
262 blockScope->Captures.push_back(
263 BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
264 captureIndex = blockScope->Captures.size(); // +1
265 }
John McCall26743b22011-02-03 09:00:02 +0000266
267 return method;
268}
269
Douglas Gregor926df6c2011-06-11 01:09:30 +0000270QualType Sema::getMessageSendResultType(QualType ReceiverType,
271 ObjCMethodDecl *Method,
272 bool isClassMessage, bool isSuperMessage) {
273 assert(Method && "Must have a method");
274 if (!Method->hasRelatedResultType())
275 return Method->getSendResultType();
276
277 // If a method has a related return type:
278 // - if the method found is an instance method, but the message send
279 // was a class message send, T is the declared return type of the method
280 // found
281 if (Method->isInstanceMethod() && isClassMessage)
282 return Method->getSendResultType();
283
284 // - if the receiver is super, T is a pointer to the class of the
285 // enclosing method definition
286 if (isSuperMessage) {
287 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
288 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
289 return Context.getObjCObjectPointerType(
290 Context.getObjCInterfaceType(Class));
291 }
292
293 // - if the receiver is the name of a class U, T is a pointer to U
294 if (ReceiverType->getAs<ObjCInterfaceType>() ||
295 ReceiverType->isObjCQualifiedInterfaceType())
296 return Context.getObjCObjectPointerType(ReceiverType);
297 // - if the receiver is of type Class or qualified Class type,
298 // T is the declared return type of the method.
299 if (ReceiverType->isObjCClassType() ||
300 ReceiverType->isObjCQualifiedClassType())
301 return Method->getSendResultType();
302
303 // - if the receiver is id, qualified id, Class, or qualified Class, T
304 // is the receiver type, otherwise
305 // - T is the type of the receiver expression.
306 return ReceiverType;
307}
John McCall26743b22011-02-03 09:00:02 +0000308
Douglas Gregor926df6c2011-06-11 01:09:30 +0000309void Sema::EmitRelatedResultTypeNote(const Expr *E) {
310 E = E->IgnoreParenImpCasts();
311 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
312 if (!MsgSend)
313 return;
314
315 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
316 if (!Method)
317 return;
318
319 if (!Method->hasRelatedResultType())
320 return;
321
322 if (Context.hasSameUnqualifiedType(Method->getResultType()
323 .getNonReferenceType(),
324 MsgSend->getType()))
325 return;
326
327 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
328 << Method->isInstanceMethod() << Method->getSelector()
329 << MsgSend->getType();
330}
331
332bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
333 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000334 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000335 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000336 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000337 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000338 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000339 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000340 for (unsigned i = 0; i != NumArgs; i++) {
341 if (Args[i]->isTypeDependent())
342 continue;
343
John Wiegley429bb272011-04-08 18:41:53 +0000344 ExprResult Result = DefaultArgumentPromotion(Args[i]);
345 if (Result.isInvalid())
346 return true;
347 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000348 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000349
John McCallf85e1932011-06-15 23:02:42 +0000350 unsigned DiagID;
351 if (getLangOptions().ObjCAutoRefCount)
352 DiagID = diag::err_arc_method_not_found;
353 else
354 DiagID = isClassMessage ? diag::warn_class_method_not_found
355 : diag::warn_inst_method_not_found;
Chris Lattner077bf5e2008-11-24 03:33:13 +0000356 Diag(lbrac, DiagID)
357 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +0000358
359 // In debuggers, we want to use __unknown_anytype for these
360 // results so that clients can cast them.
361 if (getLangOptions().DebuggerSupport) {
362 ReturnType = Context.UnknownAnyTy;
363 } else {
364 ReturnType = Context.getObjCIdType();
365 }
John McCallf89e55a2010-11-18 06:31:45 +0000366 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000367 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000368 }
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Douglas Gregor926df6c2011-06-11 01:09:30 +0000370 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
371 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000372 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000374 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000375 // Method might have more arguments than selector indicates. This is due
376 // to addition of c-style arguments in method.
377 if (Method->param_size() > Sel.getNumArgs())
378 NumNamedArgs = Method->param_size();
379 // FIXME. This need be cleaned up.
380 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000381 Diag(lbrac, diag::err_typecheck_call_too_few_args)
382 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000383 return false;
384 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000385
Chris Lattner312531a2009-04-12 08:11:20 +0000386 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000387 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000388 // We can't do any type-checking on a type-dependent argument.
389 if (Args[i]->isTypeDependent())
390 continue;
391
Chris Lattner85a932e2008-01-04 22:32:30 +0000392 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000393
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000394 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000395 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000397 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
398 Param->getType(),
399 PDiag(diag::err_call_incomplete_argument)
400 << argExpr->getSourceRange()))
401 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000402
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000403 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
404 Param);
John McCall3fa5cae2010-10-26 07:05:15 +0000405 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000406 if (ArgE.isInvalid())
407 IsError = true;
408 else
409 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000410 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000411
412 // Promote additional arguments to variadic methods.
413 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000414 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
415 if (Args[i]->isTypeDependent())
416 continue;
417
John Wiegley429bb272011-04-08 18:41:53 +0000418 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
419 IsError |= Arg.isInvalid();
420 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000421 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000422 } else {
423 // Check for extra arguments to non-variadic methods.
424 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000425 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000426 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000427 << 2 /*method*/ << NumNamedArgs << NumArgs
428 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000429 << SourceRange(Args[NumNamedArgs]->getLocStart(),
430 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000431 }
432 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000433 // diagnose nonnull arguments.
434 for (specific_attr_iterator<NonNullAttr>
435 i = Method->specific_attr_begin<NonNullAttr>(),
436 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
437 CheckNonNullArguments(*i, Args, lbrac);
438 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000439
Douglas Gregor2725ca82010-04-21 19:57:20 +0000440 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000441 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000442}
443
John McCallf85e1932011-06-15 23:02:42 +0000444bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000445 // 'self' is objc 'self' in an objc method only.
Fariborz Jahanianb4602102011-03-28 16:23:34 +0000446 DeclContext *DC = CurContext;
447 while (isa<BlockDecl>(DC))
448 DC = DC->getParent();
449 if (DC && !isa<ObjCMethodDecl>(DC))
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000450 return false;
John McCallf85e1932011-06-15 23:02:42 +0000451 receiver = receiver->IgnoreParenLValueCasts();
452 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000453 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
454 return true;
455 return false;
456}
457
Steve Narofff1afaf62009-02-26 15:55:06 +0000458// Helper method for ActOnClassMethod/ActOnInstanceMethod.
459// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000460// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000461// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000462ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000463 ObjCInterfaceDecl *ClassDecl) {
464 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000465 // lookup in class and all superclasses
466 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000467 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000468 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000469
Steve Naroff5609ec02009-03-08 18:56:13 +0000470 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000471 if (!Method)
472 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Steve Naroff5609ec02009-03-08 18:56:13 +0000474 // Before we give up, check if the selector is an instance method.
475 // But only in the root. This matches gcc's behaviour and what the
476 // runtime expects.
477 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000478 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000479 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000480 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000481 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000482 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
483 }
Mike Stump1eb44332009-09-09 15:08:12 +0000484
Steve Naroff5609ec02009-03-08 18:56:13 +0000485 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000486 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000487 return Method;
488}
489
490ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
491 ObjCInterfaceDecl *ClassDecl) {
492 ObjCMethodDecl *Method = 0;
493 while (ClassDecl && !Method) {
494 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000495 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000496 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Steve Naroff5609ec02009-03-08 18:56:13 +0000498 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000499 if (!Method)
500 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000501 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000502 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000503 return Method;
504}
505
Fariborz Jahanian61478062011-03-09 20:18:06 +0000506/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
507/// list of a qualified objective pointer type.
508ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
509 const ObjCObjectPointerType *OPT,
510 bool Instance)
511{
512 ObjCMethodDecl *MD = 0;
513 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
514 E = OPT->qual_end(); I != E; ++I) {
515 ObjCProtocolDecl *PROTO = (*I);
516 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
517 return MD;
518 }
519 }
520 return 0;
521}
522
Chris Lattner7f816522010-04-11 07:45:24 +0000523/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
524/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000525ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000526HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000527 Expr *BaseExpr, SourceLocation OpLoc,
528 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000529 SourceLocation MemberLoc,
530 SourceLocation SuperLoc, QualType SuperType,
531 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000532 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
533 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000534
535 if (MemberName.getNameKind() != DeclarationName::Identifier) {
536 Diag(MemberLoc, diag::err_invalid_property_name)
537 << MemberName << QualType(OPT, 0);
538 return ExprError();
539 }
540
Chris Lattner7f816522010-04-11 07:45:24 +0000541 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
542
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000543 if (IFace->isForwardDecl()) {
544 Diag(MemberLoc, diag::err_property_not_found_forward_class)
545 << MemberName << QualType(OPT, 0);
546 Diag(IFace->getLocation(), diag::note_forward_class);
547 return ExprError();
548 }
Chris Lattner7f816522010-04-11 07:45:24 +0000549 // Search for a declared property first.
550 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
551 // Check whether we can reference this property.
552 if (DiagnoseUseOfDecl(PD, MemberLoc))
553 return ExprError();
554 QualType ResTy = PD->getType();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000555 ResTy = ResTy.getNonLValueExprType(Context);
Chris Lattner7f816522010-04-11 07:45:24 +0000556 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
557 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000558 if (Getter &&
559 (Getter->hasRelatedResultType()
560 || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
561 ResTy = getMessageSendResultType(QualType(OPT, 0), Getter, false,
562 Super);
563
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000564 if (Super)
565 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000566 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000567 MemberLoc,
568 SuperLoc, SuperType));
569 else
570 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000571 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000572 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000573 }
574 // Check protocols on qualified interfaces.
575 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
576 E = OPT->qual_end(); I != E; ++I)
577 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
578 // Check whether we can reference this property.
579 if (DiagnoseUseOfDecl(PD, MemberLoc))
580 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000581
582 QualType T = PD->getType();
583 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
584 T = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000585 if (Super)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000586 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000587 VK_LValue,
588 OK_ObjCProperty,
589 MemberLoc,
590 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000591 else
Douglas Gregor926df6c2011-06-11 01:09:30 +0000592 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000593 VK_LValue,
594 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000595 MemberLoc,
596 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000597 }
598 // If that failed, look for an "implicit" property by seeing if the nullary
599 // selector is implemented.
600
601 // FIXME: The logic for looking up nullary and unary selectors should be
602 // shared with the code in ActOnInstanceMessage.
603
604 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
605 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000606
607 // May be founf in property's qualified list.
608 if (!Getter)
609 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000610
611 // If this reference is in an @implementation, check for 'private' methods.
612 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000613 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000614
615 // Look through local category implementations associated with the class.
616 if (!Getter)
617 Getter = IFace->getCategoryInstanceMethod(Sel);
618 if (Getter) {
619 // Check if we can reference this property.
620 if (DiagnoseUseOfDecl(Getter, MemberLoc))
621 return ExprError();
622 }
623 // If we found a getter then this may be a valid dot-reference, we
624 // will look for the matching setter, in case it is needed.
625 Selector SetterSel =
626 SelectorTable::constructSetterName(PP.getIdentifierTable(),
627 PP.getSelectorTable(), Member);
628 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000629
630 // May be founf in property's qualified list.
631 if (!Setter)
632 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
633
Chris Lattner7f816522010-04-11 07:45:24 +0000634 if (!Setter) {
635 // If this reference is in an @implementation, also check for 'private'
636 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000637 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000638 }
639 // Look through local category implementations associated with the class.
640 if (!Setter)
641 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000642
Chris Lattner7f816522010-04-11 07:45:24 +0000643 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
644 return ExprError();
645
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000646 if (Getter || Setter) {
647 QualType PType;
648 if (Getter)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000649 PType = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000650 else {
651 ParmVarDecl *ArgDecl = *Setter->param_begin();
652 PType = ArgDecl->getType();
653 }
654
John McCall09431682010-11-18 19:01:18 +0000655 ExprValueKind VK = VK_LValue;
656 ExprObjectKind OK = OK_ObjCProperty;
657 if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
658 PType->isVoidType())
659 VK = VK_RValue, OK = OK_Ordinary;
660
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000661 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000662 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
663 PType, VK, OK,
664 MemberLoc,
665 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000666 else
John McCall12f78a62010-12-02 01:19:52 +0000667 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
668 PType, VK, OK,
669 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000670
Chris Lattner7f816522010-04-11 07:45:24 +0000671 }
672
673 // Attempt to correct for typos in property names.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000674 TypoCorrection Corrected = CorrectTypo(
675 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
676 NULL, IFace, false, CTC_NoKeywords, OPT);
677 if (ObjCPropertyDecl *Property =
678 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>()) {
679 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +0000680 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000681 << MemberName << QualType(OPT, 0) << TypoResult
682 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000683 Diag(Property->getLocation(), diag::note_previous_decl)
684 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000685 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
686 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000687 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000688 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000689 ObjCInterfaceDecl *ClassDeclared;
690 if (ObjCIvarDecl *Ivar =
691 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
692 QualType T = Ivar->getType();
693 if (const ObjCObjectPointerType * OBJPT =
694 T->getAsObjCInterfacePointerType()) {
695 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
696 if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
697 if (IFace->isForwardDecl()) {
698 Diag(MemberLoc, diag::err_property_not_as_forward_class)
Fariborz Jahanian2a96bf52011-02-17 17:30:05 +0000699 << MemberName << IFace;
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000700 Diag(IFace->getLocation(), diag::note_forward_class);
701 return ExprError();
702 }
703 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000704 Diag(MemberLoc,
705 diag::err_ivar_access_using_property_syntax_suggest)
706 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
707 << FixItHint::CreateReplacement(OpLoc, "->");
708 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000709 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000710
Chris Lattner7f816522010-04-11 07:45:24 +0000711 Diag(MemberLoc, diag::err_property_not_found)
712 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000713 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000714 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000715 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000716 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000717}
718
719
720
John McCall60d7b3a2010-08-24 06:29:42 +0000721ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000722ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
723 IdentifierInfo &propertyName,
724 SourceLocation receiverNameLoc,
725 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000726
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000727 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000728 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
729 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000730
731 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000732 if (IFace == 0) {
733 // If the "receiver" is 'super' in a method, handle it as an expression-like
734 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000735 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000736 IsSuper = true;
737
John McCall26743b22011-02-03 09:00:02 +0000738 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000739 if (CurMethod->isInstanceMethod()) {
740 QualType T =
741 Context.getObjCInterfaceType(CurMethod->getClassInterface());
742 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000743
744 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000745 /*BaseExpr*/0,
746 SourceLocation()/*OpLoc*/,
747 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000748 propertyNameLoc,
749 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000750 }
Mike Stump1eb44332009-09-09 15:08:12 +0000751
Chris Lattnereb483eb2010-04-11 08:28:14 +0000752 // Otherwise, if this is a class method, try dispatching to our
753 // superclass.
754 IFace = CurMethod->getClassInterface()->getSuperClass();
755 }
John McCall26743b22011-02-03 09:00:02 +0000756 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000757
758 if (IFace == 0) {
759 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
760 return ExprError();
761 }
762 }
763
764 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000765 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000766 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000767
768 // If this reference is in an @implementation, check for 'private' methods.
769 if (!Getter)
770 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
771 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000772 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000773 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000774
775 if (Getter) {
776 // FIXME: refactor/share with ActOnMemberReference().
777 // Check if we can reference this property.
778 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
779 return ExprError();
780 }
Mike Stump1eb44332009-09-09 15:08:12 +0000781
Steve Naroff61f72cb2009-03-09 21:12:44 +0000782 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000783 Selector SetterSel =
784 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000785 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000787 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000788 if (!Setter) {
789 // If this reference is in an @implementation, also check for 'private'
790 // methods.
791 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
792 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000793 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000794 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000795 }
796 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000797 if (!Setter)
798 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000799
800 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
801 return ExprError();
802
803 if (Getter || Setter) {
804 QualType PType;
805
John McCall09431682010-11-18 19:01:18 +0000806 ExprValueKind VK = VK_LValue;
807 if (Getter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000808 PType = getMessageSendResultType(Context.getObjCInterfaceType(IFace),
809 Getter, true,
810 receiverNamePtr->isStr("super"));
John McCall09431682010-11-18 19:01:18 +0000811 if (!getLangOptions().CPlusPlus &&
812 !PType.hasQualifiers() && PType->isVoidType())
813 VK = VK_RValue;
814 } else {
Steve Naroff61f72cb2009-03-09 21:12:44 +0000815 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
816 E = Setter->param_end(); PI != E; ++PI)
817 PType = (*PI)->getType();
John McCall09431682010-11-18 19:01:18 +0000818 VK = VK_LValue;
Steve Naroff61f72cb2009-03-09 21:12:44 +0000819 }
John McCall09431682010-11-18 19:01:18 +0000820
821 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
822
Douglas Gregor926df6c2011-06-11 01:09:30 +0000823 if (IsSuper)
824 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
825 PType, VK, OK,
826 propertyNameLoc,
827 receiverNameLoc,
828 Context.getObjCInterfaceType(IFace)));
829
John McCall12f78a62010-12-02 01:19:52 +0000830 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
831 PType, VK, OK,
832 propertyNameLoc,
833 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000834 }
835 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
836 << &propertyName << Context.getObjCInterfaceType(IFace));
837}
838
Douglas Gregor47bd5432010-04-14 02:46:37 +0000839Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000840 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000841 SourceLocation NameLoc,
842 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000843 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000844 ParsedType &ReceiverType) {
845 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000846
Douglas Gregor47bd5432010-04-14 02:46:37 +0000847 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000848 // messaging super. If the identifier is "super" and there is a
849 // trailing dot, it's an instance message.
850 if (IsSuper && S->isInObjcMethodScope())
851 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000852
853 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
854 LookupName(Result, S);
855
856 switch (Result.getResultKind()) {
857 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000858 // Normal name lookup didn't find anything. If we're in an
859 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000860 // FIXME: This is a hack. Ivar lookup should be part of normal
861 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000862 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
863 ObjCInterfaceDecl *ClassDeclared;
864 if (Method->getClassInterface()->lookupInstanceVariable(Name,
865 ClassDeclared))
866 return ObjCInstanceMessage;
867 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000868
Douglas Gregor47bd5432010-04-14 02:46:37 +0000869 // Break out; we'll perform typo correction below.
870 break;
871
872 case LookupResult::NotFoundInCurrentInstantiation:
873 case LookupResult::FoundOverloaded:
874 case LookupResult::FoundUnresolvedValue:
875 case LookupResult::Ambiguous:
876 Result.suppressDiagnostics();
877 return ObjCInstanceMessage;
878
879 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000880 // If the identifier is a class or not, and there is a trailing dot,
881 // it's an instance message.
882 if (HasTrailingDot)
883 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000884 // We found something. If it's a type, then we have a class
885 // message. Otherwise, it's an instance message.
886 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000887 QualType T;
888 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
889 T = Context.getObjCInterfaceType(Class);
890 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
891 T = Context.getTypeDeclType(Type);
892 else
893 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000894
Douglas Gregor1569f952010-04-21 20:38:13 +0000895 // We have a class message, and T is the type we're
896 // messaging. Build source-location information for it.
897 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000898 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000899 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000900 }
901 }
902
Douglas Gregoraaf87162010-04-14 20:04:41 +0000903 // Determine our typo-correction context.
904 CorrectTypoContext CTC = CTC_Expression;
905 if (ObjCMethodDecl *Method = getCurMethodDecl())
906 if (Method->getClassInterface() &&
907 Method->getClassInterface()->getSuperClass())
908 CTC = CTC_ObjCMessageReceiver;
909
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000910 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
911 Result.getLookupKind(), S, NULL,
912 NULL, false, CTC)) {
913 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000914 // If we found a declaration, correct when it refers to an Objective-C
915 // class.
Douglas Gregor1569f952010-04-21 20:38:13 +0000916 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000917 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000918 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000919 << FixItHint::CreateReplacement(SourceRange(NameLoc),
920 ND->getNameAsString());
921 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000922 << Corrected.getCorrection();
Douglas Gregor47bd5432010-04-14 02:46:37 +0000923
Douglas Gregor1569f952010-04-21 20:38:13 +0000924 QualType T = Context.getObjCInterfaceType(Class);
925 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000926 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000927 return ObjCClassMessage;
928 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000929 } else if (Corrected.isKeyword() &&
930 Corrected.getCorrectionAsIdentifierInfo()->isStr("super")) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000931 // If we've found the keyword "super", this is a send to super.
932 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000933 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000934 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000935 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000936 }
937 }
938
939 // Fall back: let the parser try to parse it as an instance message.
940 return ObjCInstanceMessage;
941}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000942
John McCall60d7b3a2010-08-24 06:29:42 +0000943ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000944 SourceLocation SuperLoc,
945 Selector Sel,
946 SourceLocation LBracLoc,
947 SourceLocation SelectorLoc,
948 SourceLocation RBracLoc,
949 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000950 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000951 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000952 if (!Method) {
953 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
954 return ExprError();
955 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000956
Douglas Gregorf95861a2010-04-21 20:01:04 +0000957 ObjCInterfaceDecl *Class = Method->getClassInterface();
958 if (!Class) {
959 Diag(SuperLoc, diag::error_no_super_class_message)
960 << Method->getDeclName();
961 return ExprError();
962 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000963
Douglas Gregorf95861a2010-04-21 20:01:04 +0000964 ObjCInterfaceDecl *Super = Class->getSuperClass();
965 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000966 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000967 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
968 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000969 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000970 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000971
Douglas Gregorf95861a2010-04-21 20:01:04 +0000972 // We are in a method whose class has a superclass, so 'super'
973 // is acting as a keyword.
974 if (Method->isInstanceMethod()) {
975 // Since we are in an instance method, this is an instance
976 // message to the superclass instance.
977 QualType SuperTy = Context.getObjCInterfaceType(Super);
978 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +0000979 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000980 Sel, /*Method=*/0,
981 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000982 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000983
984 // Since we are in a class method, this is a class message to
985 // the superclass.
986 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
987 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000988 SuperLoc, Sel, /*Method=*/0,
989 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000990}
991
992/// \brief Build an Objective-C class message expression.
993///
994/// This routine takes care of both normal class messages and
995/// class messages to the superclass.
996///
997/// \param ReceiverTypeInfo Type source information that describes the
998/// receiver of this message. This may be NULL, in which case we are
999/// sending to the superclass and \p SuperLoc must be a valid source
1000/// location.
1001
1002/// \param ReceiverType The type of the object receiving the
1003/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1004/// type as that refers to. For a superclass send, this is the type of
1005/// the superclass.
1006///
1007/// \param SuperLoc The location of the "super" keyword in a
1008/// superclass message.
1009///
1010/// \param Sel The selector to which the message is being sent.
1011///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001012/// \param Method The method that this class message is invoking, if
1013/// already known.
1014///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001015/// \param LBracLoc The location of the opening square bracket ']'.
1016///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001017/// \param RBrac The location of the closing square bracket ']'.
1018///
1019/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001020ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001021 QualType ReceiverType,
1022 SourceLocation SuperLoc,
1023 Selector Sel,
1024 ObjCMethodDecl *Method,
1025 SourceLocation LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001026 SourceLocation SelectorLoc,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001027 SourceLocation RBracLoc,
1028 MultiExprArg ArgsIn) {
1029 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001030 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001031 if (LBracLoc.isInvalid()) {
1032 Diag(Loc, diag::err_missing_open_square_message_send)
1033 << FixItHint::CreateInsertion(Loc, "[");
1034 LBracLoc = Loc;
1035 }
1036
Douglas Gregor92e986e2010-04-22 16:44:27 +00001037 if (ReceiverType->isDependentType()) {
1038 // If the receiver type is dependent, we can't type-check anything
1039 // at this point. Build a dependent expression.
1040 unsigned NumArgs = ArgsIn.size();
1041 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1042 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001043 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1044 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001045 Sel, SelectorLoc, /*Method=*/0,
Douglas Gregor92e986e2010-04-22 16:44:27 +00001046 Args, NumArgs, RBracLoc));
1047 }
Chris Lattner15faee12010-04-12 05:38:43 +00001048
Douglas Gregor2725ca82010-04-21 19:57:20 +00001049 // Find the class to which we are sending this message.
1050 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001051 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1052 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001053 Diag(Loc, diag::err_invalid_receiver_class_message)
1054 << ReceiverType;
1055 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001056 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001057 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian02b0d652011-03-08 19:12:46 +00001058 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001059 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001060 if (!Method) {
1061 if (Class->isForwardDecl()) {
John McCallf85e1932011-06-15 23:02:42 +00001062 if (getLangOptions().ObjCAutoRefCount) {
1063 Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
1064 } else {
1065 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1066 }
1067
Douglas Gregorf49bb082010-04-22 17:01:48 +00001068 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001069 Method = LookupFactoryMethodInGlobalPool(Sel,
1070 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001071 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001072 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1073 << Method->getDeclName();
1074 }
1075 if (!Method)
1076 Method = Class->lookupClassMethod(Sel);
1077
1078 // If we have an implementation in scope, check "private" methods.
1079 if (!Method)
1080 Method = LookupPrivateClassMethod(Sel, Class);
1081
1082 if (Method && DiagnoseUseOfDecl(Method, Loc))
1083 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001084 }
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Douglas Gregor2725ca82010-04-21 19:57:20 +00001086 // Check the argument types and determine the result type.
1087 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001088 ExprValueKind VK = VK_RValue;
1089
Douglas Gregor2725ca82010-04-21 19:57:20 +00001090 unsigned NumArgs = ArgsIn.size();
1091 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001092 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1093 SuperLoc.isValid(), LBracLoc, RBracLoc,
1094 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001095 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001096
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001097 if (Method && !Method->getResultType()->isVoidType() &&
1098 RequireCompleteType(LBracLoc, Method->getResultType(),
1099 diag::err_illegal_message_expr_incomplete_type))
1100 return ExprError();
1101
Douglas Gregor2725ca82010-04-21 19:57:20 +00001102 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001103 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001104 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001105 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001106 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001107 ReceiverType, Sel, SelectorLoc,
1108 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001109 else
John McCallf89e55a2010-11-18 06:31:45 +00001110 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001111 ReceiverTypeInfo, Sel, SelectorLoc,
1112 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001113 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001114}
1115
Douglas Gregor2725ca82010-04-21 19:57:20 +00001116// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001117// ArgExprs is optional - if it is present, the number of expressions
1118// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001119ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001120 ParsedType Receiver,
1121 Selector Sel,
1122 SourceLocation LBracLoc,
1123 SourceLocation SelectorLoc,
1124 SourceLocation RBracLoc,
1125 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001126 TypeSourceInfo *ReceiverTypeInfo;
1127 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1128 if (ReceiverType.isNull())
1129 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001130
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Douglas Gregor2725ca82010-04-21 19:57:20 +00001132 if (!ReceiverTypeInfo)
1133 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1134
1135 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001136 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001137 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001138}
1139
1140/// \brief Build an Objective-C instance message expression.
1141///
1142/// This routine takes care of both normal instance messages and
1143/// instance messages to the superclass instance.
1144///
1145/// \param Receiver The expression that computes the object that will
1146/// receive this message. This may be empty, in which case we are
1147/// sending to the superclass instance and \p SuperLoc must be a valid
1148/// source location.
1149///
1150/// \param ReceiverType The (static) type of the object receiving the
1151/// message. When a \p Receiver expression is provided, this is the
1152/// same type as that expression. For a superclass instance send, this
1153/// is a pointer to the type of the superclass.
1154///
1155/// \param SuperLoc The location of the "super" keyword in a
1156/// superclass instance message.
1157///
1158/// \param Sel The selector to which the message is being sent.
1159///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001160/// \param Method The method that this instance message is invoking, if
1161/// already known.
1162///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001163/// \param LBracLoc The location of the opening square bracket ']'.
1164///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001165/// \param RBrac The location of the closing square bracket ']'.
1166///
1167/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001168ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001169 QualType ReceiverType,
1170 SourceLocation SuperLoc,
1171 Selector Sel,
1172 ObjCMethodDecl *Method,
1173 SourceLocation LBracLoc,
1174 SourceLocation SelectorLoc,
1175 SourceLocation RBracLoc,
1176 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001177 // The location of the receiver.
1178 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1179
1180 if (LBracLoc.isInvalid()) {
1181 Diag(Loc, diag::err_missing_open_square_message_send)
1182 << FixItHint::CreateInsertion(Loc, "[");
1183 LBracLoc = Loc;
1184 }
1185
Douglas Gregor2725ca82010-04-21 19:57:20 +00001186 // If we have a receiver expression, perform appropriate promotions
1187 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001188 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001189 if (Receiver->isTypeDependent()) {
1190 // If the receiver is type-dependent, we can't type-check anything
1191 // at this point. Build a dependent expression.
1192 unsigned NumArgs = ArgsIn.size();
1193 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1194 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1195 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001196 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001197 SelectorLoc, /*Method=*/0,
1198 Args, NumArgs, RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001199 }
1200
Douglas Gregor2725ca82010-04-21 19:57:20 +00001201 // If necessary, apply function/array conversion to the receiver.
1202 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001203 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1204 if (Result.isInvalid())
1205 return ExprError();
1206 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001207 ReceiverType = Receiver->getType();
1208 }
1209
Douglas Gregorf49bb082010-04-22 17:01:48 +00001210 if (!Method) {
1211 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001212 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001213 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001214 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1215 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001216 SourceRange(LBracLoc, RBracLoc),
1217 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001218 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001219 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001220 SourceRange(LBracLoc, RBracLoc),
1221 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001222 } else if (ReceiverType->isObjCClassType() ||
1223 ReceiverType->isObjCQualifiedClassType()) {
1224 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001225 // We allow sending a message to a qualified Class ("Class<foo>"), which
1226 // is ok as long as one of the protocols implements the selector (if not, warn).
1227 if (const ObjCObjectPointerType *QClassTy
1228 = ReceiverType->getAsObjCQualifiedClassType()) {
1229 // Search protocols for class methods.
1230 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1231 if (!Method) {
1232 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1233 // warn if instance method found for a Class message.
1234 if (Method) {
1235 Diag(Loc, diag::warn_instance_method_on_class_found)
1236 << Method->getSelector() << Sel;
1237 Diag(Method->getLocation(), diag::note_method_declared_at);
1238 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001239 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001240 } else {
1241 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1242 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1243 // First check the public methods in the class interface.
1244 Method = ClassDecl->lookupClassMethod(Sel);
1245
1246 if (!Method)
1247 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1248 }
1249 if (Method && DiagnoseUseOfDecl(Method, Loc))
1250 return ExprError();
1251 }
1252 if (!Method) {
1253 // If not messaging 'self', look for any factory method named 'Sel'.
1254 if (!Receiver || !isSelfExpr(Receiver)) {
1255 Method = LookupFactoryMethodInGlobalPool(Sel,
1256 SourceRange(LBracLoc, RBracLoc),
1257 true);
1258 if (!Method) {
1259 // If no class (factory) method was found, check if an _instance_
1260 // method of the same name exists in the root class only.
1261 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001262 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001263 true);
1264 if (Method)
1265 if (const ObjCInterfaceDecl *ID =
1266 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1267 if (ID->getSuperClass())
1268 Diag(Loc, diag::warn_root_inst_method_not_found)
1269 << Sel << SourceRange(LBracLoc, RBracLoc);
1270 }
1271 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001272 }
1273 }
1274 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001275 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001276 ObjCInterfaceDecl* ClassDecl = 0;
1277
1278 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1279 // long as one of the protocols implements the selector (if not, warn).
1280 if (const ObjCObjectPointerType *QIdTy
1281 = ReceiverType->getAsObjCQualifiedIdType()) {
1282 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001283 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1284 if (!Method)
1285 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001286 } else if (const ObjCObjectPointerType *OCIType
1287 = ReceiverType->getAsObjCInterfacePointerType()) {
1288 // We allow sending a message to a pointer to an interface (an object).
1289 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001290
1291 if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCount) {
1292 Diag(Loc, diag::err_arc_receiver_forward_instance)
1293 << OCIType->getPointeeType()
1294 << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperLoc));
1295 return ExprError();
1296 }
1297
Douglas Gregorf49bb082010-04-22 17:01:48 +00001298 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1299 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +00001300 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001301 Method = ClassDecl->lookupInstanceMethod(Sel);
1302
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001303 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001304 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001305 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1306
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001307 const ObjCInterfaceDecl *forwardClass = 0;
Douglas Gregorf49bb082010-04-22 17:01:48 +00001308 if (!Method) {
1309 // If we have implementations in scope, check "private" methods.
1310 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1311
John McCallf85e1932011-06-15 23:02:42 +00001312 if (!Method && getLangOptions().ObjCAutoRefCount) {
1313 Diag(Loc, diag::err_arc_may_not_respond)
1314 << OCIType->getPointeeType() << Sel;
1315 return ExprError();
1316 }
1317
Douglas Gregorf49bb082010-04-22 17:01:48 +00001318 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1319 // If we still haven't found a method, look in the global pool. This
1320 // behavior isn't very desirable, however we need it for GCC
1321 // compatibility. FIXME: should we deviate??
1322 if (OCIType->qual_empty()) {
1323 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001324 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001325 if (OCIType->getInterfaceDecl()->isForwardDecl())
1326 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001327 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001328 Diag(Loc, diag::warn_maynot_respond)
1329 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1330 }
1331 }
1332 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001333 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001334 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001335 } else if (!getLangOptions().ObjCAutoRefCount &&
1336 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001337 (ReceiverType->isPointerType() ||
1338 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001339 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001340 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001341 Diag(Loc, diag::warn_bad_receiver_type)
1342 << ReceiverType
1343 << Receiver->getSourceRange();
1344 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001345 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1346 CK_BitCast).take();
John McCall404cd162010-11-13 01:35:44 +00001347 else {
1348 // TODO: specialized warning on null receivers?
1349 bool IsNull = Receiver->isNullPointerConstant(Context,
1350 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001351 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1352 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001353 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001354 ReceiverType = Receiver->getType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00001355 }
John Wiegley429bb272011-04-08 18:41:53 +00001356 else {
1357 ExprResult ReceiverRes;
1358 if (getLangOptions().CPlusPlus)
1359 ReceiverRes = PerformContextuallyConvertToObjCId(Receiver);
1360 if (ReceiverRes.isUsable()) {
1361 Receiver = ReceiverRes.take();
1362 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
1363 Receiver = ICE->getSubExpr();
1364 ReceiverType = Receiver->getType();
1365 }
1366 return BuildInstanceMessage(Receiver,
1367 ReceiverType,
1368 SuperLoc,
1369 Sel,
1370 Method,
1371 LBracLoc,
1372 SelectorLoc,
1373 RBracLoc,
1374 move(ArgsIn));
1375 } else {
1376 // Reject other random receiver types (e.g. structs).
1377 Diag(Loc, diag::err_bad_receiver_type)
1378 << ReceiverType << Receiver->getSourceRange();
1379 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001380 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001381 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001382 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001383 }
Mike Stump1eb44332009-09-09 15:08:12 +00001384
Douglas Gregor2725ca82010-04-21 19:57:20 +00001385 // Check the message arguments.
1386 unsigned NumArgs = ArgsIn.size();
1387 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1388 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001389 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001390 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1391 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001392 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1393 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001394 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001395 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001396
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001397 if (Method && !Method->getResultType()->isVoidType() &&
1398 RequireCompleteType(LBracLoc, Method->getResultType(),
1399 diag::err_illegal_message_expr_incomplete_type))
1400 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001401
John McCallf85e1932011-06-15 23:02:42 +00001402 // In ARC, forbid the user from sending messages to
1403 // retain/release/autorelease/dealloc/retainCount explicitly.
1404 if (getLangOptions().ObjCAutoRefCount) {
1405 ObjCMethodFamily family =
1406 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1407 switch (family) {
1408 case OMF_init:
1409 if (Method)
1410 checkInitMethod(Method, ReceiverType);
1411
1412 case OMF_None:
1413 case OMF_alloc:
1414 case OMF_copy:
1415 case OMF_mutableCopy:
1416 case OMF_new:
1417 case OMF_self:
1418 break;
1419
1420 case OMF_dealloc:
1421 case OMF_retain:
1422 case OMF_release:
1423 case OMF_autorelease:
1424 case OMF_retainCount:
1425 Diag(Loc, diag::err_arc_illegal_explicit_message)
1426 << Sel << SelectorLoc;
1427 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001428
1429 case OMF_performSelector:
1430 if (Method && NumArgs >= 1) {
1431 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1432 Selector ArgSel = SelExp->getSelector();
1433 ObjCMethodDecl *SelMethod =
1434 LookupInstanceMethodInGlobalPool(ArgSel,
1435 SelExp->getSourceRange());
1436 if (!SelMethod)
1437 SelMethod =
1438 LookupFactoryMethodInGlobalPool(ArgSel,
1439 SelExp->getSourceRange());
1440 if (SelMethod) {
1441 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1442 switch (SelFamily) {
1443 case OMF_alloc:
1444 case OMF_copy:
1445 case OMF_mutableCopy:
1446 case OMF_new:
1447 case OMF_self:
1448 case OMF_init:
1449 // Issue error, unless ns_returns_not_retained.
1450 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1451 // selector names a +1 method
1452 Diag(SelectorLoc,
1453 diag::err_arc_perform_selector_retains);
1454 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1455 }
1456 break;
1457 default:
1458 // +0 call. OK. unless ns_returns_retained.
1459 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1460 // selector names a +1 method
1461 Diag(SelectorLoc,
1462 diag::err_arc_perform_selector_retains);
1463 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1464 }
1465 break;
1466 }
1467 }
1468 } else {
1469 // error (may leak).
1470 Diag(SelectorLoc, diag::warn_arc_perform_selector_leaks);
1471 Diag(Args[0]->getExprLoc(), diag::note_used_here);
1472 }
1473 }
1474 break;
John McCallf85e1932011-06-15 23:02:42 +00001475 }
1476 }
1477
Douglas Gregor2725ca82010-04-21 19:57:20 +00001478 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001479 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001480 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001481 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001482 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001483 ReceiverType, Sel, SelectorLoc, Method,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001484 Args, NumArgs, RBracLoc);
1485 else
John McCallf89e55a2010-11-18 06:31:45 +00001486 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001487 Receiver, Sel, SelectorLoc, Method,
1488 Args, NumArgs, RBracLoc);
John McCallf85e1932011-06-15 23:02:42 +00001489
1490 if (getLangOptions().ObjCAutoRefCount) {
1491 // In ARC, annotate delegate init calls.
1492 if (Result->getMethodFamily() == OMF_init &&
1493 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
1494 // Only consider init calls *directly* in init implementations,
1495 // not within blocks.
1496 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1497 if (method && method->getMethodFamily() == OMF_init) {
1498 // The implicit assignment to self means we also don't want to
1499 // consume the result.
1500 Result->setDelegateInitCall(true);
1501 return Owned(Result);
1502 }
1503 }
1504
1505 // In ARC, check for message sends which are likely to introduce
1506 // retain cycles.
1507 checkRetainCycles(Result);
1508 }
1509
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001510 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001511}
1512
1513// ActOnInstanceMessage - used for both unary and keyword messages.
1514// ArgExprs is optional - if it is present, the number of expressions
1515// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001516ExprResult Sema::ActOnInstanceMessage(Scope *S,
1517 Expr *Receiver,
1518 Selector Sel,
1519 SourceLocation LBracLoc,
1520 SourceLocation SelectorLoc,
1521 SourceLocation RBracLoc,
1522 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001523 if (!Receiver)
1524 return ExprError();
1525
John McCall9ae2f072010-08-23 23:25:46 +00001526 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001527 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001528 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001529}
Chris Lattnereca7be62008-04-07 05:30:13 +00001530
John McCallf85e1932011-06-15 23:02:42 +00001531enum ARCConversionTypeClass {
1532 ACTC_none,
1533 ACTC_retainable,
1534 ACTC_indirectRetainable
1535};
1536static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
1537 ARCConversionTypeClass ACTC = ACTC_retainable;
1538
1539 // Ignore an outermost reference type.
1540 if (const ReferenceType *ref = type->getAs<ReferenceType>())
1541 type = ref->getPointeeType();
1542
1543 // Drill through pointers and arrays recursively.
1544 while (true) {
1545 if (const PointerType *ptr = type->getAs<PointerType>()) {
1546 type = ptr->getPointeeType();
1547 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1548 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1549 } else {
1550 break;
1551 }
1552 ACTC = ACTC_indirectRetainable;
1553 }
1554
1555 if (!type->isObjCRetainableType()) return ACTC_none;
1556 return ACTC;
1557}
1558
1559namespace {
1560 /// Return true if the given expression can be reasonably converted
1561 /// between a retainable pointer type and a C pointer type.
1562 struct ARCCastChecker : StmtVisitor<ARCCastChecker, bool> {
1563 ASTContext &Context;
1564 ARCCastChecker(ASTContext &Context) : Context(Context) {}
1565 bool VisitStmt(Stmt *s) {
1566 return false;
1567 }
1568 bool VisitExpr(Expr *e) {
1569 return e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
1570 }
1571
1572 bool VisitParenExpr(ParenExpr *e) {
1573 return Visit(e->getSubExpr());
1574 }
1575 bool VisitCastExpr(CastExpr *e) {
1576 switch (e->getCastKind()) {
1577 case CK_NullToPointer:
1578 return true;
1579 case CK_NoOp:
1580 case CK_LValueToRValue:
1581 case CK_BitCast:
1582 case CK_AnyPointerToObjCPointerCast:
1583 case CK_AnyPointerToBlockPointerCast:
1584 return Visit(e->getSubExpr());
1585 default:
1586 return false;
1587 }
1588 }
1589 bool VisitUnaryExtension(UnaryOperator *e) {
1590 return Visit(e->getSubExpr());
1591 }
1592 bool VisitBinComma(BinaryOperator *e) {
1593 return Visit(e->getRHS());
1594 }
1595 bool VisitConditionalOperator(ConditionalOperator *e) {
1596 // Conditional operators are okay if both sides are okay.
1597 return Visit(e->getTrueExpr()) && Visit(e->getFalseExpr());
1598 }
1599 bool VisitObjCStringLiteral(ObjCStringLiteral *e) {
1600 // Always white-list Objective-C string literals.
1601 return true;
1602 }
1603 bool VisitStmtExpr(StmtExpr *e) {
1604 return Visit(e->getSubStmt()->body_back());
1605 }
1606 bool VisitDeclRefExpr(DeclRefExpr *e) {
1607 // White-list references to global extern strings from system
1608 // headers.
1609 if (VarDecl *var = dyn_cast<VarDecl>(e->getDecl()))
1610 if (var->getStorageClass() == SC_Extern &&
1611 var->getType().isConstQualified() &&
1612 Context.getSourceManager().isInSystemHeader(var->getLocation()))
1613 return true;
1614 return false;
1615 }
1616 };
1617}
1618
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001619bool
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001620Sema::ValidObjCARCNoBridgeCastExpr(Expr *&Exp, QualType castType) {
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001621 Expr *NewExp = Exp->IgnoreParenCasts();
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001622
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001623 if (!isa<ObjCMessageExpr>(NewExp) && !isa<ObjCPropertyRefExpr>(NewExp)
1624 && !isa<CallExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001625 return false;
1626 ObjCMethodDecl *method = 0;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001627 bool MethodReturnsPlusOne = false;
1628
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001629 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(NewExp)) {
1630 method = PRE->getExplicitProperty()->getGetterMethodDecl();
1631 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001632 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001633 method = ME->getMethodDecl();
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001634 else {
1635 CallExpr *CE = cast<CallExpr>(NewExp);
1636 Decl *CallDecl = CE->getCalleeDecl();
1637 if (!CallDecl)
1638 return false;
1639 if (CallDecl->hasAttr<CFReturnsNotRetainedAttr>())
1640 return true;
1641 MethodReturnsPlusOne = CallDecl->hasAttr<CFReturnsRetainedAttr>();
1642 if (!MethodReturnsPlusOne) {
1643 if (NamedDecl *ND = dyn_cast<NamedDecl>(CallDecl))
1644 if (const IdentifierInfo *Id = ND->getIdentifier())
1645 if (Id->isStr("__builtin___CFStringMakeConstantString"))
1646 return true;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001647 }
1648 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001649
1650 if (!MethodReturnsPlusOne) {
1651 if (!method)
1652 return false;
1653 if (method->hasAttr<CFReturnsNotRetainedAttr>())
1654 return true;
1655 MethodReturnsPlusOne = method->hasAttr<CFReturnsRetainedAttr>();
1656 if (!MethodReturnsPlusOne) {
1657 ObjCMethodFamily family = method->getSelector().getMethodFamily();
1658 switch (family) {
1659 case OMF_alloc:
1660 case OMF_copy:
1661 case OMF_mutableCopy:
1662 case OMF_new:
1663 MethodReturnsPlusOne = true;
1664 break;
1665 default:
1666 break;
1667 }
1668 }
1669 }
1670
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001671 if (MethodReturnsPlusOne) {
1672 TypeSourceInfo *TSInfo =
1673 Context.getTrivialTypeSourceInfo(castType, SourceLocation());
1674 ExprResult ExpRes = BuildObjCBridgedCast(SourceLocation(), OBC_BridgeTransfer,
1675 SourceLocation(), TSInfo, Exp);
1676 Exp = ExpRes.take();
1677 }
1678 return true;
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001679}
1680
John McCallf85e1932011-06-15 23:02:42 +00001681void
1682Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001683 Expr *&castExpr, CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00001684 QualType castExprType = castExpr->getType();
1685
1686 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1687 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
1688 if (exprACTC == castACTC) return;
Fariborz Jahanian8295b7b2011-06-22 16:36:45 +00001689 if (exprACTC && castType->isIntegralType(Context)) return;
John McCallf85e1932011-06-15 23:02:42 +00001690
1691 // Allow casts between pointers to lifetime types (e.g., __strong id*)
1692 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1693 // must be explicit.
1694 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
1695 if (const PointerType *CastExprPtr = castExprType->getAs<PointerType>()) {
1696 QualType CastPointee = CastPtr->getPointeeType();
1697 QualType CastExprPointee = CastExprPtr->getPointeeType();
1698 if ((CCK != CCK_ImplicitConversion &&
1699 CastPointee->isObjCIndirectLifetimeType() &&
1700 CastExprPointee->isVoidType()) ||
1701 (CastPointee->isVoidType() &&
1702 CastExprPointee->isObjCIndirectLifetimeType()))
1703 return;
1704 }
1705 }
1706
1707 if (ARCCastChecker(Context).Visit(castExpr))
1708 return;
1709
1710 SourceLocation loc =
1711 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
1712
1713 if (makeUnavailableInSystemHeader(loc,
1714 "converts between Objective-C and C pointers in -fobjc-arc"))
1715 return;
1716
John McCall71c482c2011-06-17 06:50:50 +00001717 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00001718 switch (exprACTC) {
1719 case ACTC_none:
1720 srcKind = (castExprType->isPointerType() ? 1 : 0);
1721 break;
1722 case ACTC_retainable:
1723 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1724 break;
1725 case ACTC_indirectRetainable:
1726 srcKind = 4;
1727 break;
1728 }
1729
1730 if (CCK == CCK_CStyleCast) {
1731 // Check whether this could be fixed with a bridge cast.
1732 SourceLocation AfterLParen = PP.getLocForEndOfToken(castRange.getBegin());
1733 SourceLocation NoteLoc = AfterLParen.isValid()? AfterLParen : loc;
1734
1735 if (castType->isObjCARCBridgableType() &&
1736 castExprType->isCARCBridgableType()) {
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001737 // explicit unbridged casts are allowed if the source of the cast is a
1738 // message sent to an objc method (or property access)
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001739 if (ValidObjCARCNoBridgeCastExpr(castExpr, castType))
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001740 return;
John McCallf85e1932011-06-15 23:02:42 +00001741 Diag(loc, diag::err_arc_cast_requires_bridge)
1742 << 2
1743 << castExprType
1744 << (castType->isBlockPointerType()? 1 : 0)
1745 << castType
1746 << castRange
1747 << castExpr->getSourceRange();
1748 Diag(NoteLoc, diag::note_arc_bridge)
1749 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1750 Diag(NoteLoc, diag::note_arc_bridge_transfer)
1751 << castExprType
1752 << FixItHint::CreateInsertion(AfterLParen, "__bridge_transfer ");
1753
1754 return;
1755 }
1756
1757 if (castType->isCARCBridgableType() &&
1758 castExprType->isObjCARCBridgableType()){
1759 Diag(loc, diag::err_arc_cast_requires_bridge)
1760 << (castExprType->isBlockPointerType()? 1 : 0)
1761 << castExprType
1762 << 2
1763 << castType
1764 << castRange
1765 << castExpr->getSourceRange();
1766
1767 Diag(NoteLoc, diag::note_arc_bridge)
1768 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1769 Diag(NoteLoc, diag::note_arc_bridge_retained)
1770 << castType
1771 << FixItHint::CreateInsertion(AfterLParen, "__bridge_retained ");
1772 return;
1773 }
1774 }
1775
1776 Diag(loc, diag::err_arc_mismatched_cast)
1777 << (CCK != CCK_ImplicitConversion) << srcKind << castExprType << castType
1778 << castRange << castExpr->getSourceRange();
1779}
1780
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00001781bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
1782 QualType exprType) {
1783 QualType canCastType =
1784 Context.getCanonicalType(castType).getUnqualifiedType();
1785 QualType canExprType =
1786 Context.getCanonicalType(exprType).getUnqualifiedType();
1787 if (isa<ObjCObjectPointerType>(canCastType) &&
1788 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
1789 canExprType->isObjCObjectPointerType()) {
1790 if (const ObjCObjectPointerType *ObjT =
1791 canExprType->getAs<ObjCObjectPointerType>())
1792 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
1793 return false;
1794 }
1795 return true;
1796}
1797
John McCall7e5e5f42011-07-07 06:58:02 +00001798/// Look for an ObjCReclaimReturnedObject cast and destroy it.
1799static Expr *maybeUndoReclaimObject(Expr *e) {
1800 // For now, we just undo operands that are *immediately* reclaim
1801 // expressions, which prevents the vast majority of potential
1802 // problems here. To catch them all, we'd need to rebuild arbitrary
1803 // value-propagating subexpressions --- we can't reliably rebuild
1804 // in-place because of expression sharing.
1805 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
1806 if (ice->getCastKind() == CK_ObjCReclaimReturnedObject)
1807 return ice->getSubExpr();
1808
1809 return e;
1810}
1811
John McCallf85e1932011-06-15 23:02:42 +00001812ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
1813 ObjCBridgeCastKind Kind,
1814 SourceLocation BridgeKeywordLoc,
1815 TypeSourceInfo *TSInfo,
1816 Expr *SubExpr) {
1817 QualType T = TSInfo->getType();
1818 QualType FromType = SubExpr->getType();
1819
1820 bool MustConsume = false;
1821 if (T->isDependentType() || SubExpr->isTypeDependent()) {
1822 // Okay: we'll build a dependent expression type.
1823 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
1824 // Casting CF -> id
1825 switch (Kind) {
1826 case OBC_Bridge:
1827 break;
1828
1829 case OBC_BridgeRetained:
1830 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1831 << 2
1832 << FromType
1833 << (T->isBlockPointerType()? 1 : 0)
1834 << T
1835 << SubExpr->getSourceRange()
1836 << Kind;
1837 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1838 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
1839 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
1840 << FromType
1841 << FixItHint::CreateReplacement(BridgeKeywordLoc,
1842 "__bridge_transfer ");
1843
1844 Kind = OBC_Bridge;
1845 break;
1846
1847 case OBC_BridgeTransfer:
1848 // We must consume the Objective-C object produced by the cast.
1849 MustConsume = true;
1850 break;
1851 }
1852 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
1853 // Okay: id -> CF
1854 switch (Kind) {
1855 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00001856 // Reclaiming a value that's going to be __bridge-casted to CF
1857 // is very dangerous, so we don't do it.
1858 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00001859 break;
1860
1861 case OBC_BridgeRetained:
1862 // Produce the object before casting it.
1863 SubExpr = ImplicitCastExpr::Create(Context, FromType,
1864 CK_ObjCProduceObject,
1865 SubExpr, 0, VK_RValue);
1866 break;
1867
1868 case OBC_BridgeTransfer:
1869 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1870 << (FromType->isBlockPointerType()? 1 : 0)
1871 << FromType
1872 << 2
1873 << T
1874 << SubExpr->getSourceRange()
1875 << Kind;
1876
1877 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1878 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
1879 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
1880 << T
1881 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
1882
1883 Kind = OBC_Bridge;
1884 break;
1885 }
1886 } else {
1887 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
1888 << FromType << T << Kind
1889 << SubExpr->getSourceRange()
1890 << TSInfo->getTypeLoc().getSourceRange();
1891 return ExprError();
1892 }
1893
1894 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind,
1895 BridgeKeywordLoc,
1896 TSInfo, SubExpr);
1897
1898 if (MustConsume) {
1899 ExprNeedsCleanups = true;
1900 Result = ImplicitCastExpr::Create(Context, T, CK_ObjCConsumeObject, Result,
1901 0, VK_RValue);
1902 }
1903
1904 return Result;
1905}
1906
1907ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
1908 SourceLocation LParenLoc,
1909 ObjCBridgeCastKind Kind,
1910 SourceLocation BridgeKeywordLoc,
1911 ParsedType Type,
1912 SourceLocation RParenLoc,
1913 Expr *SubExpr) {
1914 TypeSourceInfo *TSInfo = 0;
1915 QualType T = GetTypeFromParser(Type, &TSInfo);
1916 if (!TSInfo)
1917 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
1918 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
1919 SubExpr);
1920}