blob: be87a42a3cf729c3cb2521cde2f08d58031befae [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"
Douglas Gregore737f502010-08-12 20:07:10 +000017#include "clang/Sema/Initialization.h"
Chris Lattner85a932e2008-01-04 22:32:30 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000021#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000022#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000023#include "clang/Lex/Preprocessor.h"
24
Chris Lattner85a932e2008-01-04 22:32:30 +000025using namespace clang;
26
John McCallf312b1e2010-08-26 23:41:50 +000027ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
28 Expr **strings,
29 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000030 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
31
Chris Lattnerf4b136f2009-02-18 06:13:04 +000032 // Most ObjC strings are formed out of a single piece. However, we *can*
33 // have strings formed out of multiple @ strings with multiple pptokens in
34 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
35 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner39c28bb2009-02-18 06:48:40 +000036 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000037
Chris Lattnerf4b136f2009-02-18 06:13:04 +000038 // If we have a multi-part string, merge it all together.
39 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000040 // Concatenate objc strings.
Chris Lattner39c28bb2009-02-18 06:48:40 +000041 llvm::SmallString<128> StrBuf;
42 llvm::SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000043
Chris Lattner726e1682009-02-18 05:49:11 +000044 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000045 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000046
Chris Lattner39c28bb2009-02-18 06:48:40 +000047 // ObjC strings can't be wide.
Chris Lattnerf4b136f2009-02-18 06:13:04 +000048 if (S->isWide()) {
49 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
50 << S->getSourceRange();
51 return true;
52 }
Mike Stump1eb44332009-09-09 15:08:12 +000053
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +000054 // Append the string.
55 StrBuf += S->getString();
Mike Stump1eb44332009-09-09 15:08:12 +000056
Chris Lattner39c28bb2009-02-18 06:48:40 +000057 // Get the locations of the string tokens.
58 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattner85a932e2008-01-04 22:32:30 +000059 }
Mike Stump1eb44332009-09-09 15:08:12 +000060
Chris Lattner39c28bb2009-02-18 06:48:40 +000061 // Create the aggregate string with the appropriate content and location
62 // information.
63 S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(), false,
Chris Lattner2085fd62009-02-18 06:40:38 +000064 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000065 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000066 }
Mike Stump1eb44332009-09-09 15:08:12 +000067
Chris Lattner69039812009-02-18 06:01:06 +000068 // Verify that this composite string is acceptable for ObjC strings.
69 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000070 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000071
72 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000073 // the NSString interface is seen in this translation unit. Note: We
74 // don't use NSConstantString, since the runtime team considers this
75 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000076 QualType Ty = Context.getObjCConstantStringInterface();
77 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000078 Ty = Context.getObjCObjectPointerType(Ty);
Fariborz Jahanian8a437762010-04-23 23:19:04 +000079 } else if (getLangOptions().NoConstantCFStrings) {
Fariborz Jahanian4c733072010-10-19 17:19:29 +000080 IdentifierInfo *NSIdent=0;
81 std::string StringClass(getLangOptions().ObjCConstantStringClass);
82
83 if (StringClass.empty())
84 NSIdent = &Context.Idents.get("NSConstantString");
85 else
86 NSIdent = &Context.Idents.get(StringClass);
87
Fariborz Jahanian8a437762010-04-23 23:19:04 +000088 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
89 LookupOrdinaryName);
90 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
91 Context.setObjCConstantStringInterface(StrIF);
92 Ty = Context.getObjCConstantStringInterface();
93 Ty = Context.getObjCObjectPointerType(Ty);
94 } else {
95 // If there is no NSConstantString interface defined then treat this
96 // as error and recover from it.
97 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
98 << S->getSourceRange();
99 Ty = Context.getObjCIdType();
100 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000101 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000102 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +0000103 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
104 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000105 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
106 Context.setObjCConstantStringInterface(StrIF);
107 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000108 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000109 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000110 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000111 // strings as untyped objects and let the runtime figure it out later.
112 Ty = Context.getObjCIdType();
113 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000114 }
Mike Stump1eb44332009-09-09 15:08:12 +0000115
Chris Lattnerf4b136f2009-02-18 06:13:04 +0000116 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +0000117}
118
Mike Stump1eb44332009-09-09 15:08:12 +0000119Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000120 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000121 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000122 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000123 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000124 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000125 StrTy = Context.DependentTy;
126 else {
127 std::string Str;
128 Context.getObjCEncodingForType(EncodedType, Str);
129
130 // The type of @encode is the same as the type of the corresponding string,
131 // which is an array type.
132 StrTy = Context.CharTy;
133 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000134 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000135 StrTy.addConst();
136 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
137 ArrayType::Normal, 0);
138 }
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Douglas Gregor81d34662010-04-20 15:39:42 +0000140 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000141}
142
John McCallf312b1e2010-08-26 23:41:50 +0000143ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
144 SourceLocation EncodeLoc,
145 SourceLocation LParenLoc,
146 ParsedType ty,
147 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000148 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000149 TypeSourceInfo *TInfo;
150 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
151 if (!TInfo)
152 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
153 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000154
Douglas Gregor81d34662010-04-20 15:39:42 +0000155 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000156}
157
John McCallf312b1e2010-08-26 23:41:50 +0000158ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
159 SourceLocation AtLoc,
160 SourceLocation SelLoc,
161 SourceLocation LParenLoc,
162 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000163 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000164 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000165 if (!Method)
166 Method = LookupFactoryMethodInGlobalPool(Sel,
167 SourceRange(LParenLoc, RParenLoc));
168 if (!Method)
169 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
170
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000171 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
172 = ReferencedSelectors.find(Sel);
173 if (Pos == ReferencedSelectors.end())
174 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
175
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000176 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000177 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000178}
179
John McCallf312b1e2010-08-26 23:41:50 +0000180ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
181 SourceLocation AtLoc,
182 SourceLocation ProtoLoc,
183 SourceLocation LParenLoc,
184 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000185 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000186 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000187 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000188 return true;
189 }
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000191 QualType Ty = Context.getObjCProtoType();
192 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000193 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000194 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000195 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000196}
197
Mike Stump1eb44332009-09-09 15:08:12 +0000198bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
199 Selector Sel, ObjCMethodDecl *Method,
Chris Lattner077bf5e2008-11-24 03:33:13 +0000200 bool isClassMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000201 SourceLocation lbrac, SourceLocation rbrac,
Mike Stump1eb44332009-09-09 15:08:12 +0000202 QualType &ReturnType) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000203 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000204 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000205 for (unsigned i = 0; i != NumArgs; i++) {
206 if (Args[i]->isTypeDependent())
207 continue;
208
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000209 DefaultArgumentPromotion(Args[i]);
Douglas Gregor92e986e2010-04-22 16:44:27 +0000210 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000211
Chris Lattner077bf5e2008-11-24 03:33:13 +0000212 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
213 diag::warn_inst_method_not_found;
214 Diag(lbrac, DiagID)
215 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000216 ReturnType = Context.getObjCIdType();
217 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000218 }
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000220 ReturnType = Method->getSendResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000221
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000222 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000223 // Method might have more arguments than selector indicates. This is due
224 // to addition of c-style arguments in method.
225 if (Method->param_size() > Sel.getNumArgs())
226 NumNamedArgs = Method->param_size();
227 // FIXME. This need be cleaned up.
228 if (NumArgs < NumNamedArgs) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000229 Diag(lbrac, diag::err_typecheck_call_too_few_args) << 2
230 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000231 return false;
232 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000233
Chris Lattner312531a2009-04-12 08:11:20 +0000234 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000235 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000236 // We can't do any type-checking on a type-dependent argument.
237 if (Args[i]->isTypeDependent())
238 continue;
239
Chris Lattner85a932e2008-01-04 22:32:30 +0000240 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000241
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000242 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000243 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000245 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
246 Param->getType(),
247 PDiag(diag::err_call_incomplete_argument)
248 << argExpr->getSourceRange()))
249 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000250
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000251 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
252 Param);
John McCall3fa5cae2010-10-26 07:05:15 +0000253 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000254 if (ArgE.isInvalid())
255 IsError = true;
256 else
257 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000258 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000259
260 // Promote additional arguments to variadic methods.
261 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000262 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
263 if (Args[i]->isTypeDependent())
264 continue;
265
Chris Lattner40378332010-05-16 04:01:30 +0000266 IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
Douglas Gregor92e986e2010-04-22 16:44:27 +0000267 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000268 } else {
269 // Check for extra arguments to non-variadic methods.
270 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000271 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000272 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000273 << 2 /*method*/ << NumNamedArgs << NumArgs
274 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000275 << SourceRange(Args[NumNamedArgs]->getLocStart(),
276 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000277 }
278 }
279
Douglas Gregor2725ca82010-04-21 19:57:20 +0000280 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000281 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000282}
283
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000284bool Sema::isSelfExpr(Expr *RExpr) {
285 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
286 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
287 return true;
288 return false;
289}
290
Steve Narofff1afaf62009-02-26 15:55:06 +0000291// Helper method for ActOnClassMethod/ActOnInstanceMethod.
292// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000293// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000294// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000295ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000296 ObjCInterfaceDecl *ClassDecl) {
297 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000298 // lookup in class and all superclasses
299 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000300 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000301 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Steve Naroff5609ec02009-03-08 18:56:13 +0000303 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000304 if (!Method)
305 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Steve Naroff5609ec02009-03-08 18:56:13 +0000307 // Before we give up, check if the selector is an instance method.
308 // But only in the root. This matches gcc's behaviour and what the
309 // runtime expects.
310 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000311 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000312 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000313 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000314 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000315 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
316 }
Mike Stump1eb44332009-09-09 15:08:12 +0000317
Steve Naroff5609ec02009-03-08 18:56:13 +0000318 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000319 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000320 return Method;
321}
322
323ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
324 ObjCInterfaceDecl *ClassDecl) {
325 ObjCMethodDecl *Method = 0;
326 while (ClassDecl && !Method) {
327 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000328 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000329 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Steve Naroff5609ec02009-03-08 18:56:13 +0000331 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000332 if (!Method)
333 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000334 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000335 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000336 return Method;
337}
338
Chris Lattner7f816522010-04-11 07:45:24 +0000339/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
340/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000341ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000342HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000343 Expr *BaseExpr, DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000344 SourceLocation MemberLoc,
345 SourceLocation SuperLoc, QualType SuperType,
346 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000347 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
348 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
349 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
350
351 // Search for a declared property first.
352 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
353 // Check whether we can reference this property.
354 if (DiagnoseUseOfDecl(PD, MemberLoc))
355 return ExprError();
356 QualType ResTy = PD->getType();
357 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
358 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
359 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000360 ResTy = Getter->getSendResultType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000361 if (Super)
362 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
363 MemberLoc,
364 SuperLoc, SuperType));
365 else
366 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
367 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000368 }
369 // Check protocols on qualified interfaces.
370 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
371 E = OPT->qual_end(); I != E; ++I)
372 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
373 // Check whether we can reference this property.
374 if (DiagnoseUseOfDecl(PD, MemberLoc))
375 return ExprError();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000376 if (Super)
Chris Lattner7f816522010-04-11 07:45:24 +0000377 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000378 MemberLoc,
379 SuperLoc, SuperType));
380 else
381 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
382 MemberLoc,
383 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000384 }
385 // If that failed, look for an "implicit" property by seeing if the nullary
386 // selector is implemented.
387
388 // FIXME: The logic for looking up nullary and unary selectors should be
389 // shared with the code in ActOnInstanceMessage.
390
391 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
392 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
393
394 // If this reference is in an @implementation, check for 'private' methods.
395 if (!Getter)
396 Getter = IFace->lookupPrivateInstanceMethod(Sel);
397
398 // Look through local category implementations associated with the class.
399 if (!Getter)
400 Getter = IFace->getCategoryInstanceMethod(Sel);
401 if (Getter) {
402 // Check if we can reference this property.
403 if (DiagnoseUseOfDecl(Getter, MemberLoc))
404 return ExprError();
405 }
406 // If we found a getter then this may be a valid dot-reference, we
407 // will look for the matching setter, in case it is needed.
408 Selector SetterSel =
409 SelectorTable::constructSetterName(PP.getIdentifierTable(),
410 PP.getSelectorTable(), Member);
411 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
412 if (!Setter) {
413 // If this reference is in an @implementation, also check for 'private'
414 // methods.
415 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
416 }
417 // Look through local category implementations associated with the class.
418 if (!Setter)
419 Setter = IFace->getCategoryInstanceMethod(SetterSel);
420
421 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
422 return ExprError();
423
424 if (Getter) {
425 QualType PType;
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000426 PType = Getter->getSendResultType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000427 if (Super)
428 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
429 Setter, MemberLoc,
430 SuperLoc, SuperType));
431 else
432 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
433 Setter, MemberLoc,
434 BaseExpr));
435
Chris Lattner7f816522010-04-11 07:45:24 +0000436 }
437
438 // Attempt to correct for typos in property names.
439 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000440 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
Chris Lattner7f816522010-04-11 07:45:24 +0000441 Res.getAsSingle<ObjCPropertyDecl>()) {
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000442 DeclarationName TypoResult = Res.getLookupName();
Chris Lattner7f816522010-04-11 07:45:24 +0000443 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000444 << MemberName << QualType(OPT, 0) << TypoResult
445 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000446 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
447 Diag(Property->getLocation(), diag::note_previous_decl)
448 << Property->getDeclName();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000449 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc,
450 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000451 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000452
Chris Lattner7f816522010-04-11 07:45:24 +0000453 Diag(MemberLoc, diag::err_property_not_found)
454 << MemberName << QualType(OPT, 0);
455 if (Setter && !Getter)
456 Diag(Setter->getLocation(), diag::note_getter_unavailable)
457 << MemberName << BaseExpr->getSourceRange();
458 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000459}
460
461
462
John McCall60d7b3a2010-08-24 06:29:42 +0000463ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000464ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
465 IdentifierInfo &propertyName,
466 SourceLocation receiverNameLoc,
467 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000469 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000470 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
471 receiverNameLoc);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000472 if (IFace == 0) {
473 // If the "receiver" is 'super' in a method, handle it as an expression-like
474 // property reference.
475 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
476 if (receiverNamePtr->isStr("super")) {
477 if (CurMethod->isInstanceMethod()) {
478 QualType T =
479 Context.getObjCInterfaceType(CurMethod->getClassInterface());
480 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000481
482 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000483 /*BaseExpr*/0, &propertyName,
484 propertyNameLoc,
485 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Chris Lattnereb483eb2010-04-11 08:28:14 +0000488 // Otherwise, if this is a class method, try dispatching to our
489 // superclass.
490 IFace = CurMethod->getClassInterface()->getSuperClass();
491 }
492
493 if (IFace == 0) {
494 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
495 return ExprError();
496 }
497 }
498
499 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000500 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000501 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000502
503 // If this reference is in an @implementation, check for 'private' methods.
504 if (!Getter)
505 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
506 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000507 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000508 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000509
510 if (Getter) {
511 // FIXME: refactor/share with ActOnMemberReference().
512 // Check if we can reference this property.
513 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
514 return ExprError();
515 }
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Steve Naroff61f72cb2009-03-09 21:12:44 +0000517 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000518 Selector SetterSel =
519 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000520 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000521
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000522 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000523 if (!Setter) {
524 // If this reference is in an @implementation, also check for 'private'
525 // methods.
526 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
527 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000528 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000529 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000530 }
531 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000532 if (!Setter)
533 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000534
535 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
536 return ExprError();
537
538 if (Getter || Setter) {
539 QualType PType;
540
541 if (Getter)
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000542 PType = Getter->getSendResultType();
Steve Naroff61f72cb2009-03-09 21:12:44 +0000543 else {
544 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
545 E = Setter->param_end(); PI != E; ++PI)
546 PType = (*PI)->getType();
547 }
Fariborz Jahanian09105f52009-08-20 17:02:02 +0000548 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(
Mike Stump1eb44332009-09-09 15:08:12 +0000549 Getter, PType, Setter,
Steve Naroff61f72cb2009-03-09 21:12:44 +0000550 propertyNameLoc, IFace, receiverNameLoc));
551 }
552 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
553 << &propertyName << Context.getObjCInterfaceType(IFace));
554}
555
Douglas Gregor47bd5432010-04-14 02:46:37 +0000556Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000557 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000558 SourceLocation NameLoc,
559 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000560 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000561 ParsedType &ReceiverType) {
562 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000563
Douglas Gregor47bd5432010-04-14 02:46:37 +0000564 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000565 // messaging super. If the identifier is "super" and there is a
566 // trailing dot, it's an instance message.
567 if (IsSuper && S->isInObjcMethodScope())
568 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000569
570 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
571 LookupName(Result, S);
572
573 switch (Result.getResultKind()) {
574 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000575 // Normal name lookup didn't find anything. If we're in an
576 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000577 // FIXME: This is a hack. Ivar lookup should be part of normal
578 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000579 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
580 ObjCInterfaceDecl *ClassDeclared;
581 if (Method->getClassInterface()->lookupInstanceVariable(Name,
582 ClassDeclared))
583 return ObjCInstanceMessage;
584 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000585
Douglas Gregor47bd5432010-04-14 02:46:37 +0000586 // Break out; we'll perform typo correction below.
587 break;
588
589 case LookupResult::NotFoundInCurrentInstantiation:
590 case LookupResult::FoundOverloaded:
591 case LookupResult::FoundUnresolvedValue:
592 case LookupResult::Ambiguous:
593 Result.suppressDiagnostics();
594 return ObjCInstanceMessage;
595
596 case LookupResult::Found: {
597 // We found something. If it's a type, then we have a class
598 // message. Otherwise, it's an instance message.
599 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000600 QualType T;
601 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
602 T = Context.getObjCInterfaceType(Class);
603 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
604 T = Context.getTypeDeclType(Type);
605 else
606 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000607
Douglas Gregor1569f952010-04-21 20:38:13 +0000608 // We have a class message, and T is the type we're
609 // messaging. Build source-location information for it.
610 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000611 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000612 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000613 }
614 }
615
Douglas Gregoraaf87162010-04-14 20:04:41 +0000616 // Determine our typo-correction context.
617 CorrectTypoContext CTC = CTC_Expression;
618 if (ObjCMethodDecl *Method = getCurMethodDecl())
619 if (Method->getClassInterface() &&
620 Method->getClassInterface()->getSuperClass())
621 CTC = CTC_ObjCMessageReceiver;
622
623 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
624 if (Result.isSingleResult()) {
625 // If we found a declaration, correct when it refers to an Objective-C
626 // class.
627 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000628 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000629 Diag(NameLoc, diag::err_unknown_receiver_suggest)
630 << Name << Result.getLookupName()
631 << FixItHint::CreateReplacement(SourceRange(NameLoc),
632 ND->getNameAsString());
633 Diag(ND->getLocation(), diag::note_previous_decl)
634 << Corrected;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000635
Douglas Gregor1569f952010-04-21 20:38:13 +0000636 QualType T = Context.getObjCInterfaceType(Class);
637 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000638 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000639 return ObjCClassMessage;
640 }
641 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
642 Corrected.getAsIdentifierInfo()->isStr("super")) {
643 // If we've found the keyword "super", this is a send to super.
644 Diag(NameLoc, diag::err_unknown_receiver_suggest)
645 << Name << Corrected
646 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
647 Name = Corrected.getAsIdentifierInfo();
648 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000649 }
650 }
651
652 // Fall back: let the parser try to parse it as an instance message.
653 return ObjCInstanceMessage;
654}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000655
John McCall60d7b3a2010-08-24 06:29:42 +0000656ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000657 SourceLocation SuperLoc,
658 Selector Sel,
659 SourceLocation LBracLoc,
660 SourceLocation SelectorLoc,
661 SourceLocation RBracLoc,
662 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000663 // Determine whether we are inside a method or not.
664 ObjCMethodDecl *Method = getCurMethodDecl();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000665 if (!Method) {
666 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
667 return ExprError();
668 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000669
Douglas Gregorf95861a2010-04-21 20:01:04 +0000670 ObjCInterfaceDecl *Class = Method->getClassInterface();
671 if (!Class) {
672 Diag(SuperLoc, diag::error_no_super_class_message)
673 << Method->getDeclName();
674 return ExprError();
675 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000676
Douglas Gregorf95861a2010-04-21 20:01:04 +0000677 ObjCInterfaceDecl *Super = Class->getSuperClass();
678 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000679 // The current class does not have a superclass.
680 Diag(SuperLoc, diag::error_no_super_class) << Class->getIdentifier();
681 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000682 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000683
Douglas Gregorf95861a2010-04-21 20:01:04 +0000684 // We are in a method whose class has a superclass, so 'super'
685 // is acting as a keyword.
686 if (Method->isInstanceMethod()) {
687 // Since we are in an instance method, this is an instance
688 // message to the superclass instance.
689 QualType SuperTy = Context.getObjCInterfaceType(Super);
690 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +0000691 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000692 Sel, /*Method=*/0, LBracLoc, RBracLoc,
693 move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000694 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000695
696 // Since we are in a class method, this is a class message to
697 // the superclass.
698 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
699 Context.getObjCInterfaceType(Super),
Douglas Gregorf49bb082010-04-22 17:01:48 +0000700 SuperLoc, Sel, /*Method=*/0, LBracLoc, RBracLoc,
701 move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000702}
703
704/// \brief Build an Objective-C class message expression.
705///
706/// This routine takes care of both normal class messages and
707/// class messages to the superclass.
708///
709/// \param ReceiverTypeInfo Type source information that describes the
710/// receiver of this message. This may be NULL, in which case we are
711/// sending to the superclass and \p SuperLoc must be a valid source
712/// location.
713
714/// \param ReceiverType The type of the object receiving the
715/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
716/// type as that refers to. For a superclass send, this is the type of
717/// the superclass.
718///
719/// \param SuperLoc The location of the "super" keyword in a
720/// superclass message.
721///
722/// \param Sel The selector to which the message is being sent.
723///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000724/// \param Method The method that this class message is invoking, if
725/// already known.
726///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000727/// \param LBracLoc The location of the opening square bracket ']'.
728///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000729/// \param RBrac The location of the closing square bracket ']'.
730///
731/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +0000732ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000733 QualType ReceiverType,
734 SourceLocation SuperLoc,
735 Selector Sel,
736 ObjCMethodDecl *Method,
737 SourceLocation LBracLoc,
738 SourceLocation RBracLoc,
739 MultiExprArg ArgsIn) {
740 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +0000741 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +0000742 if (LBracLoc.isInvalid()) {
743 Diag(Loc, diag::err_missing_open_square_message_send)
744 << FixItHint::CreateInsertion(Loc, "[");
745 LBracLoc = Loc;
746 }
747
Douglas Gregor92e986e2010-04-22 16:44:27 +0000748 if (ReceiverType->isDependentType()) {
749 // If the receiver type is dependent, we can't type-check anything
750 // at this point. Build a dependent expression.
751 unsigned NumArgs = ArgsIn.size();
752 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
753 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
754 return Owned(ObjCMessageExpr::Create(Context, ReceiverType, LBracLoc,
755 ReceiverTypeInfo, Sel, /*Method=*/0,
756 Args, NumArgs, RBracLoc));
757 }
Chris Lattner15faee12010-04-12 05:38:43 +0000758
Douglas Gregor2725ca82010-04-21 19:57:20 +0000759 // Find the class to which we are sending this message.
760 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +0000761 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
762 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000763 Diag(Loc, diag::err_invalid_receiver_class_message)
764 << ReceiverType;
765 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +0000766 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000767 assert(Class && "We don't know which class we're messaging?");
768
769 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +0000770 if (!Method) {
771 if (Class->isForwardDecl()) {
772 // A forward class used in messaging is treated as a 'Class'
773 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
774 Method = LookupFactoryMethodInGlobalPool(Sel,
775 SourceRange(LBracLoc, RBracLoc));
776 if (Method)
777 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
778 << Method->getDeclName();
779 }
780 if (!Method)
781 Method = Class->lookupClassMethod(Sel);
782
783 // If we have an implementation in scope, check "private" methods.
784 if (!Method)
785 Method = LookupPrivateClassMethod(Sel, Class);
786
787 if (Method && DiagnoseUseOfDecl(Method, Loc))
788 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +0000789 }
Mike Stump1eb44332009-09-09 15:08:12 +0000790
Douglas Gregor2725ca82010-04-21 19:57:20 +0000791 // Check the argument types and determine the result type.
792 QualType ReturnType;
793 unsigned NumArgs = ArgsIn.size();
794 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
795 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
Douglas Gregorff331c12010-07-25 18:17:45 +0000796 LBracLoc, RBracLoc, ReturnType))
Douglas Gregor2725ca82010-04-21 19:57:20 +0000797 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +0000798
Douglas Gregor2725ca82010-04-21 19:57:20 +0000799 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000800 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +0000801 if (SuperLoc.isValid())
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000802 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
803 SuperLoc, /*IsInstanceSuper=*/false,
804 ReceiverType, Sel, Method, Args,
805 NumArgs, RBracLoc);
806 else
807 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
808 ReceiverTypeInfo, Sel, Method, Args,
809 NumArgs, RBracLoc);
810 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +0000811}
812
Douglas Gregor2725ca82010-04-21 19:57:20 +0000813// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +0000814// ArgExprs is optional - if it is present, the number of expressions
815// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +0000816ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +0000817 ParsedType Receiver,
818 Selector Sel,
819 SourceLocation LBracLoc,
820 SourceLocation SelectorLoc,
821 SourceLocation RBracLoc,
822 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000823 TypeSourceInfo *ReceiverTypeInfo;
824 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
825 if (ReceiverType.isNull())
826 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000827
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Douglas Gregor2725ca82010-04-21 19:57:20 +0000829 if (!ReceiverTypeInfo)
830 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
831
832 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000833 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Douglas Gregor39968ad2010-04-22 16:50:51 +0000834 LBracLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000835}
836
837/// \brief Build an Objective-C instance message expression.
838///
839/// This routine takes care of both normal instance messages and
840/// instance messages to the superclass instance.
841///
842/// \param Receiver The expression that computes the object that will
843/// receive this message. This may be empty, in which case we are
844/// sending to the superclass instance and \p SuperLoc must be a valid
845/// source location.
846///
847/// \param ReceiverType The (static) type of the object receiving the
848/// message. When a \p Receiver expression is provided, this is the
849/// same type as that expression. For a superclass instance send, this
850/// is a pointer to the type of the superclass.
851///
852/// \param SuperLoc The location of the "super" keyword in a
853/// superclass instance message.
854///
855/// \param Sel The selector to which the message is being sent.
856///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000857/// \param Method The method that this instance message is invoking, if
858/// already known.
859///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000860/// \param LBracLoc The location of the opening square bracket ']'.
861///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000862/// \param RBrac The location of the closing square bracket ']'.
863///
864/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +0000865ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000866 QualType ReceiverType,
867 SourceLocation SuperLoc,
868 Selector Sel,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000869 ObjCMethodDecl *Method,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000870 SourceLocation LBracLoc,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000871 SourceLocation RBracLoc,
872 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +0000873 // The location of the receiver.
874 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
875
876 if (LBracLoc.isInvalid()) {
877 Diag(Loc, diag::err_missing_open_square_message_send)
878 << FixItHint::CreateInsertion(Loc, "[");
879 LBracLoc = Loc;
880 }
881
Douglas Gregor2725ca82010-04-21 19:57:20 +0000882 // If we have a receiver expression, perform appropriate promotions
883 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000884 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000885 if (Receiver->isTypeDependent()) {
886 // If the receiver is type-dependent, we can't type-check anything
887 // at this point. Build a dependent expression.
888 unsigned NumArgs = ArgsIn.size();
889 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
890 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
891 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
892 LBracLoc, Receiver, Sel,
893 /*Method=*/0, Args, NumArgs,
894 RBracLoc));
895 }
896
Douglas Gregor2725ca82010-04-21 19:57:20 +0000897 // If necessary, apply function/array conversion to the receiver.
898 // C99 6.7.5.3p[7,8].
899 DefaultFunctionArrayLvalueConversion(Receiver);
900 ReceiverType = Receiver->getType();
901 }
902
Douglas Gregorf49bb082010-04-22 17:01:48 +0000903 if (!Method) {
904 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +0000905 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000906 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +0000907 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
908 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000909 SourceRange(LBracLoc, RBracLoc),
910 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +0000911 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000912 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000913 SourceRange(LBracLoc, RBracLoc),
914 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +0000915 } else if (ReceiverType->isObjCClassType() ||
916 ReceiverType->isObjCQualifiedClassType()) {
917 // Handle messages to Class.
918 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
919 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
920 // First check the public methods in the class interface.
921 Method = ClassDecl->lookupClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000922
Douglas Gregorf49bb082010-04-22 17:01:48 +0000923 if (!Method)
924 Method = LookupPrivateClassMethod(Sel, ClassDecl);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000925
Douglas Gregorf49bb082010-04-22 17:01:48 +0000926 // FIXME: if we still haven't found a method, we need to look in
927 // protocols (if we have qualifiers).
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000928 }
Douglas Gregorf49bb082010-04-22 17:01:48 +0000929 if (Method && DiagnoseUseOfDecl(Method, Loc))
930 return ExprError();
Fariborz Jahanian268bc8c2009-03-03 22:19:15 +0000931 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000932 if (!Method) {
Douglas Gregorf49bb082010-04-22 17:01:48 +0000933 // If not messaging 'self', look for any factory method named 'Sel'.
934 if (!Receiver || !isSelfExpr(Receiver)) {
935 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000936 SourceRange(LBracLoc, RBracLoc),
937 true);
Douglas Gregorf49bb082010-04-22 17:01:48 +0000938 if (!Method) {
939 // If no class (factory) method was found, check if an _instance_
940 // method of the same name exists in the root class only.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000941 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000942 SourceRange(LBracLoc, RBracLoc),
943 true);
Douglas Gregorf49bb082010-04-22 17:01:48 +0000944 if (Method)
945 if (const ObjCInterfaceDecl *ID =
946 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
947 if (ID->getSuperClass())
948 Diag(Loc, diag::warn_root_inst_method_not_found)
949 << Sel << SourceRange(LBracLoc, RBracLoc);
950 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000951 }
952 }
953 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000954 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +0000955 ObjCInterfaceDecl* ClassDecl = 0;
956
957 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
958 // long as one of the protocols implements the selector (if not, warn).
959 if (const ObjCObjectPointerType *QIdTy
960 = ReceiverType->getAsObjCQualifiedIdType()) {
961 // Search protocols for instance methods.
962 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
963 E = QIdTy->qual_end(); I != E; ++I) {
964 ObjCProtocolDecl *PDecl = *I;
965 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
966 break;
967 // Since we aren't supporting "Class<foo>", look for a class method.
968 if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
969 break;
970 }
971 } else if (const ObjCObjectPointerType *OCIType
972 = ReceiverType->getAsObjCInterfacePointerType()) {
973 // We allow sending a message to a pointer to an interface (an object).
974 ClassDecl = OCIType->getInterfaceDecl();
975 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
976 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +0000977 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +0000978 Method = ClassDecl->lookupInstanceMethod(Sel);
979
980 if (!Method) {
981 // Search protocol qualifiers.
982 for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(),
983 E = OCIType->qual_end(); QI != E; ++QI) {
984 if ((Method = (*QI)->lookupInstanceMethod(Sel)))
985 break;
986 }
987 }
988 if (!Method) {
989 // If we have implementations in scope, check "private" methods.
990 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
991
992 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
993 // If we still haven't found a method, look in the global pool. This
994 // behavior isn't very desirable, however we need it for GCC
995 // compatibility. FIXME: should we deviate??
996 if (OCIType->qual_empty()) {
997 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000998 SourceRange(LBracLoc, RBracLoc));
Douglas Gregorf49bb082010-04-22 17:01:48 +0000999 if (Method && !OCIType->getInterfaceDecl()->isForwardDecl())
1000 Diag(Loc, diag::warn_maynot_respond)
1001 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1002 }
1003 }
1004 }
1005 if (Method && DiagnoseUseOfDecl(Method, Loc))
1006 return ExprError();
1007 } else if (!Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001008 (ReceiverType->isPointerType() ||
1009 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001010 // Implicitly convert integers and pointers to 'id' but emit a warning.
1011 Diag(Loc, diag::warn_bad_receiver_type)
1012 << ReceiverType
1013 << Receiver->getSourceRange();
1014 if (ReceiverType->isPointerType())
1015 ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00001016 CK_BitCast);
John McCall404cd162010-11-13 01:35:44 +00001017 else {
1018 // TODO: specialized warning on null receivers?
1019 bool IsNull = Receiver->isNullPointerConstant(Context,
1020 Expr::NPC_ValueDependentIsNull);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001021 ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall404cd162010-11-13 01:35:44 +00001022 IsNull ? CK_NullToPointer : CK_IntegralToPointer);
1023 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001024 ReceiverType = Receiver->getType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00001025 }
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001026 else if (getLangOptions().CPlusPlus &&
1027 !PerformContextuallyConvertToObjCId(Receiver)) {
1028 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
1029 Receiver = ICE->getSubExpr();
1030 ReceiverType = Receiver->getType();
1031 }
John McCall9ae2f072010-08-23 23:25:46 +00001032 return BuildInstanceMessage(Receiver,
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00001033 ReceiverType,
1034 SuperLoc,
1035 Sel,
1036 Method,
1037 LBracLoc,
1038 RBracLoc,
1039 move(ArgsIn));
Douglas Gregorf49bb082010-04-22 17:01:48 +00001040 } else {
1041 // Reject other random receiver types (e.g. structs).
1042 Diag(Loc, diag::err_bad_receiver_type)
1043 << ReceiverType << Receiver->getSourceRange();
1044 return ExprError();
1045 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001046 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001047 }
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Douglas Gregor2725ca82010-04-21 19:57:20 +00001049 // Check the message arguments.
1050 unsigned NumArgs = ArgsIn.size();
1051 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1052 QualType ReturnType;
1053 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, false,
1054 LBracLoc, RBracLoc, ReturnType))
1055 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001056
1057 if (!ReturnType->isVoidType()) {
1058 if (RequireCompleteType(LBracLoc, ReturnType,
1059 diag::err_illegal_message_expr_incomplete_type))
1060 return ExprError();
1061 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001062
Douglas Gregor2725ca82010-04-21 19:57:20 +00001063 // Construct the appropriate ObjCMessageExpr instance.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001064 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001065 if (SuperLoc.isValid())
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001066 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
1067 SuperLoc, /*IsInstanceSuper=*/true,
1068 ReceiverType, Sel, Method,
1069 Args, NumArgs, RBracLoc);
1070 else
1071 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, Receiver,
1072 Sel, Method, Args, NumArgs, RBracLoc);
1073 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001074}
1075
1076// ActOnInstanceMessage - used for both unary and keyword messages.
1077// ArgExprs is optional - if it is present, the number of expressions
1078// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001079ExprResult Sema::ActOnInstanceMessage(Scope *S,
1080 Expr *Receiver,
1081 Selector Sel,
1082 SourceLocation LBracLoc,
1083 SourceLocation SelectorLoc,
1084 SourceLocation RBracLoc,
1085 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001086 if (!Receiver)
1087 return ExprError();
1088
John McCall9ae2f072010-08-23 23:25:46 +00001089 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001090 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1091 LBracLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001092}
Chris Lattnereca7be62008-04-07 05:30:13 +00001093