blob: cb5c1e0d0cbe4e96176b1873b92c9d1c2789a361 [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"
Douglas Gregor2725ca82010-04-21 19:57:20 +000022#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000023#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000024#include "clang/Lex/Preprocessor.h"
25
Chris Lattner85a932e2008-01-04 22:32:30 +000026using namespace clang;
John McCall26743b22011-02-03 09:00:02 +000027using namespace sema;
Chris Lattner85a932e2008-01-04 22:32:30 +000028
John McCallf312b1e2010-08-26 23:41:50 +000029ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
30 Expr **strings,
31 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000032 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
33
Chris Lattnerf4b136f2009-02-18 06:13:04 +000034 // Most ObjC strings are formed out of a single piece. However, we *can*
35 // have strings formed out of multiple @ strings with multiple pptokens in
36 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
37 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner39c28bb2009-02-18 06:48:40 +000038 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000039
Chris Lattnerf4b136f2009-02-18 06:13:04 +000040 // If we have a multi-part string, merge it all together.
41 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000042 // Concatenate objc strings.
Chris Lattner39c28bb2009-02-18 06:48:40 +000043 llvm::SmallString<128> StrBuf;
44 llvm::SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000045
Chris Lattner726e1682009-02-18 05:49:11 +000046 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000047 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000048
Chris Lattner39c28bb2009-02-18 06:48:40 +000049 // ObjC strings can't be wide.
Chris Lattnerf4b136f2009-02-18 06:13:04 +000050 if (S->isWide()) {
51 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
52 << S->getSourceRange();
53 return true;
54 }
Mike Stump1eb44332009-09-09 15:08:12 +000055
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +000056 // Append the string.
57 StrBuf += S->getString();
Mike Stump1eb44332009-09-09 15:08:12 +000058
Chris Lattner39c28bb2009-02-18 06:48:40 +000059 // Get the locations of the string tokens.
60 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattner85a932e2008-01-04 22:32:30 +000061 }
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattner39c28bb2009-02-18 06:48:40 +000063 // Create the aggregate string with the appropriate content and location
64 // information.
Anders Carlsson3e2193c2011-04-14 00:40:03 +000065 S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(),
66 /*Wide=*/false, /*Pascal=*/false,
Chris Lattner2085fd62009-02-18 06:40:38 +000067 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000068 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000069 }
Mike Stump1eb44332009-09-09 15:08:12 +000070
Chris Lattner69039812009-02-18 06:01:06 +000071 // Verify that this composite string is acceptable for ObjC strings.
72 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000073 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000074
75 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000076 // the NSString interface is seen in this translation unit. Note: We
77 // don't use NSConstantString, since the runtime team considers this
78 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000079 QualType Ty = Context.getObjCConstantStringInterface();
80 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000081 Ty = Context.getObjCObjectPointerType(Ty);
Fariborz Jahanian8a437762010-04-23 23:19:04 +000082 } else if (getLangOptions().NoConstantCFStrings) {
Fariborz Jahanian4c733072010-10-19 17:19:29 +000083 IdentifierInfo *NSIdent=0;
84 std::string StringClass(getLangOptions().ObjCConstantStringClass);
85
86 if (StringClass.empty())
87 NSIdent = &Context.Idents.get("NSConstantString");
88 else
89 NSIdent = &Context.Idents.get(StringClass);
90
Fariborz Jahanian8a437762010-04-23 23:19:04 +000091 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
92 LookupOrdinaryName);
93 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
94 Context.setObjCConstantStringInterface(StrIF);
95 Ty = Context.getObjCConstantStringInterface();
96 Ty = Context.getObjCObjectPointerType(Ty);
97 } else {
98 // If there is no NSConstantString interface defined then treat this
99 // as error and recover from it.
100 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
101 << S->getSourceRange();
102 Ty = Context.getObjCIdType();
103 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000104 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000105 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +0000106 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
107 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000108 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
109 Context.setObjCConstantStringInterface(StrIF);
110 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000111 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000112 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000113 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000114 // strings as untyped objects and let the runtime figure it out later.
115 Ty = Context.getObjCIdType();
116 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000117 }
Mike Stump1eb44332009-09-09 15:08:12 +0000118
Chris Lattnerf4b136f2009-02-18 06:13:04 +0000119 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +0000120}
121
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000122ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000123 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000124 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000125 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000126 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000127 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000128 StrTy = Context.DependentTy;
129 else {
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000130 if (!EncodedType->getAsArrayTypeUnsafe()) // Incomplete array is handled.
131 if (RequireCompleteType(AtLoc, EncodedType,
132 PDiag(diag::err_incomplete_type_objc_at_encode)
133 << EncodedTypeInfo->getTypeLoc().getSourceRange()))
134 return ExprError();
135
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000136 std::string Str;
137 Context.getObjCEncodingForType(EncodedType, Str);
138
139 // The type of @encode is the same as the type of the corresponding string,
140 // which is an array type.
141 StrTy = Context.CharTy;
142 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000143 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000144 StrTy.addConst();
145 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
146 ArrayType::Normal, 0);
147 }
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Douglas Gregor81d34662010-04-20 15:39:42 +0000149 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000150}
151
John McCallf312b1e2010-08-26 23:41:50 +0000152ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
153 SourceLocation EncodeLoc,
154 SourceLocation LParenLoc,
155 ParsedType ty,
156 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000157 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000158 TypeSourceInfo *TInfo;
159 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
160 if (!TInfo)
161 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
162 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000163
Douglas Gregor81d34662010-04-20 15:39:42 +0000164 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000165}
166
John McCallf312b1e2010-08-26 23:41:50 +0000167ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
168 SourceLocation AtLoc,
169 SourceLocation SelLoc,
170 SourceLocation LParenLoc,
171 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000172 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000173 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000174 if (!Method)
175 Method = LookupFactoryMethodInGlobalPool(Sel,
176 SourceRange(LParenLoc, RParenLoc));
177 if (!Method)
178 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
179
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000180 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
181 = ReferencedSelectors.find(Sel);
182 if (Pos == ReferencedSelectors.end())
183 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
184
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000185 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000186 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000187}
188
John McCallf312b1e2010-08-26 23:41:50 +0000189ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
190 SourceLocation AtLoc,
191 SourceLocation ProtoLoc,
192 SourceLocation LParenLoc,
193 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000194 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000195 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000196 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000197 return true;
198 }
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000200 QualType Ty = Context.getObjCProtoType();
201 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000202 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000203 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000204 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000205}
206
John McCall26743b22011-02-03 09:00:02 +0000207/// Try to capture an implicit reference to 'self'.
208ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
209 // Ignore block scopes: we can capture through them.
210 DeclContext *DC = CurContext;
211 while (true) {
212 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
213 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
214 else break;
215 }
216
217 // If we're not in an ObjC method, error out. Note that, unlike the
218 // C++ case, we don't require an instance method --- class methods
219 // still have a 'self', and we really do still need to capture it!
220 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
221 if (!method)
222 return 0;
223
224 ImplicitParamDecl *self = method->getSelfDecl();
225 assert(self && "capturing 'self' in non-definition?");
226
227 // Mark that we're closing on 'this' in all the block scopes, if applicable.
228 for (unsigned idx = FunctionScopes.size() - 1;
229 isa<BlockScopeInfo>(FunctionScopes[idx]);
John McCall6b5a61b2011-02-07 10:33:21 +0000230 --idx) {
231 BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
232 unsigned &captureIndex = blockScope->CaptureMap[self];
233 if (captureIndex) break;
234
235 bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
236 blockScope->Captures.push_back(
237 BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
238 captureIndex = blockScope->Captures.size(); // +1
239 }
John McCall26743b22011-02-03 09:00:02 +0000240
241 return method;
242}
243
Douglas Gregor926df6c2011-06-11 01:09:30 +0000244QualType Sema::getMessageSendResultType(QualType ReceiverType,
245 ObjCMethodDecl *Method,
246 bool isClassMessage, bool isSuperMessage) {
247 assert(Method && "Must have a method");
248 if (!Method->hasRelatedResultType())
249 return Method->getSendResultType();
250
251 // If a method has a related return type:
252 // - if the method found is an instance method, but the message send
253 // was a class message send, T is the declared return type of the method
254 // found
255 if (Method->isInstanceMethod() && isClassMessage)
256 return Method->getSendResultType();
257
258 // - if the receiver is super, T is a pointer to the class of the
259 // enclosing method definition
260 if (isSuperMessage) {
261 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
262 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
263 return Context.getObjCObjectPointerType(
264 Context.getObjCInterfaceType(Class));
265 }
266
267 // - if the receiver is the name of a class U, T is a pointer to U
268 if (ReceiverType->getAs<ObjCInterfaceType>() ||
269 ReceiverType->isObjCQualifiedInterfaceType())
270 return Context.getObjCObjectPointerType(ReceiverType);
271 // - if the receiver is of type Class or qualified Class type,
272 // T is the declared return type of the method.
273 if (ReceiverType->isObjCClassType() ||
274 ReceiverType->isObjCQualifiedClassType())
275 return Method->getSendResultType();
276
277 // - if the receiver is id, qualified id, Class, or qualified Class, T
278 // is the receiver type, otherwise
279 // - T is the type of the receiver expression.
280 return ReceiverType;
281}
John McCall26743b22011-02-03 09:00:02 +0000282
Douglas Gregor926df6c2011-06-11 01:09:30 +0000283void Sema::EmitRelatedResultTypeNote(const Expr *E) {
284 E = E->IgnoreParenImpCasts();
285 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
286 if (!MsgSend)
287 return;
288
289 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
290 if (!Method)
291 return;
292
293 if (!Method->hasRelatedResultType())
294 return;
295
296 if (Context.hasSameUnqualifiedType(Method->getResultType()
297 .getNonReferenceType(),
298 MsgSend->getType()))
299 return;
300
301 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
302 << Method->isInstanceMethod() << Method->getSelector()
303 << MsgSend->getType();
304}
305
306bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
307 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000308 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000309 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000310 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000311 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000312 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000313 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000314 for (unsigned i = 0; i != NumArgs; i++) {
315 if (Args[i]->isTypeDependent())
316 continue;
317
John Wiegley429bb272011-04-08 18:41:53 +0000318 ExprResult Result = DefaultArgumentPromotion(Args[i]);
319 if (Result.isInvalid())
320 return true;
321 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000322 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000323
Chris Lattner077bf5e2008-11-24 03:33:13 +0000324 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
325 diag::warn_inst_method_not_found;
326 Diag(lbrac, DiagID)
327 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000328 ReturnType = Context.getObjCIdType();
John McCallf89e55a2010-11-18 06:31:45 +0000329 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000330 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000331 }
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Douglas Gregor926df6c2011-06-11 01:09:30 +0000333 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
334 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000335 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000337 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000338 // Method might have more arguments than selector indicates. This is due
339 // to addition of c-style arguments in method.
340 if (Method->param_size() > Sel.getNumArgs())
341 NumNamedArgs = Method->param_size();
342 // FIXME. This need be cleaned up.
343 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000344 Diag(lbrac, diag::err_typecheck_call_too_few_args)
345 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000346 return false;
347 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000348
Chris Lattner312531a2009-04-12 08:11:20 +0000349 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000350 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000351 // We can't do any type-checking on a type-dependent argument.
352 if (Args[i]->isTypeDependent())
353 continue;
354
Chris Lattner85a932e2008-01-04 22:32:30 +0000355 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000356
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000357 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000358 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000360 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
361 Param->getType(),
362 PDiag(diag::err_call_incomplete_argument)
363 << argExpr->getSourceRange()))
364 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000365
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000366 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
367 Param);
John McCall3fa5cae2010-10-26 07:05:15 +0000368 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000369 if (ArgE.isInvalid())
370 IsError = true;
371 else
372 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000373 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000374
375 // Promote additional arguments to variadic methods.
376 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000377 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
378 if (Args[i]->isTypeDependent())
379 continue;
380
John Wiegley429bb272011-04-08 18:41:53 +0000381 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
382 IsError |= Arg.isInvalid();
383 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000384 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000385 } else {
386 // Check for extra arguments to non-variadic methods.
387 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000388 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000389 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000390 << 2 /*method*/ << NumNamedArgs << NumArgs
391 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000392 << SourceRange(Args[NumNamedArgs]->getLocStart(),
393 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000394 }
395 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000396 // diagnose nonnull arguments.
397 for (specific_attr_iterator<NonNullAttr>
398 i = Method->specific_attr_begin<NonNullAttr>(),
399 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
400 CheckNonNullArguments(*i, Args, lbrac);
401 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000402
Douglas Gregor2725ca82010-04-21 19:57:20 +0000403 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000404 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000405}
406
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000407bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000408 // 'self' is objc 'self' in an objc method only.
Fariborz Jahanianb4602102011-03-28 16:23:34 +0000409 DeclContext *DC = CurContext;
410 while (isa<BlockDecl>(DC))
411 DC = DC->getParent();
412 if (DC && !isa<ObjCMethodDecl>(DC))
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000413 return false;
John McCallf6a16482010-12-04 03:47:34 +0000414 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RExpr))
415 if (ICE->getCastKind() == CK_LValueToRValue)
416 RExpr = ICE->getSubExpr();
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000417 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
418 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
419 return true;
420 return false;
421}
422
Steve Narofff1afaf62009-02-26 15:55:06 +0000423// Helper method for ActOnClassMethod/ActOnInstanceMethod.
424// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000425// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000426// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000427ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000428 ObjCInterfaceDecl *ClassDecl) {
429 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000430 // lookup in class and all superclasses
431 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000432 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000433 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000434
Steve Naroff5609ec02009-03-08 18:56:13 +0000435 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000436 if (!Method)
437 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000438
Steve Naroff5609ec02009-03-08 18:56:13 +0000439 // Before we give up, check if the selector is an instance method.
440 // But only in the root. This matches gcc's behaviour and what the
441 // runtime expects.
442 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000443 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000444 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000445 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000446 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000447 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
448 }
Mike Stump1eb44332009-09-09 15:08:12 +0000449
Steve Naroff5609ec02009-03-08 18:56:13 +0000450 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000451 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000452 return Method;
453}
454
455ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
456 ObjCInterfaceDecl *ClassDecl) {
457 ObjCMethodDecl *Method = 0;
458 while (ClassDecl && !Method) {
459 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000460 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000461 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000462
Steve Naroff5609ec02009-03-08 18:56:13 +0000463 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000464 if (!Method)
465 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000466 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000467 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000468 return Method;
469}
470
Fariborz Jahanian61478062011-03-09 20:18:06 +0000471/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
472/// list of a qualified objective pointer type.
473ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
474 const ObjCObjectPointerType *OPT,
475 bool Instance)
476{
477 ObjCMethodDecl *MD = 0;
478 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
479 E = OPT->qual_end(); I != E; ++I) {
480 ObjCProtocolDecl *PROTO = (*I);
481 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
482 return MD;
483 }
484 }
485 return 0;
486}
487
Chris Lattner7f816522010-04-11 07:45:24 +0000488/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
489/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000490ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000491HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000492 Expr *BaseExpr, DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000493 SourceLocation MemberLoc,
494 SourceLocation SuperLoc, QualType SuperType,
495 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000496 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
497 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000498
499 if (MemberName.getNameKind() != DeclarationName::Identifier) {
500 Diag(MemberLoc, diag::err_invalid_property_name)
501 << MemberName << QualType(OPT, 0);
502 return ExprError();
503 }
504
Chris Lattner7f816522010-04-11 07:45:24 +0000505 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
506
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000507 if (IFace->isForwardDecl()) {
508 Diag(MemberLoc, diag::err_property_not_found_forward_class)
509 << MemberName << QualType(OPT, 0);
510 Diag(IFace->getLocation(), diag::note_forward_class);
511 return ExprError();
512 }
Chris Lattner7f816522010-04-11 07:45:24 +0000513 // Search for a declared property first.
514 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
515 // Check whether we can reference this property.
516 if (DiagnoseUseOfDecl(PD, MemberLoc))
517 return ExprError();
518 QualType ResTy = PD->getType();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000519 ResTy = ResTy.getNonLValueExprType(Context);
Chris Lattner7f816522010-04-11 07:45:24 +0000520 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
521 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000522 if (Getter &&
523 (Getter->hasRelatedResultType()
524 || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
525 ResTy = getMessageSendResultType(QualType(OPT, 0), Getter, false,
526 Super);
527
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000528 if (Super)
529 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000530 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000531 MemberLoc,
532 SuperLoc, SuperType));
533 else
534 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000535 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000536 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000537 }
538 // Check protocols on qualified interfaces.
539 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
540 E = OPT->qual_end(); I != E; ++I)
541 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
542 // Check whether we can reference this property.
543 if (DiagnoseUseOfDecl(PD, MemberLoc))
544 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000545
546 QualType T = PD->getType();
547 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
548 T = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000549 if (Super)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000550 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000551 VK_LValue,
552 OK_ObjCProperty,
553 MemberLoc,
554 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000555 else
Douglas Gregor926df6c2011-06-11 01:09:30 +0000556 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000557 VK_LValue,
558 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000559 MemberLoc,
560 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000561 }
562 // If that failed, look for an "implicit" property by seeing if the nullary
563 // selector is implemented.
564
565 // FIXME: The logic for looking up nullary and unary selectors should be
566 // shared with the code in ActOnInstanceMessage.
567
568 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
569 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000570
571 // May be founf in property's qualified list.
572 if (!Getter)
573 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000574
575 // If this reference is in an @implementation, check for 'private' methods.
576 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000577 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000578
579 // Look through local category implementations associated with the class.
580 if (!Getter)
581 Getter = IFace->getCategoryInstanceMethod(Sel);
582 if (Getter) {
583 // Check if we can reference this property.
584 if (DiagnoseUseOfDecl(Getter, MemberLoc))
585 return ExprError();
586 }
587 // If we found a getter then this may be a valid dot-reference, we
588 // will look for the matching setter, in case it is needed.
589 Selector SetterSel =
590 SelectorTable::constructSetterName(PP.getIdentifierTable(),
591 PP.getSelectorTable(), Member);
592 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000593
594 // May be founf in property's qualified list.
595 if (!Setter)
596 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
597
Chris Lattner7f816522010-04-11 07:45:24 +0000598 if (!Setter) {
599 // If this reference is in an @implementation, also check for 'private'
600 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000601 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000602 }
603 // Look through local category implementations associated with the class.
604 if (!Setter)
605 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000606
Chris Lattner7f816522010-04-11 07:45:24 +0000607 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
608 return ExprError();
609
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000610 if (Getter || Setter) {
611 QualType PType;
612 if (Getter)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000613 PType = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000614 else {
615 ParmVarDecl *ArgDecl = *Setter->param_begin();
616 PType = ArgDecl->getType();
617 }
618
John McCall09431682010-11-18 19:01:18 +0000619 ExprValueKind VK = VK_LValue;
620 ExprObjectKind OK = OK_ObjCProperty;
621 if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
622 PType->isVoidType())
623 VK = VK_RValue, OK = OK_Ordinary;
624
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000625 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000626 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
627 PType, VK, OK,
628 MemberLoc,
629 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000630 else
John McCall12f78a62010-12-02 01:19:52 +0000631 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
632 PType, VK, OK,
633 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000634
Chris Lattner7f816522010-04-11 07:45:24 +0000635 }
636
637 // Attempt to correct for typos in property names.
638 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000639 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
Chris Lattner7f816522010-04-11 07:45:24 +0000640 Res.getAsSingle<ObjCPropertyDecl>()) {
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000641 DeclarationName TypoResult = Res.getLookupName();
Chris Lattner7f816522010-04-11 07:45:24 +0000642 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000643 << MemberName << QualType(OPT, 0) << TypoResult
644 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000645 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
646 Diag(Property->getLocation(), diag::note_previous_decl)
647 << Property->getDeclName();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000648 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc,
649 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000650 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000651 ObjCInterfaceDecl *ClassDeclared;
652 if (ObjCIvarDecl *Ivar =
653 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
654 QualType T = Ivar->getType();
655 if (const ObjCObjectPointerType * OBJPT =
656 T->getAsObjCInterfacePointerType()) {
657 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
658 if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
659 if (IFace->isForwardDecl()) {
660 Diag(MemberLoc, diag::err_property_not_as_forward_class)
Fariborz Jahanian2a96bf52011-02-17 17:30:05 +0000661 << MemberName << IFace;
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000662 Diag(IFace->getLocation(), diag::note_forward_class);
663 return ExprError();
664 }
665 }
666 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000667
Chris Lattner7f816522010-04-11 07:45:24 +0000668 Diag(MemberLoc, diag::err_property_not_found)
669 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000670 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000671 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000672 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000673 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000674}
675
676
677
John McCall60d7b3a2010-08-24 06:29:42 +0000678ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000679ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
680 IdentifierInfo &propertyName,
681 SourceLocation receiverNameLoc,
682 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000683
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000684 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000685 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
686 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000687
688 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000689 if (IFace == 0) {
690 // If the "receiver" is 'super' in a method, handle it as an expression-like
691 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000692 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000693 IsSuper = true;
694
John McCall26743b22011-02-03 09:00:02 +0000695 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000696 if (CurMethod->isInstanceMethod()) {
697 QualType T =
698 Context.getObjCInterfaceType(CurMethod->getClassInterface());
699 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000700
701 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000702 /*BaseExpr*/0, &propertyName,
703 propertyNameLoc,
704 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000705 }
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Chris Lattnereb483eb2010-04-11 08:28:14 +0000707 // Otherwise, if this is a class method, try dispatching to our
708 // superclass.
709 IFace = CurMethod->getClassInterface()->getSuperClass();
710 }
John McCall26743b22011-02-03 09:00:02 +0000711 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000712
713 if (IFace == 0) {
714 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
715 return ExprError();
716 }
717 }
718
719 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000720 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000721 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000722
723 // If this reference is in an @implementation, check for 'private' methods.
724 if (!Getter)
725 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
726 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000727 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000728 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000729
730 if (Getter) {
731 // FIXME: refactor/share with ActOnMemberReference().
732 // Check if we can reference this property.
733 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
734 return ExprError();
735 }
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Steve Naroff61f72cb2009-03-09 21:12:44 +0000737 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000738 Selector SetterSel =
739 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000740 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000742 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000743 if (!Setter) {
744 // If this reference is in an @implementation, also check for 'private'
745 // methods.
746 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
747 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000748 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000749 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000750 }
751 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000752 if (!Setter)
753 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000754
755 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
756 return ExprError();
757
758 if (Getter || Setter) {
759 QualType PType;
760
John McCall09431682010-11-18 19:01:18 +0000761 ExprValueKind VK = VK_LValue;
762 if (Getter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000763 PType = getMessageSendResultType(Context.getObjCInterfaceType(IFace),
764 Getter, true,
765 receiverNamePtr->isStr("super"));
John McCall09431682010-11-18 19:01:18 +0000766 if (!getLangOptions().CPlusPlus &&
767 !PType.hasQualifiers() && PType->isVoidType())
768 VK = VK_RValue;
769 } else {
Steve Naroff61f72cb2009-03-09 21:12:44 +0000770 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
771 E = Setter->param_end(); PI != E; ++PI)
772 PType = (*PI)->getType();
John McCall09431682010-11-18 19:01:18 +0000773 VK = VK_LValue;
Steve Naroff61f72cb2009-03-09 21:12:44 +0000774 }
John McCall09431682010-11-18 19:01:18 +0000775
776 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
777
Douglas Gregor926df6c2011-06-11 01:09:30 +0000778 if (IsSuper)
779 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
780 PType, VK, OK,
781 propertyNameLoc,
782 receiverNameLoc,
783 Context.getObjCInterfaceType(IFace)));
784
John McCall12f78a62010-12-02 01:19:52 +0000785 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
786 PType, VK, OK,
787 propertyNameLoc,
788 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000789 }
790 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
791 << &propertyName << Context.getObjCInterfaceType(IFace));
792}
793
Douglas Gregor47bd5432010-04-14 02:46:37 +0000794Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000795 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000796 SourceLocation NameLoc,
797 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000798 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000799 ParsedType &ReceiverType) {
800 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000801
Douglas Gregor47bd5432010-04-14 02:46:37 +0000802 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000803 // messaging super. If the identifier is "super" and there is a
804 // trailing dot, it's an instance message.
805 if (IsSuper && S->isInObjcMethodScope())
806 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000807
808 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
809 LookupName(Result, S);
810
811 switch (Result.getResultKind()) {
812 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000813 // Normal name lookup didn't find anything. If we're in an
814 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000815 // FIXME: This is a hack. Ivar lookup should be part of normal
816 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000817 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
818 ObjCInterfaceDecl *ClassDeclared;
819 if (Method->getClassInterface()->lookupInstanceVariable(Name,
820 ClassDeclared))
821 return ObjCInstanceMessage;
822 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000823
Douglas Gregor47bd5432010-04-14 02:46:37 +0000824 // Break out; we'll perform typo correction below.
825 break;
826
827 case LookupResult::NotFoundInCurrentInstantiation:
828 case LookupResult::FoundOverloaded:
829 case LookupResult::FoundUnresolvedValue:
830 case LookupResult::Ambiguous:
831 Result.suppressDiagnostics();
832 return ObjCInstanceMessage;
833
834 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000835 // If the identifier is a class or not, and there is a trailing dot,
836 // it's an instance message.
837 if (HasTrailingDot)
838 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000839 // We found something. If it's a type, then we have a class
840 // message. Otherwise, it's an instance message.
841 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000842 QualType T;
843 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
844 T = Context.getObjCInterfaceType(Class);
845 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
846 T = Context.getTypeDeclType(Type);
847 else
848 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000849
Douglas Gregor1569f952010-04-21 20:38:13 +0000850 // We have a class message, and T is the type we're
851 // messaging. Build source-location information for it.
852 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000853 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000854 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000855 }
856 }
857
Douglas Gregoraaf87162010-04-14 20:04:41 +0000858 // Determine our typo-correction context.
859 CorrectTypoContext CTC = CTC_Expression;
860 if (ObjCMethodDecl *Method = getCurMethodDecl())
861 if (Method->getClassInterface() &&
862 Method->getClassInterface()->getSuperClass())
863 CTC = CTC_ObjCMessageReceiver;
864
865 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
866 if (Result.isSingleResult()) {
867 // If we found a declaration, correct when it refers to an Objective-C
868 // class.
869 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000870 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000871 Diag(NameLoc, diag::err_unknown_receiver_suggest)
872 << Name << Result.getLookupName()
873 << FixItHint::CreateReplacement(SourceRange(NameLoc),
874 ND->getNameAsString());
875 Diag(ND->getLocation(), diag::note_previous_decl)
876 << Corrected;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000877
Douglas Gregor1569f952010-04-21 20:38:13 +0000878 QualType T = Context.getObjCInterfaceType(Class);
879 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000880 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000881 return ObjCClassMessage;
882 }
883 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
884 Corrected.getAsIdentifierInfo()->isStr("super")) {
885 // If we've found the keyword "super", this is a send to super.
886 Diag(NameLoc, diag::err_unknown_receiver_suggest)
887 << Name << Corrected
888 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000889 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000890 }
891 }
892
893 // Fall back: let the parser try to parse it as an instance message.
894 return ObjCInstanceMessage;
895}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000896
John McCall60d7b3a2010-08-24 06:29:42 +0000897ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000898 SourceLocation SuperLoc,
899 Selector Sel,
900 SourceLocation LBracLoc,
901 SourceLocation SelectorLoc,
902 SourceLocation RBracLoc,
903 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000904 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000905 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000906 if (!Method) {
907 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
908 return ExprError();
909 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000910
Douglas Gregorf95861a2010-04-21 20:01:04 +0000911 ObjCInterfaceDecl *Class = Method->getClassInterface();
912 if (!Class) {
913 Diag(SuperLoc, diag::error_no_super_class_message)
914 << Method->getDeclName();
915 return ExprError();
916 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000917
Douglas Gregorf95861a2010-04-21 20:01:04 +0000918 ObjCInterfaceDecl *Super = Class->getSuperClass();
919 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000920 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000921 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
922 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000923 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000924 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000925
Douglas Gregorf95861a2010-04-21 20:01:04 +0000926 // We are in a method whose class has a superclass, so 'super'
927 // is acting as a keyword.
928 if (Method->isInstanceMethod()) {
929 // Since we are in an instance method, this is an instance
930 // message to the superclass instance.
931 QualType SuperTy = Context.getObjCInterfaceType(Super);
932 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +0000933 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000934 Sel, /*Method=*/0,
935 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000936 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000937
938 // Since we are in a class method, this is a class message to
939 // the superclass.
940 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
941 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000942 SuperLoc, Sel, /*Method=*/0,
943 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000944}
945
946/// \brief Build an Objective-C class message expression.
947///
948/// This routine takes care of both normal class messages and
949/// class messages to the superclass.
950///
951/// \param ReceiverTypeInfo Type source information that describes the
952/// receiver of this message. This may be NULL, in which case we are
953/// sending to the superclass and \p SuperLoc must be a valid source
954/// location.
955
956/// \param ReceiverType The type of the object receiving the
957/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
958/// type as that refers to. For a superclass send, this is the type of
959/// the superclass.
960///
961/// \param SuperLoc The location of the "super" keyword in a
962/// superclass message.
963///
964/// \param Sel The selector to which the message is being sent.
965///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000966/// \param Method The method that this class message is invoking, if
967/// already known.
968///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000969/// \param LBracLoc The location of the opening square bracket ']'.
970///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000971/// \param RBrac The location of the closing square bracket ']'.
972///
973/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +0000974ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000975 QualType ReceiverType,
976 SourceLocation SuperLoc,
977 Selector Sel,
978 ObjCMethodDecl *Method,
979 SourceLocation LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000980 SourceLocation SelectorLoc,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000981 SourceLocation RBracLoc,
982 MultiExprArg ArgsIn) {
983 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +0000984 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +0000985 if (LBracLoc.isInvalid()) {
986 Diag(Loc, diag::err_missing_open_square_message_send)
987 << FixItHint::CreateInsertion(Loc, "[");
988 LBracLoc = Loc;
989 }
990
Douglas Gregor92e986e2010-04-22 16:44:27 +0000991 if (ReceiverType->isDependentType()) {
992 // If the receiver type is dependent, we can't type-check anything
993 // at this point. Build a dependent expression.
994 unsigned NumArgs = ArgsIn.size();
995 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
996 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +0000997 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
998 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000999 Sel, SelectorLoc, /*Method=*/0,
Douglas Gregor92e986e2010-04-22 16:44:27 +00001000 Args, NumArgs, RBracLoc));
1001 }
Chris Lattner15faee12010-04-12 05:38:43 +00001002
Douglas Gregor2725ca82010-04-21 19:57:20 +00001003 // Find the class to which we are sending this message.
1004 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001005 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1006 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001007 Diag(Loc, diag::err_invalid_receiver_class_message)
1008 << ReceiverType;
1009 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001010 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001011 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian02b0d652011-03-08 19:12:46 +00001012 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001013 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001014 if (!Method) {
1015 if (Class->isForwardDecl()) {
1016 // A forward class used in messaging is treated as a 'Class'
1017 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1018 Method = LookupFactoryMethodInGlobalPool(Sel,
1019 SourceRange(LBracLoc, RBracLoc));
1020 if (Method)
1021 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1022 << Method->getDeclName();
1023 }
1024 if (!Method)
1025 Method = Class->lookupClassMethod(Sel);
1026
1027 // If we have an implementation in scope, check "private" methods.
1028 if (!Method)
1029 Method = LookupPrivateClassMethod(Sel, Class);
1030
1031 if (Method && DiagnoseUseOfDecl(Method, Loc))
1032 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001033 }
Mike Stump1eb44332009-09-09 15:08:12 +00001034
Douglas Gregor2725ca82010-04-21 19:57:20 +00001035 // Check the argument types and determine the result type.
1036 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001037 ExprValueKind VK = VK_RValue;
1038
Douglas Gregor2725ca82010-04-21 19:57:20 +00001039 unsigned NumArgs = ArgsIn.size();
1040 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001041 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1042 SuperLoc.isValid(), LBracLoc, RBracLoc,
1043 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001044 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001045
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001046 if (Method && !Method->getResultType()->isVoidType() &&
1047 RequireCompleteType(LBracLoc, Method->getResultType(),
1048 diag::err_illegal_message_expr_incomplete_type))
1049 return ExprError();
1050
Douglas Gregor2725ca82010-04-21 19:57:20 +00001051 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001052 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001053 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001054 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001055 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001056 ReceiverType, Sel, SelectorLoc,
1057 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001058 else
John McCallf89e55a2010-11-18 06:31:45 +00001059 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001060 ReceiverTypeInfo, Sel, SelectorLoc,
1061 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001062 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001063}
1064
Douglas Gregor2725ca82010-04-21 19:57:20 +00001065// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001066// ArgExprs is optional - if it is present, the number of expressions
1067// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001068ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001069 ParsedType Receiver,
1070 Selector Sel,
1071 SourceLocation LBracLoc,
1072 SourceLocation SelectorLoc,
1073 SourceLocation RBracLoc,
1074 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001075 TypeSourceInfo *ReceiverTypeInfo;
1076 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1077 if (ReceiverType.isNull())
1078 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001079
Mike Stump1eb44332009-09-09 15:08:12 +00001080
Douglas Gregor2725ca82010-04-21 19:57:20 +00001081 if (!ReceiverTypeInfo)
1082 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1083
1084 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001085 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001086 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001087}
1088
1089/// \brief Build an Objective-C instance message expression.
1090///
1091/// This routine takes care of both normal instance messages and
1092/// instance messages to the superclass instance.
1093///
1094/// \param Receiver The expression that computes the object that will
1095/// receive this message. This may be empty, in which case we are
1096/// sending to the superclass instance and \p SuperLoc must be a valid
1097/// source location.
1098///
1099/// \param ReceiverType The (static) type of the object receiving the
1100/// message. When a \p Receiver expression is provided, this is the
1101/// same type as that expression. For a superclass instance send, this
1102/// is a pointer to the type of the superclass.
1103///
1104/// \param SuperLoc The location of the "super" keyword in a
1105/// superclass instance message.
1106///
1107/// \param Sel The selector to which the message is being sent.
1108///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001109/// \param Method The method that this instance message is invoking, if
1110/// already known.
1111///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001112/// \param LBracLoc The location of the opening square bracket ']'.
1113///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001114/// \param RBrac The location of the closing square bracket ']'.
1115///
1116/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001117ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001118 QualType ReceiverType,
1119 SourceLocation SuperLoc,
1120 Selector Sel,
1121 ObjCMethodDecl *Method,
1122 SourceLocation LBracLoc,
1123 SourceLocation SelectorLoc,
1124 SourceLocation RBracLoc,
1125 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001126 // The location of the receiver.
1127 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1128
1129 if (LBracLoc.isInvalid()) {
1130 Diag(Loc, diag::err_missing_open_square_message_send)
1131 << FixItHint::CreateInsertion(Loc, "[");
1132 LBracLoc = Loc;
1133 }
1134
Douglas Gregor2725ca82010-04-21 19:57:20 +00001135 // If we have a receiver expression, perform appropriate promotions
1136 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001137 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001138 if (Receiver->isTypeDependent()) {
1139 // If the receiver is type-dependent, we can't type-check anything
1140 // at this point. Build a dependent expression.
1141 unsigned NumArgs = ArgsIn.size();
1142 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1143 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1144 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001145 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001146 SelectorLoc, /*Method=*/0,
1147 Args, NumArgs, RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001148 }
1149
Douglas Gregor2725ca82010-04-21 19:57:20 +00001150 // If necessary, apply function/array conversion to the receiver.
1151 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001152 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1153 if (Result.isInvalid())
1154 return ExprError();
1155 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001156 ReceiverType = Receiver->getType();
1157 }
1158
Douglas Gregorf49bb082010-04-22 17:01:48 +00001159 if (!Method) {
1160 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001161 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001162 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001163 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1164 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001165 SourceRange(LBracLoc, RBracLoc),
1166 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001167 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001168 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001169 SourceRange(LBracLoc, RBracLoc),
1170 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001171 } else if (ReceiverType->isObjCClassType() ||
1172 ReceiverType->isObjCQualifiedClassType()) {
1173 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001174 // We allow sending a message to a qualified Class ("Class<foo>"), which
1175 // is ok as long as one of the protocols implements the selector (if not, warn).
1176 if (const ObjCObjectPointerType *QClassTy
1177 = ReceiverType->getAsObjCQualifiedClassType()) {
1178 // Search protocols for class methods.
1179 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1180 if (!Method) {
1181 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1182 // warn if instance method found for a Class message.
1183 if (Method) {
1184 Diag(Loc, diag::warn_instance_method_on_class_found)
1185 << Method->getSelector() << Sel;
1186 Diag(Method->getLocation(), diag::note_method_declared_at);
1187 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001188 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001189 } else {
1190 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1191 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1192 // First check the public methods in the class interface.
1193 Method = ClassDecl->lookupClassMethod(Sel);
1194
1195 if (!Method)
1196 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1197 }
1198 if (Method && DiagnoseUseOfDecl(Method, Loc))
1199 return ExprError();
1200 }
1201 if (!Method) {
1202 // If not messaging 'self', look for any factory method named 'Sel'.
1203 if (!Receiver || !isSelfExpr(Receiver)) {
1204 Method = LookupFactoryMethodInGlobalPool(Sel,
1205 SourceRange(LBracLoc, RBracLoc),
1206 true);
1207 if (!Method) {
1208 // If no class (factory) method was found, check if an _instance_
1209 // method of the same name exists in the root class only.
1210 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001211 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001212 true);
1213 if (Method)
1214 if (const ObjCInterfaceDecl *ID =
1215 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1216 if (ID->getSuperClass())
1217 Diag(Loc, diag::warn_root_inst_method_not_found)
1218 << Sel << SourceRange(LBracLoc, RBracLoc);
1219 }
1220 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001221 }
1222 }
1223 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001224 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001225 ObjCInterfaceDecl* ClassDecl = 0;
1226
1227 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1228 // long as one of the protocols implements the selector (if not, warn).
1229 if (const ObjCObjectPointerType *QIdTy
1230 = ReceiverType->getAsObjCQualifiedIdType()) {
1231 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001232 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1233 if (!Method)
1234 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001235 } else if (const ObjCObjectPointerType *OCIType
1236 = ReceiverType->getAsObjCInterfacePointerType()) {
1237 // We allow sending a message to a pointer to an interface (an object).
1238 ClassDecl = OCIType->getInterfaceDecl();
1239 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1240 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +00001241 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001242 Method = ClassDecl->lookupInstanceMethod(Sel);
1243
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001244 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001245 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001246 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1247
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001248 const ObjCInterfaceDecl *forwardClass = 0;
Douglas Gregorf49bb082010-04-22 17:01:48 +00001249 if (!Method) {
1250 // If we have implementations in scope, check "private" methods.
1251 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1252
1253 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1254 // If we still haven't found a method, look in the global pool. This
1255 // behavior isn't very desirable, however we need it for GCC
1256 // compatibility. FIXME: should we deviate??
1257 if (OCIType->qual_empty()) {
1258 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001259 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001260 if (OCIType->getInterfaceDecl()->isForwardDecl())
1261 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001262 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001263 Diag(Loc, diag::warn_maynot_respond)
1264 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1265 }
1266 }
1267 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001268 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001269 return ExprError();
1270 } else if (!Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001271 (ReceiverType->isPointerType() ||
1272 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001273 // Implicitly convert integers and pointers to 'id' but emit a warning.
1274 Diag(Loc, diag::warn_bad_receiver_type)
1275 << ReceiverType
1276 << Receiver->getSourceRange();
1277 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001278 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1279 CK_BitCast).take();
John McCall404cd162010-11-13 01:35:44 +00001280 else {
1281 // TODO: specialized warning on null receivers?
1282 bool IsNull = Receiver->isNullPointerConstant(Context,
1283 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001284 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1285 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001286 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001287 ReceiverType = Receiver->getType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00001288 }
John Wiegley429bb272011-04-08 18:41:53 +00001289 else {
1290 ExprResult ReceiverRes;
1291 if (getLangOptions().CPlusPlus)
1292 ReceiverRes = PerformContextuallyConvertToObjCId(Receiver);
1293 if (ReceiverRes.isUsable()) {
1294 Receiver = ReceiverRes.take();
1295 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
1296 Receiver = ICE->getSubExpr();
1297 ReceiverType = Receiver->getType();
1298 }
1299 return BuildInstanceMessage(Receiver,
1300 ReceiverType,
1301 SuperLoc,
1302 Sel,
1303 Method,
1304 LBracLoc,
1305 SelectorLoc,
1306 RBracLoc,
1307 move(ArgsIn));
1308 } else {
1309 // Reject other random receiver types (e.g. structs).
1310 Diag(Loc, diag::err_bad_receiver_type)
1311 << ReceiverType << Receiver->getSourceRange();
1312 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001313 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001314 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001315 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001316 }
Mike Stump1eb44332009-09-09 15:08:12 +00001317
Douglas Gregor2725ca82010-04-21 19:57:20 +00001318 // Check the message arguments.
1319 unsigned NumArgs = ArgsIn.size();
1320 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1321 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001322 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001323 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1324 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001325 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1326 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001327 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001328 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001329
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001330 if (Method && !Method->getResultType()->isVoidType() &&
1331 RequireCompleteType(LBracLoc, Method->getResultType(),
1332 diag::err_illegal_message_expr_incomplete_type))
1333 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001334
Douglas Gregor2725ca82010-04-21 19:57:20 +00001335 // Construct the appropriate ObjCMessageExpr instance.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001336 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001337 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001338 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001339 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001340 ReceiverType, Sel, SelectorLoc, Method,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001341 Args, NumArgs, RBracLoc);
1342 else
John McCallf89e55a2010-11-18 06:31:45 +00001343 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001344 Receiver, Sel, SelectorLoc, Method,
1345 Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001346 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001347}
1348
1349// ActOnInstanceMessage - used for both unary and keyword messages.
1350// ArgExprs is optional - if it is present, the number of expressions
1351// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001352ExprResult Sema::ActOnInstanceMessage(Scope *S,
1353 Expr *Receiver,
1354 Selector Sel,
1355 SourceLocation LBracLoc,
1356 SourceLocation SelectorLoc,
1357 SourceLocation RBracLoc,
1358 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001359 if (!Receiver)
1360 return ExprError();
1361
John McCall9ae2f072010-08-23 23:25:46 +00001362 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001363 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001364 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001365}
Chris Lattnereca7be62008-04-07 05:30:13 +00001366