blob: 2a262f09392211ef57000565943492c5e8d7868a [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
Mike Stump1eb44332009-09-09 15:08:12 +0000122Expr *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 {
130 std::string Str;
131 Context.getObjCEncodingForType(EncodedType, Str);
132
133 // The type of @encode is the same as the type of the corresponding string,
134 // which is an array type.
135 StrTy = Context.CharTy;
136 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000137 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000138 StrTy.addConst();
139 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
140 ArrayType::Normal, 0);
141 }
Mike Stump1eb44332009-09-09 15:08:12 +0000142
Douglas Gregor81d34662010-04-20 15:39:42 +0000143 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000144}
145
John McCallf312b1e2010-08-26 23:41:50 +0000146ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
147 SourceLocation EncodeLoc,
148 SourceLocation LParenLoc,
149 ParsedType ty,
150 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000151 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000152 TypeSourceInfo *TInfo;
153 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
154 if (!TInfo)
155 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
156 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000157
Douglas Gregor81d34662010-04-20 15:39:42 +0000158 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000159}
160
John McCallf312b1e2010-08-26 23:41:50 +0000161ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
162 SourceLocation AtLoc,
163 SourceLocation SelLoc,
164 SourceLocation LParenLoc,
165 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000166 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000167 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000168 if (!Method)
169 Method = LookupFactoryMethodInGlobalPool(Sel,
170 SourceRange(LParenLoc, RParenLoc));
171 if (!Method)
172 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
173
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000174 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
175 = ReferencedSelectors.find(Sel);
176 if (Pos == ReferencedSelectors.end())
177 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
178
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000179 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000180 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000181}
182
John McCallf312b1e2010-08-26 23:41:50 +0000183ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
184 SourceLocation AtLoc,
185 SourceLocation ProtoLoc,
186 SourceLocation LParenLoc,
187 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000188 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000189 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000190 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000191 return true;
192 }
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000194 QualType Ty = Context.getObjCProtoType();
195 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000196 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000197 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000198 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000199}
200
John McCall26743b22011-02-03 09:00:02 +0000201/// Try to capture an implicit reference to 'self'.
202ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
203 // Ignore block scopes: we can capture through them.
204 DeclContext *DC = CurContext;
205 while (true) {
206 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
207 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
208 else break;
209 }
210
211 // If we're not in an ObjC method, error out. Note that, unlike the
212 // C++ case, we don't require an instance method --- class methods
213 // still have a 'self', and we really do still need to capture it!
214 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
215 if (!method)
216 return 0;
217
218 ImplicitParamDecl *self = method->getSelfDecl();
219 assert(self && "capturing 'self' in non-definition?");
220
221 // Mark that we're closing on 'this' in all the block scopes, if applicable.
222 for (unsigned idx = FunctionScopes.size() - 1;
223 isa<BlockScopeInfo>(FunctionScopes[idx]);
John McCall6b5a61b2011-02-07 10:33:21 +0000224 --idx) {
225 BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
226 unsigned &captureIndex = blockScope->CaptureMap[self];
227 if (captureIndex) break;
228
229 bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
230 blockScope->Captures.push_back(
231 BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
232 captureIndex = blockScope->Captures.size(); // +1
233 }
John McCall26743b22011-02-03 09:00:02 +0000234
235 return method;
236}
237
238
Mike Stump1eb44332009-09-09 15:08:12 +0000239bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
240 Selector Sel, ObjCMethodDecl *Method,
Chris Lattner077bf5e2008-11-24 03:33:13 +0000241 bool isClassMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000242 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000243 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000244 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000245 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000246 for (unsigned i = 0; i != NumArgs; i++) {
247 if (Args[i]->isTypeDependent())
248 continue;
249
John Wiegley429bb272011-04-08 18:41:53 +0000250 ExprResult Result = DefaultArgumentPromotion(Args[i]);
251 if (Result.isInvalid())
252 return true;
253 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000254 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000255
Chris Lattner077bf5e2008-11-24 03:33:13 +0000256 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
257 diag::warn_inst_method_not_found;
258 Diag(lbrac, DiagID)
259 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000260 ReturnType = Context.getObjCIdType();
John McCallf89e55a2010-11-18 06:31:45 +0000261 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000262 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000263 }
Mike Stump1eb44332009-09-09 15:08:12 +0000264
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000265 ReturnType = Method->getSendResultType();
John McCallf89e55a2010-11-18 06:31:45 +0000266 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000268 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000269 // Method might have more arguments than selector indicates. This is due
270 // to addition of c-style arguments in method.
271 if (Method->param_size() > Sel.getNumArgs())
272 NumNamedArgs = Method->param_size();
273 // FIXME. This need be cleaned up.
274 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000275 Diag(lbrac, diag::err_typecheck_call_too_few_args)
276 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000277 return false;
278 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000279
Chris Lattner312531a2009-04-12 08:11:20 +0000280 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000281 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000282 // We can't do any type-checking on a type-dependent argument.
283 if (Args[i]->isTypeDependent())
284 continue;
285
Chris Lattner85a932e2008-01-04 22:32:30 +0000286 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000287
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000288 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000289 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000290
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000291 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
292 Param->getType(),
293 PDiag(diag::err_call_incomplete_argument)
294 << argExpr->getSourceRange()))
295 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000296
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000297 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
298 Param);
John McCall3fa5cae2010-10-26 07:05:15 +0000299 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000300 if (ArgE.isInvalid())
301 IsError = true;
302 else
303 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000304 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000305
306 // Promote additional arguments to variadic methods.
307 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000308 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
309 if (Args[i]->isTypeDependent())
310 continue;
311
John Wiegley429bb272011-04-08 18:41:53 +0000312 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
313 IsError |= Arg.isInvalid();
314 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000315 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000316 } else {
317 // Check for extra arguments to non-variadic methods.
318 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000319 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000320 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000321 << 2 /*method*/ << NumNamedArgs << NumArgs
322 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000323 << SourceRange(Args[NumNamedArgs]->getLocStart(),
324 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000325 }
326 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000327 // diagnose nonnull arguments.
328 for (specific_attr_iterator<NonNullAttr>
329 i = Method->specific_attr_begin<NonNullAttr>(),
330 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
331 CheckNonNullArguments(*i, Args, lbrac);
332 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000333
Douglas Gregor2725ca82010-04-21 19:57:20 +0000334 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000335 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000336}
337
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000338bool Sema::isSelfExpr(Expr *RExpr) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000339 // 'self' is objc 'self' in an objc method only.
Fariborz Jahanianb4602102011-03-28 16:23:34 +0000340 DeclContext *DC = CurContext;
341 while (isa<BlockDecl>(DC))
342 DC = DC->getParent();
343 if (DC && !isa<ObjCMethodDecl>(DC))
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000344 return false;
John McCallf6a16482010-12-04 03:47:34 +0000345 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RExpr))
346 if (ICE->getCastKind() == CK_LValueToRValue)
347 RExpr = ICE->getSubExpr();
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000348 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
349 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
350 return true;
351 return false;
352}
353
Steve Narofff1afaf62009-02-26 15:55:06 +0000354// Helper method for ActOnClassMethod/ActOnInstanceMethod.
355// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000356// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000357// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000358ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000359 ObjCInterfaceDecl *ClassDecl) {
360 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000361 // lookup in class and all superclasses
362 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000363 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000364 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Steve Naroff5609ec02009-03-08 18:56:13 +0000366 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000367 if (!Method)
368 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
Steve Naroff5609ec02009-03-08 18:56:13 +0000370 // Before we give up, check if the selector is an instance method.
371 // But only in the root. This matches gcc's behaviour and what the
372 // runtime expects.
373 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000374 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000375 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000376 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000377 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000378 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
379 }
Mike Stump1eb44332009-09-09 15:08:12 +0000380
Steve Naroff5609ec02009-03-08 18:56:13 +0000381 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000382 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000383 return Method;
384}
385
386ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
387 ObjCInterfaceDecl *ClassDecl) {
388 ObjCMethodDecl *Method = 0;
389 while (ClassDecl && !Method) {
390 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000391 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000392 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Steve Naroff5609ec02009-03-08 18:56:13 +0000394 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000395 if (!Method)
396 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000397 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000398 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000399 return Method;
400}
401
Fariborz Jahanian61478062011-03-09 20:18:06 +0000402/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
403/// list of a qualified objective pointer type.
404ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
405 const ObjCObjectPointerType *OPT,
406 bool Instance)
407{
408 ObjCMethodDecl *MD = 0;
409 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
410 E = OPT->qual_end(); I != E; ++I) {
411 ObjCProtocolDecl *PROTO = (*I);
412 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
413 return MD;
414 }
415 }
416 return 0;
417}
418
Chris Lattner7f816522010-04-11 07:45:24 +0000419/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
420/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000421ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000422HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000423 Expr *BaseExpr, DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000424 SourceLocation MemberLoc,
425 SourceLocation SuperLoc, QualType SuperType,
426 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000427 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
428 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000429
430 if (MemberName.getNameKind() != DeclarationName::Identifier) {
431 Diag(MemberLoc, diag::err_invalid_property_name)
432 << MemberName << QualType(OPT, 0);
433 return ExprError();
434 }
435
Chris Lattner7f816522010-04-11 07:45:24 +0000436 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
437
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000438 if (IFace->isForwardDecl()) {
439 Diag(MemberLoc, diag::err_property_not_found_forward_class)
440 << MemberName << QualType(OPT, 0);
441 Diag(IFace->getLocation(), diag::note_forward_class);
442 return ExprError();
443 }
Chris Lattner7f816522010-04-11 07:45:24 +0000444 // Search for a declared property first.
445 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
446 // Check whether we can reference this property.
447 if (DiagnoseUseOfDecl(PD, MemberLoc))
448 return ExprError();
449 QualType ResTy = PD->getType();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000450 ResTy = ResTy.getNonLValueExprType(Context);
Chris Lattner7f816522010-04-11 07:45:24 +0000451 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
452 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
453 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
John McCallf89e55a2010-11-18 06:31:45 +0000454 ResTy = Getter->getResultType();
455
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000456 if (Super)
457 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000458 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000459 MemberLoc,
460 SuperLoc, SuperType));
461 else
462 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000463 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000464 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000465 }
466 // Check protocols on qualified interfaces.
467 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
468 E = OPT->qual_end(); I != E; ++I)
469 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
470 // Check whether we can reference this property.
471 if (DiagnoseUseOfDecl(PD, MemberLoc))
472 return ExprError();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000473 if (Super)
John McCallf89e55a2010-11-18 06:31:45 +0000474 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
475 VK_LValue,
476 OK_ObjCProperty,
477 MemberLoc,
478 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000479 else
480 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
John McCallf89e55a2010-11-18 06:31:45 +0000481 VK_LValue,
482 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000483 MemberLoc,
484 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000485 }
486 // If that failed, look for an "implicit" property by seeing if the nullary
487 // selector is implemented.
488
489 // FIXME: The logic for looking up nullary and unary selectors should be
490 // shared with the code in ActOnInstanceMessage.
491
492 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
493 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000494
495 // May be founf in property's qualified list.
496 if (!Getter)
497 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000498
499 // If this reference is in an @implementation, check for 'private' methods.
500 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000501 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000502
503 // Look through local category implementations associated with the class.
504 if (!Getter)
505 Getter = IFace->getCategoryInstanceMethod(Sel);
506 if (Getter) {
507 // Check if we can reference this property.
508 if (DiagnoseUseOfDecl(Getter, MemberLoc))
509 return ExprError();
510 }
511 // If we found a getter then this may be a valid dot-reference, we
512 // will look for the matching setter, in case it is needed.
513 Selector SetterSel =
514 SelectorTable::constructSetterName(PP.getIdentifierTable(),
515 PP.getSelectorTable(), Member);
516 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000517
518 // May be founf in property's qualified list.
519 if (!Setter)
520 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
521
Chris Lattner7f816522010-04-11 07:45:24 +0000522 if (!Setter) {
523 // If this reference is in an @implementation, also check for 'private'
524 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000525 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000526 }
527 // Look through local category implementations associated with the class.
528 if (!Setter)
529 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000530
Chris Lattner7f816522010-04-11 07:45:24 +0000531 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
532 return ExprError();
533
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000534 if (Getter || Setter) {
535 QualType PType;
536 if (Getter)
537 PType = Getter->getSendResultType();
538 else {
539 ParmVarDecl *ArgDecl = *Setter->param_begin();
540 PType = ArgDecl->getType();
541 }
542
John McCall09431682010-11-18 19:01:18 +0000543 ExprValueKind VK = VK_LValue;
544 ExprObjectKind OK = OK_ObjCProperty;
545 if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
546 PType->isVoidType())
547 VK = VK_RValue, OK = OK_Ordinary;
548
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000549 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000550 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
551 PType, VK, OK,
552 MemberLoc,
553 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000554 else
John McCall12f78a62010-12-02 01:19:52 +0000555 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
556 PType, VK, OK,
557 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000558
Chris Lattner7f816522010-04-11 07:45:24 +0000559 }
560
561 // Attempt to correct for typos in property names.
562 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000563 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
Chris Lattner7f816522010-04-11 07:45:24 +0000564 Res.getAsSingle<ObjCPropertyDecl>()) {
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000565 DeclarationName TypoResult = Res.getLookupName();
Chris Lattner7f816522010-04-11 07:45:24 +0000566 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000567 << MemberName << QualType(OPT, 0) << TypoResult
568 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000569 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
570 Diag(Property->getLocation(), diag::note_previous_decl)
571 << Property->getDeclName();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000572 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc,
573 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000574 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000575 ObjCInterfaceDecl *ClassDeclared;
576 if (ObjCIvarDecl *Ivar =
577 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
578 QualType T = Ivar->getType();
579 if (const ObjCObjectPointerType * OBJPT =
580 T->getAsObjCInterfacePointerType()) {
581 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
582 if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
583 if (IFace->isForwardDecl()) {
584 Diag(MemberLoc, diag::err_property_not_as_forward_class)
Fariborz Jahanian2a96bf52011-02-17 17:30:05 +0000585 << MemberName << IFace;
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000586 Diag(IFace->getLocation(), diag::note_forward_class);
587 return ExprError();
588 }
589 }
590 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000591
Chris Lattner7f816522010-04-11 07:45:24 +0000592 Diag(MemberLoc, diag::err_property_not_found)
593 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000594 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000595 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000596 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000597 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000598}
599
600
601
John McCall60d7b3a2010-08-24 06:29:42 +0000602ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000603ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
604 IdentifierInfo &propertyName,
605 SourceLocation receiverNameLoc,
606 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000608 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000609 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
610 receiverNameLoc);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000611 if (IFace == 0) {
612 // If the "receiver" is 'super' in a method, handle it as an expression-like
613 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000614 if (receiverNamePtr->isStr("super")) {
615 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000616 if (CurMethod->isInstanceMethod()) {
617 QualType T =
618 Context.getObjCInterfaceType(CurMethod->getClassInterface());
619 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000620
621 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000622 /*BaseExpr*/0, &propertyName,
623 propertyNameLoc,
624 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000625 }
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Chris Lattnereb483eb2010-04-11 08:28:14 +0000627 // Otherwise, if this is a class method, try dispatching to our
628 // superclass.
629 IFace = CurMethod->getClassInterface()->getSuperClass();
630 }
John McCall26743b22011-02-03 09:00:02 +0000631 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000632
633 if (IFace == 0) {
634 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
635 return ExprError();
636 }
637 }
638
639 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000640 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000641 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000642
643 // If this reference is in an @implementation, check for 'private' methods.
644 if (!Getter)
645 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
646 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000647 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000648 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000649
650 if (Getter) {
651 // FIXME: refactor/share with ActOnMemberReference().
652 // Check if we can reference this property.
653 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
654 return ExprError();
655 }
Mike Stump1eb44332009-09-09 15:08:12 +0000656
Steve Naroff61f72cb2009-03-09 21:12:44 +0000657 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000658 Selector SetterSel =
659 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000660 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000662 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000663 if (!Setter) {
664 // If this reference is in an @implementation, also check for 'private'
665 // methods.
666 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
667 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000668 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000669 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000670 }
671 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000672 if (!Setter)
673 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000674
675 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
676 return ExprError();
677
678 if (Getter || Setter) {
679 QualType PType;
680
John McCall09431682010-11-18 19:01:18 +0000681 ExprValueKind VK = VK_LValue;
682 if (Getter) {
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000683 PType = Getter->getSendResultType();
John McCall09431682010-11-18 19:01:18 +0000684 if (!getLangOptions().CPlusPlus &&
685 !PType.hasQualifiers() && PType->isVoidType())
686 VK = VK_RValue;
687 } else {
Steve Naroff61f72cb2009-03-09 21:12:44 +0000688 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
689 E = Setter->param_end(); PI != E; ++PI)
690 PType = (*PI)->getType();
John McCall09431682010-11-18 19:01:18 +0000691 VK = VK_LValue;
Steve Naroff61f72cb2009-03-09 21:12:44 +0000692 }
John McCall09431682010-11-18 19:01:18 +0000693
694 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
695
John McCall12f78a62010-12-02 01:19:52 +0000696 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
697 PType, VK, OK,
698 propertyNameLoc,
699 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000700 }
701 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
702 << &propertyName << Context.getObjCInterfaceType(IFace));
703}
704
Douglas Gregor47bd5432010-04-14 02:46:37 +0000705Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000706 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000707 SourceLocation NameLoc,
708 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000709 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000710 ParsedType &ReceiverType) {
711 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000712
Douglas Gregor47bd5432010-04-14 02:46:37 +0000713 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000714 // messaging super. If the identifier is "super" and there is a
715 // trailing dot, it's an instance message.
716 if (IsSuper && S->isInObjcMethodScope())
717 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000718
719 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
720 LookupName(Result, S);
721
722 switch (Result.getResultKind()) {
723 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000724 // Normal name lookup didn't find anything. If we're in an
725 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000726 // FIXME: This is a hack. Ivar lookup should be part of normal
727 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000728 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
729 ObjCInterfaceDecl *ClassDeclared;
730 if (Method->getClassInterface()->lookupInstanceVariable(Name,
731 ClassDeclared))
732 return ObjCInstanceMessage;
733 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000734
Douglas Gregor47bd5432010-04-14 02:46:37 +0000735 // Break out; we'll perform typo correction below.
736 break;
737
738 case LookupResult::NotFoundInCurrentInstantiation:
739 case LookupResult::FoundOverloaded:
740 case LookupResult::FoundUnresolvedValue:
741 case LookupResult::Ambiguous:
742 Result.suppressDiagnostics();
743 return ObjCInstanceMessage;
744
745 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000746 // If the identifier is a class or not, and there is a trailing dot,
747 // it's an instance message.
748 if (HasTrailingDot)
749 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000750 // We found something. If it's a type, then we have a class
751 // message. Otherwise, it's an instance message.
752 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000753 QualType T;
754 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
755 T = Context.getObjCInterfaceType(Class);
756 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
757 T = Context.getTypeDeclType(Type);
758 else
759 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000760
Douglas Gregor1569f952010-04-21 20:38:13 +0000761 // We have a class message, and T is the type we're
762 // messaging. Build source-location information for it.
763 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000764 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000765 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000766 }
767 }
768
Douglas Gregoraaf87162010-04-14 20:04:41 +0000769 // Determine our typo-correction context.
770 CorrectTypoContext CTC = CTC_Expression;
771 if (ObjCMethodDecl *Method = getCurMethodDecl())
772 if (Method->getClassInterface() &&
773 Method->getClassInterface()->getSuperClass())
774 CTC = CTC_ObjCMessageReceiver;
775
776 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
777 if (Result.isSingleResult()) {
778 // If we found a declaration, correct when it refers to an Objective-C
779 // class.
780 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000781 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000782 Diag(NameLoc, diag::err_unknown_receiver_suggest)
783 << Name << Result.getLookupName()
784 << FixItHint::CreateReplacement(SourceRange(NameLoc),
785 ND->getNameAsString());
786 Diag(ND->getLocation(), diag::note_previous_decl)
787 << Corrected;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000788
Douglas Gregor1569f952010-04-21 20:38:13 +0000789 QualType T = Context.getObjCInterfaceType(Class);
790 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000791 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000792 return ObjCClassMessage;
793 }
794 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
795 Corrected.getAsIdentifierInfo()->isStr("super")) {
796 // If we've found the keyword "super", this is a send to super.
797 Diag(NameLoc, diag::err_unknown_receiver_suggest)
798 << Name << Corrected
799 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000800 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000801 }
802 }
803
804 // Fall back: let the parser try to parse it as an instance message.
805 return ObjCInstanceMessage;
806}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000807
John McCall60d7b3a2010-08-24 06:29:42 +0000808ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000809 SourceLocation SuperLoc,
810 Selector Sel,
811 SourceLocation LBracLoc,
812 SourceLocation SelectorLoc,
813 SourceLocation RBracLoc,
814 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000815 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000816 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000817 if (!Method) {
818 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
819 return ExprError();
820 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000821
Douglas Gregorf95861a2010-04-21 20:01:04 +0000822 ObjCInterfaceDecl *Class = Method->getClassInterface();
823 if (!Class) {
824 Diag(SuperLoc, diag::error_no_super_class_message)
825 << Method->getDeclName();
826 return ExprError();
827 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000828
Douglas Gregorf95861a2010-04-21 20:01:04 +0000829 ObjCInterfaceDecl *Super = Class->getSuperClass();
830 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000831 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000832 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
833 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000834 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000835 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000836
Douglas Gregorf95861a2010-04-21 20:01:04 +0000837 // We are in a method whose class has a superclass, so 'super'
838 // is acting as a keyword.
839 if (Method->isInstanceMethod()) {
840 // Since we are in an instance method, this is an instance
841 // message to the superclass instance.
842 QualType SuperTy = Context.getObjCInterfaceType(Super);
843 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +0000844 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000845 Sel, /*Method=*/0,
846 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000847 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000848
849 // Since we are in a class method, this is a class message to
850 // the superclass.
851 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
852 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000853 SuperLoc, Sel, /*Method=*/0,
854 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000855}
856
857/// \brief Build an Objective-C class message expression.
858///
859/// This routine takes care of both normal class messages and
860/// class messages to the superclass.
861///
862/// \param ReceiverTypeInfo Type source information that describes the
863/// receiver of this message. This may be NULL, in which case we are
864/// sending to the superclass and \p SuperLoc must be a valid source
865/// location.
866
867/// \param ReceiverType The type of the object receiving the
868/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
869/// type as that refers to. For a superclass send, this is the type of
870/// the superclass.
871///
872/// \param SuperLoc The location of the "super" keyword in a
873/// superclass message.
874///
875/// \param Sel The selector to which the message is being sent.
876///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000877/// \param Method The method that this class message is invoking, if
878/// already known.
879///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000880/// \param LBracLoc The location of the opening square bracket ']'.
881///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000882/// \param RBrac The location of the closing square bracket ']'.
883///
884/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +0000885ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000886 QualType ReceiverType,
887 SourceLocation SuperLoc,
888 Selector Sel,
889 ObjCMethodDecl *Method,
890 SourceLocation LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000891 SourceLocation SelectorLoc,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000892 SourceLocation RBracLoc,
893 MultiExprArg ArgsIn) {
894 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +0000895 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +0000896 if (LBracLoc.isInvalid()) {
897 Diag(Loc, diag::err_missing_open_square_message_send)
898 << FixItHint::CreateInsertion(Loc, "[");
899 LBracLoc = Loc;
900 }
901
Douglas Gregor92e986e2010-04-22 16:44:27 +0000902 if (ReceiverType->isDependentType()) {
903 // If the receiver type is dependent, we can't type-check anything
904 // at this point. Build a dependent expression.
905 unsigned NumArgs = ArgsIn.size();
906 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
907 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +0000908 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
909 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000910 Sel, SelectorLoc, /*Method=*/0,
Douglas Gregor92e986e2010-04-22 16:44:27 +0000911 Args, NumArgs, RBracLoc));
912 }
Chris Lattner15faee12010-04-12 05:38:43 +0000913
Douglas Gregor2725ca82010-04-21 19:57:20 +0000914 // Find the class to which we are sending this message.
915 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +0000916 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
917 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000918 Diag(Loc, diag::err_invalid_receiver_class_message)
919 << ReceiverType;
920 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +0000921 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000922 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian02b0d652011-03-08 19:12:46 +0000923 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +0000924 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +0000925 if (!Method) {
926 if (Class->isForwardDecl()) {
927 // A forward class used in messaging is treated as a 'Class'
928 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
929 Method = LookupFactoryMethodInGlobalPool(Sel,
930 SourceRange(LBracLoc, RBracLoc));
931 if (Method)
932 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
933 << Method->getDeclName();
934 }
935 if (!Method)
936 Method = Class->lookupClassMethod(Sel);
937
938 // If we have an implementation in scope, check "private" methods.
939 if (!Method)
940 Method = LookupPrivateClassMethod(Sel, Class);
941
942 if (Method && DiagnoseUseOfDecl(Method, Loc))
943 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +0000944 }
Mike Stump1eb44332009-09-09 15:08:12 +0000945
Douglas Gregor2725ca82010-04-21 19:57:20 +0000946 // Check the argument types and determine the result type.
947 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +0000948 ExprValueKind VK = VK_RValue;
949
Douglas Gregor2725ca82010-04-21 19:57:20 +0000950 unsigned NumArgs = ArgsIn.size();
951 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
952 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
John McCallf89e55a2010-11-18 06:31:45 +0000953 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +0000954 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +0000955
Douglas Gregor483dd2f2011-01-11 03:23:19 +0000956 if (Method && !Method->getResultType()->isVoidType() &&
957 RequireCompleteType(LBracLoc, Method->getResultType(),
958 diag::err_illegal_message_expr_incomplete_type))
959 return ExprError();
960
Douglas Gregor2725ca82010-04-21 19:57:20 +0000961 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000962 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +0000963 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +0000964 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000965 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000966 ReceiverType, Sel, SelectorLoc,
967 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000968 else
John McCallf89e55a2010-11-18 06:31:45 +0000969 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000970 ReceiverTypeInfo, Sel, SelectorLoc,
971 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000972 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +0000973}
974
Douglas Gregor2725ca82010-04-21 19:57:20 +0000975// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +0000976// ArgExprs is optional - if it is present, the number of expressions
977// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +0000978ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +0000979 ParsedType Receiver,
980 Selector Sel,
981 SourceLocation LBracLoc,
982 SourceLocation SelectorLoc,
983 SourceLocation RBracLoc,
984 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000985 TypeSourceInfo *ReceiverTypeInfo;
986 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
987 if (ReceiverType.isNull())
988 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Mike Stump1eb44332009-09-09 15:08:12 +0000990
Douglas Gregor2725ca82010-04-21 19:57:20 +0000991 if (!ReceiverTypeInfo)
992 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
993
994 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000995 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000996 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000997}
998
999/// \brief Build an Objective-C instance message expression.
1000///
1001/// This routine takes care of both normal instance messages and
1002/// instance messages to the superclass instance.
1003///
1004/// \param Receiver The expression that computes the object that will
1005/// receive this message. This may be empty, in which case we are
1006/// sending to the superclass instance and \p SuperLoc must be a valid
1007/// source location.
1008///
1009/// \param ReceiverType The (static) type of the object receiving the
1010/// message. When a \p Receiver expression is provided, this is the
1011/// same type as that expression. For a superclass instance send, this
1012/// is a pointer to the type of the superclass.
1013///
1014/// \param SuperLoc The location of the "super" keyword in a
1015/// superclass instance message.
1016///
1017/// \param Sel The selector to which the message is being sent.
1018///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001019/// \param Method The method that this instance message is invoking, if
1020/// already known.
1021///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001022/// \param LBracLoc The location of the opening square bracket ']'.
1023///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001024/// \param RBrac The location of the closing square bracket ']'.
1025///
1026/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001027ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001028 QualType ReceiverType,
1029 SourceLocation SuperLoc,
1030 Selector Sel,
1031 ObjCMethodDecl *Method,
1032 SourceLocation LBracLoc,
1033 SourceLocation SelectorLoc,
1034 SourceLocation RBracLoc,
1035 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001036 // The location of the receiver.
1037 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1038
1039 if (LBracLoc.isInvalid()) {
1040 Diag(Loc, diag::err_missing_open_square_message_send)
1041 << FixItHint::CreateInsertion(Loc, "[");
1042 LBracLoc = Loc;
1043 }
1044
Douglas Gregor2725ca82010-04-21 19:57:20 +00001045 // If we have a receiver expression, perform appropriate promotions
1046 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001047 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001048 if (Receiver->isTypeDependent()) {
1049 // If the receiver is type-dependent, we can't type-check anything
1050 // at this point. Build a dependent expression.
1051 unsigned NumArgs = ArgsIn.size();
1052 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1053 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1054 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001055 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001056 SelectorLoc, /*Method=*/0,
1057 Args, NumArgs, RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001058 }
1059
Douglas Gregor2725ca82010-04-21 19:57:20 +00001060 // If necessary, apply function/array conversion to the receiver.
1061 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001062 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1063 if (Result.isInvalid())
1064 return ExprError();
1065 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001066 ReceiverType = Receiver->getType();
1067 }
1068
Douglas Gregorf49bb082010-04-22 17:01:48 +00001069 if (!Method) {
1070 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001071 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001072 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001073 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1074 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001075 SourceRange(LBracLoc, RBracLoc),
1076 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001077 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001078 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001079 SourceRange(LBracLoc, RBracLoc),
1080 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001081 } else if (ReceiverType->isObjCClassType() ||
1082 ReceiverType->isObjCQualifiedClassType()) {
1083 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001084 // We allow sending a message to a qualified Class ("Class<foo>"), which
1085 // is ok as long as one of the protocols implements the selector (if not, warn).
1086 if (const ObjCObjectPointerType *QClassTy
1087 = ReceiverType->getAsObjCQualifiedClassType()) {
1088 // Search protocols for class methods.
1089 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1090 if (!Method) {
1091 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1092 // warn if instance method found for a Class message.
1093 if (Method) {
1094 Diag(Loc, diag::warn_instance_method_on_class_found)
1095 << Method->getSelector() << Sel;
1096 Diag(Method->getLocation(), diag::note_method_declared_at);
1097 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001098 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001099 } else {
1100 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1101 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1102 // First check the public methods in the class interface.
1103 Method = ClassDecl->lookupClassMethod(Sel);
1104
1105 if (!Method)
1106 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1107 }
1108 if (Method && DiagnoseUseOfDecl(Method, Loc))
1109 return ExprError();
1110 }
1111 if (!Method) {
1112 // If not messaging 'self', look for any factory method named 'Sel'.
1113 if (!Receiver || !isSelfExpr(Receiver)) {
1114 Method = LookupFactoryMethodInGlobalPool(Sel,
1115 SourceRange(LBracLoc, RBracLoc),
1116 true);
1117 if (!Method) {
1118 // If no class (factory) method was found, check if an _instance_
1119 // method of the same name exists in the root class only.
1120 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001121 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001122 true);
1123 if (Method)
1124 if (const ObjCInterfaceDecl *ID =
1125 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1126 if (ID->getSuperClass())
1127 Diag(Loc, diag::warn_root_inst_method_not_found)
1128 << Sel << SourceRange(LBracLoc, RBracLoc);
1129 }
1130 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001131 }
1132 }
1133 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001134 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001135 ObjCInterfaceDecl* ClassDecl = 0;
1136
1137 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1138 // long as one of the protocols implements the selector (if not, warn).
1139 if (const ObjCObjectPointerType *QIdTy
1140 = ReceiverType->getAsObjCQualifiedIdType()) {
1141 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001142 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1143 if (!Method)
1144 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001145 } else if (const ObjCObjectPointerType *OCIType
1146 = ReceiverType->getAsObjCInterfacePointerType()) {
1147 // We allow sending a message to a pointer to an interface (an object).
1148 ClassDecl = OCIType->getInterfaceDecl();
1149 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1150 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +00001151 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001152 Method = ClassDecl->lookupInstanceMethod(Sel);
1153
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001154 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001155 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001156 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1157
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001158 const ObjCInterfaceDecl *forwardClass = 0;
Douglas Gregorf49bb082010-04-22 17:01:48 +00001159 if (!Method) {
1160 // If we have implementations in scope, check "private" methods.
1161 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1162
1163 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1164 // If we still haven't found a method, look in the global pool. This
1165 // behavior isn't very desirable, however we need it for GCC
1166 // compatibility. FIXME: should we deviate??
1167 if (OCIType->qual_empty()) {
1168 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001169 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001170 if (OCIType->getInterfaceDecl()->isForwardDecl())
1171 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001172 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001173 Diag(Loc, diag::warn_maynot_respond)
1174 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1175 }
1176 }
1177 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001178 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001179 return ExprError();
1180 } else if (!Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001181 (ReceiverType->isPointerType() ||
1182 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001183 // Implicitly convert integers and pointers to 'id' but emit a warning.
1184 Diag(Loc, diag::warn_bad_receiver_type)
1185 << ReceiverType
1186 << Receiver->getSourceRange();
1187 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001188 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1189 CK_BitCast).take();
John McCall404cd162010-11-13 01:35:44 +00001190 else {
1191 // TODO: specialized warning on null receivers?
1192 bool IsNull = Receiver->isNullPointerConstant(Context,
1193 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001194 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1195 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001196 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001197 ReceiverType = Receiver->getType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00001198 }
John Wiegley429bb272011-04-08 18:41:53 +00001199 else {
1200 ExprResult ReceiverRes;
1201 if (getLangOptions().CPlusPlus)
1202 ReceiverRes = PerformContextuallyConvertToObjCId(Receiver);
1203 if (ReceiverRes.isUsable()) {
1204 Receiver = ReceiverRes.take();
1205 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
1206 Receiver = ICE->getSubExpr();
1207 ReceiverType = Receiver->getType();
1208 }
1209 return BuildInstanceMessage(Receiver,
1210 ReceiverType,
1211 SuperLoc,
1212 Sel,
1213 Method,
1214 LBracLoc,
1215 SelectorLoc,
1216 RBracLoc,
1217 move(ArgsIn));
1218 } else {
1219 // Reject other random receiver types (e.g. structs).
1220 Diag(Loc, diag::err_bad_receiver_type)
1221 << ReceiverType << Receiver->getSourceRange();
1222 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001223 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001224 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001225 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001226 }
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Douglas Gregor2725ca82010-04-21 19:57:20 +00001228 // Check the message arguments.
1229 unsigned NumArgs = ArgsIn.size();
1230 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1231 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001232 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001233 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1234 ReceiverType->isObjCQualifiedClassType());
1235 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, ClassMessage,
John McCallf89e55a2010-11-18 06:31:45 +00001236 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001237 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001238
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001239 if (Method && !Method->getResultType()->isVoidType() &&
1240 RequireCompleteType(LBracLoc, Method->getResultType(),
1241 diag::err_illegal_message_expr_incomplete_type))
1242 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001243
Douglas Gregor2725ca82010-04-21 19:57:20 +00001244 // Construct the appropriate ObjCMessageExpr instance.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001245 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001246 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001247 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001248 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001249 ReceiverType, Sel, SelectorLoc, Method,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001250 Args, NumArgs, RBracLoc);
1251 else
John McCallf89e55a2010-11-18 06:31:45 +00001252 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001253 Receiver, Sel, SelectorLoc, Method,
1254 Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001255 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001256}
1257
1258// ActOnInstanceMessage - used for both unary and keyword messages.
1259// ArgExprs is optional - if it is present, the number of expressions
1260// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001261ExprResult Sema::ActOnInstanceMessage(Scope *S,
1262 Expr *Receiver,
1263 Selector Sel,
1264 SourceLocation LBracLoc,
1265 SourceLocation SelectorLoc,
1266 SourceLocation RBracLoc,
1267 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001268 if (!Receiver)
1269 return ExprError();
1270
John McCall9ae2f072010-08-23 23:25:46 +00001271 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001272 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001273 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001274}
Chris Lattnereca7be62008-04-07 05:30:13 +00001275