blob: 055edd971005f8d3a55b39a4fa4374a042066882 [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) {
80 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
81 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
82 LookupOrdinaryName);
83 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
84 Context.setObjCConstantStringInterface(StrIF);
85 Ty = Context.getObjCConstantStringInterface();
86 Ty = Context.getObjCObjectPointerType(Ty);
87 } else {
88 // If there is no NSConstantString interface defined then treat this
89 // as error and recover from it.
90 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
91 << S->getSourceRange();
92 Ty = Context.getObjCIdType();
93 }
Chris Lattner13fd7e52008-06-21 21:44:18 +000094 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +000095 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +000096 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
97 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +000098 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
99 Context.setObjCConstantStringInterface(StrIF);
100 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000101 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000102 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000103 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000104 // strings as untyped objects and let the runtime figure it out later.
105 Ty = Context.getObjCIdType();
106 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000107 }
Mike Stump1eb44332009-09-09 15:08:12 +0000108
Chris Lattnerf4b136f2009-02-18 06:13:04 +0000109 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +0000110}
111
Mike Stump1eb44332009-09-09 15:08:12 +0000112Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000113 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000114 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000115 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000116 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000117 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000118 StrTy = Context.DependentTy;
119 else {
120 std::string Str;
121 Context.getObjCEncodingForType(EncodedType, Str);
122
123 // The type of @encode is the same as the type of the corresponding string,
124 // which is an array type.
125 StrTy = Context.CharTy;
126 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000127 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000128 StrTy.addConst();
129 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
130 ArrayType::Normal, 0);
131 }
Mike Stump1eb44332009-09-09 15:08:12 +0000132
Douglas Gregor81d34662010-04-20 15:39:42 +0000133 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000134}
135
John McCallf312b1e2010-08-26 23:41:50 +0000136ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
137 SourceLocation EncodeLoc,
138 SourceLocation LParenLoc,
139 ParsedType ty,
140 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000141 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000142 TypeSourceInfo *TInfo;
143 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
144 if (!TInfo)
145 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
146 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000147
Douglas Gregor81d34662010-04-20 15:39:42 +0000148 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000149}
150
John McCallf312b1e2010-08-26 23:41:50 +0000151ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
152 SourceLocation AtLoc,
153 SourceLocation SelLoc,
154 SourceLocation LParenLoc,
155 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000156 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000157 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000158 if (!Method)
159 Method = LookupFactoryMethodInGlobalPool(Sel,
160 SourceRange(LParenLoc, RParenLoc));
161 if (!Method)
162 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
163
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000164 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
165 = ReferencedSelectors.find(Sel);
166 if (Pos == ReferencedSelectors.end())
167 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
168
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000169 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000170 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000171}
172
John McCallf312b1e2010-08-26 23:41:50 +0000173ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
174 SourceLocation AtLoc,
175 SourceLocation ProtoLoc,
176 SourceLocation LParenLoc,
177 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000178 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000179 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000180 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000181 return true;
182 }
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000184 QualType Ty = Context.getObjCProtoType();
185 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000186 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000187 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000188 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000189}
190
Mike Stump1eb44332009-09-09 15:08:12 +0000191bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
192 Selector Sel, ObjCMethodDecl *Method,
Chris Lattner077bf5e2008-11-24 03:33:13 +0000193 bool isClassMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000194 SourceLocation lbrac, SourceLocation rbrac,
Mike Stump1eb44332009-09-09 15:08:12 +0000195 QualType &ReturnType) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000196 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000197 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000198 for (unsigned i = 0; i != NumArgs; i++) {
199 if (Args[i]->isTypeDependent())
200 continue;
201
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000202 DefaultArgumentPromotion(Args[i]);
Douglas Gregor92e986e2010-04-22 16:44:27 +0000203 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000204
Chris Lattner077bf5e2008-11-24 03:33:13 +0000205 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
206 diag::warn_inst_method_not_found;
207 Diag(lbrac, DiagID)
208 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000209 ReturnType = Context.getObjCIdType();
210 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000211 }
Mike Stump1eb44332009-09-09 15:08:12 +0000212
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000213 ReturnType = Method->getSendResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000215 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000216 // Method might have more arguments than selector indicates. This is due
217 // to addition of c-style arguments in method.
218 if (Method->param_size() > Sel.getNumArgs())
219 NumNamedArgs = Method->param_size();
220 // FIXME. This need be cleaned up.
221 if (NumArgs < NumNamedArgs) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000222 Diag(lbrac, diag::err_typecheck_call_too_few_args) << 2
223 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000224 return false;
225 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000226
Chris Lattner312531a2009-04-12 08:11:20 +0000227 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000228 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000229 // We can't do any type-checking on a type-dependent argument.
230 if (Args[i]->isTypeDependent())
231 continue;
232
Chris Lattner85a932e2008-01-04 22:32:30 +0000233 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000234
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000235 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000236 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000237
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000238 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
239 Param->getType(),
240 PDiag(diag::err_call_incomplete_argument)
241 << argExpr->getSourceRange()))
242 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000243
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000244 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
245 Param);
John McCall60d7b3a2010-08-24 06:29:42 +0000246 ExprResult ArgE = PerformCopyInitialization(Entity,
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000247 SourceLocation(),
248 Owned(argExpr->Retain()));
249 if (ArgE.isInvalid())
250 IsError = true;
251 else
252 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000253 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000254
255 // Promote additional arguments to variadic methods.
256 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000257 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
258 if (Args[i]->isTypeDependent())
259 continue;
260
Chris Lattner40378332010-05-16 04:01:30 +0000261 IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
Douglas Gregor92e986e2010-04-22 16:44:27 +0000262 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000263 } else {
264 // Check for extra arguments to non-variadic methods.
265 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000266 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000267 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000268 << 2 /*method*/ << NumNamedArgs << NumArgs
269 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000270 << SourceRange(Args[NumNamedArgs]->getLocStart(),
271 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000272 }
273 }
274
Douglas Gregor2725ca82010-04-21 19:57:20 +0000275 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000276 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000277}
278
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000279bool Sema::isSelfExpr(Expr *RExpr) {
280 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
281 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
282 return true;
283 return false;
284}
285
Steve Narofff1afaf62009-02-26 15:55:06 +0000286// Helper method for ActOnClassMethod/ActOnInstanceMethod.
287// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000288// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000289// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000290ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000291 ObjCInterfaceDecl *ClassDecl) {
292 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000293 // lookup in class and all superclasses
294 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000295 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000296 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Steve Naroff5609ec02009-03-08 18:56:13 +0000298 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000299 if (!Method)
300 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000301
Steve Naroff5609ec02009-03-08 18:56:13 +0000302 // Before we give up, check if the selector is an instance method.
303 // But only in the root. This matches gcc's behaviour and what the
304 // runtime expects.
305 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000306 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000307 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000308 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000309 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000310 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
311 }
Mike Stump1eb44332009-09-09 15:08:12 +0000312
Steve Naroff5609ec02009-03-08 18:56:13 +0000313 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000314 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000315 return Method;
316}
317
318ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
319 ObjCInterfaceDecl *ClassDecl) {
320 ObjCMethodDecl *Method = 0;
321 while (ClassDecl && !Method) {
322 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000323 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000324 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Steve Naroff5609ec02009-03-08 18:56:13 +0000326 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000327 if (!Method)
328 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000329 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000330 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000331 return Method;
332}
333
Chris Lattner7f816522010-04-11 07:45:24 +0000334/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
335/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000336ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000337HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000338 Expr *BaseExpr, DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000339 SourceLocation MemberLoc,
340 SourceLocation SuperLoc, QualType SuperType,
341 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000342 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
343 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
344 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
345
346 // Search for a declared property first.
347 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
348 // Check whether we can reference this property.
349 if (DiagnoseUseOfDecl(PD, MemberLoc))
350 return ExprError();
351 QualType ResTy = PD->getType();
352 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
353 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
354 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000355 ResTy = Getter->getSendResultType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000356 if (Super)
357 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
358 MemberLoc,
359 SuperLoc, SuperType));
360 else
361 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
362 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000363 }
364 // Check protocols on qualified interfaces.
365 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
366 E = OPT->qual_end(); I != E; ++I)
367 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
368 // Check whether we can reference this property.
369 if (DiagnoseUseOfDecl(PD, MemberLoc))
370 return ExprError();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000371 if (Super)
Chris Lattner7f816522010-04-11 07:45:24 +0000372 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000373 MemberLoc,
374 SuperLoc, SuperType));
375 else
376 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
377 MemberLoc,
378 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000379 }
380 // If that failed, look for an "implicit" property by seeing if the nullary
381 // selector is implemented.
382
383 // FIXME: The logic for looking up nullary and unary selectors should be
384 // shared with the code in ActOnInstanceMessage.
385
386 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
387 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
388
389 // If this reference is in an @implementation, check for 'private' methods.
390 if (!Getter)
391 Getter = IFace->lookupPrivateInstanceMethod(Sel);
392
393 // Look through local category implementations associated with the class.
394 if (!Getter)
395 Getter = IFace->getCategoryInstanceMethod(Sel);
396 if (Getter) {
397 // Check if we can reference this property.
398 if (DiagnoseUseOfDecl(Getter, MemberLoc))
399 return ExprError();
400 }
401 // If we found a getter then this may be a valid dot-reference, we
402 // will look for the matching setter, in case it is needed.
403 Selector SetterSel =
404 SelectorTable::constructSetterName(PP.getIdentifierTable(),
405 PP.getSelectorTable(), Member);
406 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
407 if (!Setter) {
408 // If this reference is in an @implementation, also check for 'private'
409 // methods.
410 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
411 }
412 // Look through local category implementations associated with the class.
413 if (!Setter)
414 Setter = IFace->getCategoryInstanceMethod(SetterSel);
415
416 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
417 return ExprError();
418
419 if (Getter) {
420 QualType PType;
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000421 PType = Getter->getSendResultType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000422 if (Super)
423 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
424 Setter, MemberLoc,
425 SuperLoc, SuperType));
426 else
427 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
428 Setter, MemberLoc,
429 BaseExpr));
430
Chris Lattner7f816522010-04-11 07:45:24 +0000431 }
432
433 // Attempt to correct for typos in property names.
434 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000435 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
Chris Lattner7f816522010-04-11 07:45:24 +0000436 Res.getAsSingle<ObjCPropertyDecl>()) {
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000437 DeclarationName TypoResult = Res.getLookupName();
Chris Lattner7f816522010-04-11 07:45:24 +0000438 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000439 << MemberName << QualType(OPT, 0) << TypoResult
440 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000441 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
442 Diag(Property->getLocation(), diag::note_previous_decl)
443 << Property->getDeclName();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000444 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc,
445 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000446 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000447
Chris Lattner7f816522010-04-11 07:45:24 +0000448 Diag(MemberLoc, diag::err_property_not_found)
449 << MemberName << QualType(OPT, 0);
450 if (Setter && !Getter)
451 Diag(Setter->getLocation(), diag::note_getter_unavailable)
452 << MemberName << BaseExpr->getSourceRange();
453 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000454}
455
456
457
John McCall60d7b3a2010-08-24 06:29:42 +0000458ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000459ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
460 IdentifierInfo &propertyName,
461 SourceLocation receiverNameLoc,
462 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000464 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000465 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
466 receiverNameLoc);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000467 if (IFace == 0) {
468 // If the "receiver" is 'super' in a method, handle it as an expression-like
469 // property reference.
470 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
471 if (receiverNamePtr->isStr("super")) {
472 if (CurMethod->isInstanceMethod()) {
473 QualType T =
474 Context.getObjCInterfaceType(CurMethod->getClassInterface());
475 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000476
477 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000478 /*BaseExpr*/0, &propertyName,
479 propertyNameLoc,
480 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000481 }
Mike Stump1eb44332009-09-09 15:08:12 +0000482
Chris Lattnereb483eb2010-04-11 08:28:14 +0000483 // Otherwise, if this is a class method, try dispatching to our
484 // superclass.
485 IFace = CurMethod->getClassInterface()->getSuperClass();
486 }
487
488 if (IFace == 0) {
489 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
490 return ExprError();
491 }
492 }
493
494 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000495 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000496 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000497
498 // If this reference is in an @implementation, check for 'private' methods.
499 if (!Getter)
500 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
501 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000502 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000503 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000504
505 if (Getter) {
506 // FIXME: refactor/share with ActOnMemberReference().
507 // Check if we can reference this property.
508 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
509 return ExprError();
510 }
Mike Stump1eb44332009-09-09 15:08:12 +0000511
Steve Naroff61f72cb2009-03-09 21:12:44 +0000512 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000513 Selector SetterSel =
514 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000515 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000516
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000517 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000518 if (!Setter) {
519 // If this reference is in an @implementation, also check for 'private'
520 // methods.
521 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
522 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000523 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000524 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000525 }
526 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000527 if (!Setter)
528 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000529
530 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
531 return ExprError();
532
533 if (Getter || Setter) {
534 QualType PType;
535
536 if (Getter)
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000537 PType = Getter->getSendResultType();
Steve Naroff61f72cb2009-03-09 21:12:44 +0000538 else {
539 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
540 E = Setter->param_end(); PI != E; ++PI)
541 PType = (*PI)->getType();
542 }
Fariborz Jahanian09105f52009-08-20 17:02:02 +0000543 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(
Mike Stump1eb44332009-09-09 15:08:12 +0000544 Getter, PType, Setter,
Steve Naroff61f72cb2009-03-09 21:12:44 +0000545 propertyNameLoc, IFace, receiverNameLoc));
546 }
547 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
548 << &propertyName << Context.getObjCInterfaceType(IFace));
549}
550
Douglas Gregor47bd5432010-04-14 02:46:37 +0000551Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000552 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000553 SourceLocation NameLoc,
554 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000555 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000556 ParsedType &ReceiverType) {
557 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000558
Douglas Gregor47bd5432010-04-14 02:46:37 +0000559 // If the identifier is "super" and there is no trailing dot, we're
560 // messaging super.
561 if (IsSuper && !HasTrailingDot && S->isInObjcMethodScope())
562 return ObjCSuperMessage;
563
564 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
565 LookupName(Result, S);
566
567 switch (Result.getResultKind()) {
568 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000569 // Normal name lookup didn't find anything. If we're in an
570 // Objective-C method, look for ivars. If we find one, we're done!
571 // FIXME: This is a hack. Ivar lookup should be part of normal lookup.
572 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
573 ObjCInterfaceDecl *ClassDeclared;
574 if (Method->getClassInterface()->lookupInstanceVariable(Name,
575 ClassDeclared))
576 return ObjCInstanceMessage;
577 }
578
Douglas Gregor47bd5432010-04-14 02:46:37 +0000579 // Break out; we'll perform typo correction below.
580 break;
581
582 case LookupResult::NotFoundInCurrentInstantiation:
583 case LookupResult::FoundOverloaded:
584 case LookupResult::FoundUnresolvedValue:
585 case LookupResult::Ambiguous:
586 Result.suppressDiagnostics();
587 return ObjCInstanceMessage;
588
589 case LookupResult::Found: {
590 // We found something. If it's a type, then we have a class
591 // message. Otherwise, it's an instance message.
592 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000593 QualType T;
594 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
595 T = Context.getObjCInterfaceType(Class);
596 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
597 T = Context.getTypeDeclType(Type);
598 else
599 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000600
Douglas Gregor1569f952010-04-21 20:38:13 +0000601 // We have a class message, and T is the type we're
602 // messaging. Build source-location information for it.
603 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000604 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000605 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000606 }
607 }
608
Douglas Gregoraaf87162010-04-14 20:04:41 +0000609 // Determine our typo-correction context.
610 CorrectTypoContext CTC = CTC_Expression;
611 if (ObjCMethodDecl *Method = getCurMethodDecl())
612 if (Method->getClassInterface() &&
613 Method->getClassInterface()->getSuperClass())
614 CTC = CTC_ObjCMessageReceiver;
615
616 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
617 if (Result.isSingleResult()) {
618 // If we found a declaration, correct when it refers to an Objective-C
619 // class.
620 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000621 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000622 Diag(NameLoc, diag::err_unknown_receiver_suggest)
623 << Name << Result.getLookupName()
624 << FixItHint::CreateReplacement(SourceRange(NameLoc),
625 ND->getNameAsString());
626 Diag(ND->getLocation(), diag::note_previous_decl)
627 << Corrected;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000628
Douglas Gregor1569f952010-04-21 20:38:13 +0000629 QualType T = Context.getObjCInterfaceType(Class);
630 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000631 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000632 return ObjCClassMessage;
633 }
634 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
635 Corrected.getAsIdentifierInfo()->isStr("super")) {
636 // If we've found the keyword "super", this is a send to super.
637 Diag(NameLoc, diag::err_unknown_receiver_suggest)
638 << Name << Corrected
639 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
640 Name = Corrected.getAsIdentifierInfo();
641 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000642 }
643 }
644
645 // Fall back: let the parser try to parse it as an instance message.
646 return ObjCInstanceMessage;
647}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000648
John McCall60d7b3a2010-08-24 06:29:42 +0000649ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000650 SourceLocation SuperLoc,
651 Selector Sel,
652 SourceLocation LBracLoc,
653 SourceLocation SelectorLoc,
654 SourceLocation RBracLoc,
655 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000656 // Determine whether we are inside a method or not.
657 ObjCMethodDecl *Method = getCurMethodDecl();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000658 if (!Method) {
659 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
660 return ExprError();
661 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000662
Douglas Gregorf95861a2010-04-21 20:01:04 +0000663 ObjCInterfaceDecl *Class = Method->getClassInterface();
664 if (!Class) {
665 Diag(SuperLoc, diag::error_no_super_class_message)
666 << Method->getDeclName();
667 return ExprError();
668 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000669
Douglas Gregorf95861a2010-04-21 20:01:04 +0000670 ObjCInterfaceDecl *Super = Class->getSuperClass();
671 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000672 // The current class does not have a superclass.
673 Diag(SuperLoc, diag::error_no_super_class) << Class->getIdentifier();
674 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000675 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000676
Douglas Gregorf95861a2010-04-21 20:01:04 +0000677 // We are in a method whose class has a superclass, so 'super'
678 // is acting as a keyword.
679 if (Method->isInstanceMethod()) {
680 // Since we are in an instance method, this is an instance
681 // message to the superclass instance.
682 QualType SuperTy = Context.getObjCInterfaceType(Super);
683 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +0000684 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000685 Sel, /*Method=*/0, LBracLoc, RBracLoc,
686 move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000687 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000688
689 // Since we are in a class method, this is a class message to
690 // the superclass.
691 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
692 Context.getObjCInterfaceType(Super),
Douglas Gregorf49bb082010-04-22 17:01:48 +0000693 SuperLoc, Sel, /*Method=*/0, LBracLoc, RBracLoc,
694 move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000695}
696
697/// \brief Build an Objective-C class message expression.
698///
699/// This routine takes care of both normal class messages and
700/// class messages to the superclass.
701///
702/// \param ReceiverTypeInfo Type source information that describes the
703/// receiver of this message. This may be NULL, in which case we are
704/// sending to the superclass and \p SuperLoc must be a valid source
705/// location.
706
707/// \param ReceiverType The type of the object receiving the
708/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
709/// type as that refers to. For a superclass send, this is the type of
710/// the superclass.
711///
712/// \param SuperLoc The location of the "super" keyword in a
713/// superclass message.
714///
715/// \param Sel The selector to which the message is being sent.
716///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000717/// \param Method The method that this class message is invoking, if
718/// already known.
719///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000720/// \param LBracLoc The location of the opening square bracket ']'.
721///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000722/// \param RBrac The location of the closing square bracket ']'.
723///
724/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +0000725ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000726 QualType ReceiverType,
727 SourceLocation SuperLoc,
728 Selector Sel,
729 ObjCMethodDecl *Method,
730 SourceLocation LBracLoc,
731 SourceLocation RBracLoc,
732 MultiExprArg ArgsIn) {
733 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +0000734 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +0000735 if (LBracLoc.isInvalid()) {
736 Diag(Loc, diag::err_missing_open_square_message_send)
737 << FixItHint::CreateInsertion(Loc, "[");
738 LBracLoc = Loc;
739 }
740
Douglas Gregor92e986e2010-04-22 16:44:27 +0000741 if (ReceiverType->isDependentType()) {
742 // If the receiver type is dependent, we can't type-check anything
743 // at this point. Build a dependent expression.
744 unsigned NumArgs = ArgsIn.size();
745 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
746 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
747 return Owned(ObjCMessageExpr::Create(Context, ReceiverType, LBracLoc,
748 ReceiverTypeInfo, Sel, /*Method=*/0,
749 Args, NumArgs, RBracLoc));
750 }
Chris Lattner15faee12010-04-12 05:38:43 +0000751
Douglas Gregor2725ca82010-04-21 19:57:20 +0000752 // Find the class to which we are sending this message.
753 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +0000754 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
755 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000756 Diag(Loc, diag::err_invalid_receiver_class_message)
757 << ReceiverType;
758 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +0000759 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000760 assert(Class && "We don't know which class we're messaging?");
761
762 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +0000763 if (!Method) {
764 if (Class->isForwardDecl()) {
765 // A forward class used in messaging is treated as a 'Class'
766 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
767 Method = LookupFactoryMethodInGlobalPool(Sel,
768 SourceRange(LBracLoc, RBracLoc));
769 if (Method)
770 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
771 << Method->getDeclName();
772 }
773 if (!Method)
774 Method = Class->lookupClassMethod(Sel);
775
776 // If we have an implementation in scope, check "private" methods.
777 if (!Method)
778 Method = LookupPrivateClassMethod(Sel, Class);
779
780 if (Method && DiagnoseUseOfDecl(Method, Loc))
781 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +0000782 }
Mike Stump1eb44332009-09-09 15:08:12 +0000783
Douglas Gregor2725ca82010-04-21 19:57:20 +0000784 // Check the argument types and determine the result type.
785 QualType ReturnType;
786 unsigned NumArgs = ArgsIn.size();
787 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
788 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
Douglas Gregorff331c12010-07-25 18:17:45 +0000789 LBracLoc, RBracLoc, ReturnType))
Douglas Gregor2725ca82010-04-21 19:57:20 +0000790 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +0000791
Douglas Gregor2725ca82010-04-21 19:57:20 +0000792 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000793 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +0000794 if (SuperLoc.isValid())
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000795 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
796 SuperLoc, /*IsInstanceSuper=*/false,
797 ReceiverType, Sel, Method, Args,
798 NumArgs, RBracLoc);
799 else
800 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
801 ReceiverTypeInfo, Sel, Method, Args,
802 NumArgs, RBracLoc);
803 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +0000804}
805
Douglas Gregor2725ca82010-04-21 19:57:20 +0000806// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +0000807// ArgExprs is optional - if it is present, the number of expressions
808// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +0000809ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +0000810 ParsedType Receiver,
811 Selector Sel,
812 SourceLocation LBracLoc,
813 SourceLocation SelectorLoc,
814 SourceLocation RBracLoc,
815 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000816 TypeSourceInfo *ReceiverTypeInfo;
817 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
818 if (ReceiverType.isNull())
819 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000820
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Douglas Gregor2725ca82010-04-21 19:57:20 +0000822 if (!ReceiverTypeInfo)
823 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
824
825 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000826 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Douglas Gregor39968ad2010-04-22 16:50:51 +0000827 LBracLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000828}
829
830/// \brief Build an Objective-C instance message expression.
831///
832/// This routine takes care of both normal instance messages and
833/// instance messages to the superclass instance.
834///
835/// \param Receiver The expression that computes the object that will
836/// receive this message. This may be empty, in which case we are
837/// sending to the superclass instance and \p SuperLoc must be a valid
838/// source location.
839///
840/// \param ReceiverType The (static) type of the object receiving the
841/// message. When a \p Receiver expression is provided, this is the
842/// same type as that expression. For a superclass instance send, this
843/// is a pointer to the type of the superclass.
844///
845/// \param SuperLoc The location of the "super" keyword in a
846/// superclass instance message.
847///
848/// \param Sel The selector to which the message is being sent.
849///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000850/// \param Method The method that this instance message is invoking, if
851/// already known.
852///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000853/// \param LBracLoc The location of the opening square bracket ']'.
854///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000855/// \param RBrac The location of the closing square bracket ']'.
856///
857/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +0000858ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000859 QualType ReceiverType,
860 SourceLocation SuperLoc,
861 Selector Sel,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000862 ObjCMethodDecl *Method,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000863 SourceLocation LBracLoc,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000864 SourceLocation RBracLoc,
865 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +0000866 // The location of the receiver.
867 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
868
869 if (LBracLoc.isInvalid()) {
870 Diag(Loc, diag::err_missing_open_square_message_send)
871 << FixItHint::CreateInsertion(Loc, "[");
872 LBracLoc = Loc;
873 }
874
Douglas Gregor2725ca82010-04-21 19:57:20 +0000875 // If we have a receiver expression, perform appropriate promotions
876 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000877 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000878 if (Receiver->isTypeDependent()) {
879 // If the receiver is type-dependent, we can't type-check anything
880 // at this point. Build a dependent expression.
881 unsigned NumArgs = ArgsIn.size();
882 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
883 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
884 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
885 LBracLoc, Receiver, Sel,
886 /*Method=*/0, Args, NumArgs,
887 RBracLoc));
888 }
889
Douglas Gregor2725ca82010-04-21 19:57:20 +0000890 // If necessary, apply function/array conversion to the receiver.
891 // C99 6.7.5.3p[7,8].
892 DefaultFunctionArrayLvalueConversion(Receiver);
893 ReceiverType = Receiver->getType();
894 }
895
Douglas Gregorf49bb082010-04-22 17:01:48 +0000896 if (!Method) {
897 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +0000898 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000899 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +0000900 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
901 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000902 SourceRange(LBracLoc, RBracLoc),
903 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +0000904 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000905 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000906 SourceRange(LBracLoc, RBracLoc),
907 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +0000908 } else if (ReceiverType->isObjCClassType() ||
909 ReceiverType->isObjCQualifiedClassType()) {
910 // Handle messages to Class.
911 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
912 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
913 // First check the public methods in the class interface.
914 Method = ClassDecl->lookupClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000915
Douglas Gregorf49bb082010-04-22 17:01:48 +0000916 if (!Method)
917 Method = LookupPrivateClassMethod(Sel, ClassDecl);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000918
Douglas Gregorf49bb082010-04-22 17:01:48 +0000919 // FIXME: if we still haven't found a method, we need to look in
920 // protocols (if we have qualifiers).
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000921 }
Douglas Gregorf49bb082010-04-22 17:01:48 +0000922 if (Method && DiagnoseUseOfDecl(Method, Loc))
923 return ExprError();
Fariborz Jahanian268bc8c2009-03-03 22:19:15 +0000924 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000925 if (!Method) {
Douglas Gregorf49bb082010-04-22 17:01:48 +0000926 // If not messaging 'self', look for any factory method named 'Sel'.
927 if (!Receiver || !isSelfExpr(Receiver)) {
928 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000929 SourceRange(LBracLoc, RBracLoc),
930 true);
Douglas Gregorf49bb082010-04-22 17:01:48 +0000931 if (!Method) {
932 // If no class (factory) method was found, check if an _instance_
933 // method of the same name exists in the root class only.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000934 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000935 SourceRange(LBracLoc, RBracLoc),
936 true);
Douglas Gregorf49bb082010-04-22 17:01:48 +0000937 if (Method)
938 if (const ObjCInterfaceDecl *ID =
939 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
940 if (ID->getSuperClass())
941 Diag(Loc, diag::warn_root_inst_method_not_found)
942 << Sel << SourceRange(LBracLoc, RBracLoc);
943 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000944 }
945 }
946 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000947 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +0000948 ObjCInterfaceDecl* ClassDecl = 0;
949
950 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
951 // long as one of the protocols implements the selector (if not, warn).
952 if (const ObjCObjectPointerType *QIdTy
953 = ReceiverType->getAsObjCQualifiedIdType()) {
954 // Search protocols for instance methods.
955 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
956 E = QIdTy->qual_end(); I != E; ++I) {
957 ObjCProtocolDecl *PDecl = *I;
958 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
959 break;
960 // Since we aren't supporting "Class<foo>", look for a class method.
961 if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
962 break;
963 }
964 } else if (const ObjCObjectPointerType *OCIType
965 = ReceiverType->getAsObjCInterfacePointerType()) {
966 // We allow sending a message to a pointer to an interface (an object).
967 ClassDecl = OCIType->getInterfaceDecl();
968 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
969 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +0000970 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +0000971 Method = ClassDecl->lookupInstanceMethod(Sel);
972
973 if (!Method) {
974 // Search protocol qualifiers.
975 for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(),
976 E = OCIType->qual_end(); QI != E; ++QI) {
977 if ((Method = (*QI)->lookupInstanceMethod(Sel)))
978 break;
979 }
980 }
981 if (!Method) {
982 // If we have implementations in scope, check "private" methods.
983 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
984
985 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
986 // If we still haven't found a method, look in the global pool. This
987 // behavior isn't very desirable, however we need it for GCC
988 // compatibility. FIXME: should we deviate??
989 if (OCIType->qual_empty()) {
990 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000991 SourceRange(LBracLoc, RBracLoc));
Douglas Gregorf49bb082010-04-22 17:01:48 +0000992 if (Method && !OCIType->getInterfaceDecl()->isForwardDecl())
993 Diag(Loc, diag::warn_maynot_respond)
994 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
995 }
996 }
997 }
998 if (Method && DiagnoseUseOfDecl(Method, Loc))
999 return ExprError();
1000 } else if (!Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001001 (ReceiverType->isPointerType() ||
1002 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001003 // Implicitly convert integers and pointers to 'id' but emit a warning.
1004 Diag(Loc, diag::warn_bad_receiver_type)
1005 << ReceiverType
1006 << Receiver->getSourceRange();
1007 if (ReceiverType->isPointerType())
1008 ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00001009 CK_BitCast);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001010 else
1011 ImpCastExprToType(Receiver, Context.getObjCIdType(),
John McCall2de56d12010-08-25 11:45:40 +00001012 CK_IntegralToPointer);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001013 ReceiverType = Receiver->getType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00001014 }
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001015 else if (getLangOptions().CPlusPlus &&
1016 !PerformContextuallyConvertToObjCId(Receiver)) {
1017 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
1018 Receiver = ICE->getSubExpr();
1019 ReceiverType = Receiver->getType();
1020 }
John McCall9ae2f072010-08-23 23:25:46 +00001021 return BuildInstanceMessage(Receiver,
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00001022 ReceiverType,
1023 SuperLoc,
1024 Sel,
1025 Method,
1026 LBracLoc,
1027 RBracLoc,
1028 move(ArgsIn));
Douglas Gregorf49bb082010-04-22 17:01:48 +00001029 } else {
1030 // Reject other random receiver types (e.g. structs).
1031 Diag(Loc, diag::err_bad_receiver_type)
1032 << ReceiverType << Receiver->getSourceRange();
1033 return ExprError();
1034 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001035 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001036 }
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Douglas Gregor2725ca82010-04-21 19:57:20 +00001038 // Check the message arguments.
1039 unsigned NumArgs = ArgsIn.size();
1040 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1041 QualType ReturnType;
1042 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, false,
1043 LBracLoc, RBracLoc, ReturnType))
1044 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001045
1046 if (!ReturnType->isVoidType()) {
1047 if (RequireCompleteType(LBracLoc, ReturnType,
1048 diag::err_illegal_message_expr_incomplete_type))
1049 return ExprError();
1050 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001051
Douglas Gregor2725ca82010-04-21 19:57:20 +00001052 // Construct the appropriate ObjCMessageExpr instance.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001053 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001054 if (SuperLoc.isValid())
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001055 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
1056 SuperLoc, /*IsInstanceSuper=*/true,
1057 ReceiverType, Sel, Method,
1058 Args, NumArgs, RBracLoc);
1059 else
1060 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, Receiver,
1061 Sel, Method, Args, NumArgs, RBracLoc);
1062 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001063}
1064
1065// ActOnInstanceMessage - used for both unary and keyword messages.
1066// ArgExprs is optional - if it is present, the number of expressions
1067// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001068ExprResult Sema::ActOnInstanceMessage(Scope *S,
1069 Expr *Receiver,
1070 Selector Sel,
1071 SourceLocation LBracLoc,
1072 SourceLocation SelectorLoc,
1073 SourceLocation RBracLoc,
1074 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001075 if (!Receiver)
1076 return ExprError();
1077
John McCall9ae2f072010-08-23 23:25:46 +00001078 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001079 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1080 LBracLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001081}
Chris Lattnereca7be62008-04-07 05:30:13 +00001082