blob: b0f9b2cd246a592e047ca8d54108a5ad3eeba4c4 [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
14#include "Sema.h"
Chris Lattner7f816522010-04-11 07:45:24 +000015#include "Lookup.h"
Douglas Gregor688fc9b2010-04-21 23:24:10 +000016#include "SemaInit.h"
Chris Lattner85a932e2008-01-04 22:32:30 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000019#include "clang/AST/ExprObjC.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000020#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000021#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000022#include "clang/Lex/Preprocessor.h"
23
Chris Lattner85a932e2008-01-04 22:32:30 +000024using namespace clang;
25
Mike Stump1eb44332009-09-09 15:08:12 +000026Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
Chris Lattner39c28bb2009-02-18 06:48:40 +000027 ExprTy **strings,
Chris Lattner85a932e2008-01-04 22:32:30 +000028 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000029 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
30
Chris Lattnerf4b136f2009-02-18 06:13:04 +000031 // Most ObjC strings are formed out of a single piece. However, we *can*
32 // have strings formed out of multiple @ strings with multiple pptokens in
33 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
34 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner39c28bb2009-02-18 06:48:40 +000035 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000036
Chris Lattnerf4b136f2009-02-18 06:13:04 +000037 // If we have a multi-part string, merge it all together.
38 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000039 // Concatenate objc strings.
Chris Lattner39c28bb2009-02-18 06:48:40 +000040 llvm::SmallString<128> StrBuf;
41 llvm::SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner726e1682009-02-18 05:49:11 +000043 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000044 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000045
Chris Lattner39c28bb2009-02-18 06:48:40 +000046 // ObjC strings can't be wide.
Chris Lattnerf4b136f2009-02-18 06:13:04 +000047 if (S->isWide()) {
48 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
49 << S->getSourceRange();
50 return true;
51 }
Mike Stump1eb44332009-09-09 15:08:12 +000052
Chris Lattner39c28bb2009-02-18 06:48:40 +000053 // Get the string data.
54 StrBuf.append(S->getStrData(), S->getStrData()+S->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +000055
Chris Lattner39c28bb2009-02-18 06:48:40 +000056 // Get the locations of the string tokens.
57 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Mike Stump1eb44332009-09-09 15:08:12 +000058
Chris Lattner39c28bb2009-02-18 06:48:40 +000059 // Free the temporary string.
Ted Kremenek8189cde2009-02-07 01:47:29 +000060 S->Destroy(Context);
Chris Lattner85a932e2008-01-04 22:32:30 +000061 }
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattner39c28bb2009-02-18 06:48:40 +000063 // Create the aggregate string with the appropriate content and location
64 // information.
65 S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(), false,
Chris Lattner2085fd62009-02-18 06:40:38 +000066 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000067 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000068 }
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner69039812009-02-18 06:01:06 +000070 // Verify that this composite string is acceptable for ObjC strings.
71 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000072 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000073
74 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000075 // the NSString interface is seen in this translation unit. Note: We
76 // don't use NSConstantString, since the runtime team considers this
77 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000078 QualType Ty = Context.getObjCConstantStringInterface();
79 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000080 Ty = Context.getObjCObjectPointerType(Ty);
Fariborz Jahanian8a437762010-04-23 23:19:04 +000081 } else if (getLangOptions().NoConstantCFStrings) {
82 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
83 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
84 LookupOrdinaryName);
85 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
86 Context.setObjCConstantStringInterface(StrIF);
87 Ty = Context.getObjCConstantStringInterface();
88 Ty = Context.getObjCObjectPointerType(Ty);
89 } else {
90 // If there is no NSConstantString interface defined then treat this
91 // as error and recover from it.
92 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
93 << S->getSourceRange();
94 Ty = Context.getObjCIdType();
95 }
Chris Lattner13fd7e52008-06-21 21:44:18 +000096 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +000097 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +000098 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
99 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000100 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
101 Context.setObjCConstantStringInterface(StrIF);
102 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000103 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000104 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000105 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000106 // strings as untyped objects and let the runtime figure it out later.
107 Ty = Context.getObjCIdType();
108 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000109 }
Mike Stump1eb44332009-09-09 15:08:12 +0000110
Chris Lattnerf4b136f2009-02-18 06:13:04 +0000111 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +0000112}
113
Mike Stump1eb44332009-09-09 15:08:12 +0000114Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000115 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000116 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000117 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000118 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000119 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000120 StrTy = Context.DependentTy;
121 else {
122 std::string Str;
123 Context.getObjCEncodingForType(EncodedType, Str);
124
125 // The type of @encode is the same as the type of the corresponding string,
126 // which is an array type.
127 StrTy = Context.CharTy;
128 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000129 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000130 StrTy.addConst();
131 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
132 ArrayType::Normal, 0);
133 }
Mike Stump1eb44332009-09-09 15:08:12 +0000134
Douglas Gregor81d34662010-04-20 15:39:42 +0000135 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000136}
137
Chris Lattner85a932e2008-01-04 22:32:30 +0000138Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
139 SourceLocation EncodeLoc,
140 SourceLocation LParenLoc,
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000141 TypeTy *ty,
Chris Lattner85a932e2008-01-04 22:32:30 +0000142 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000143 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000144 TypeSourceInfo *TInfo;
145 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
146 if (!TInfo)
147 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
148 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000149
Douglas Gregor81d34662010-04-20 15:39:42 +0000150 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000151}
152
153Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
154 SourceLocation AtLoc,
155 SourceLocation SelLoc,
156 SourceLocation LParenLoc,
157 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000158 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian835ed7f2009-08-22 21:13:55 +0000159 SourceRange(LParenLoc, RParenLoc), false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000160 if (!Method)
161 Method = LookupFactoryMethodInGlobalPool(Sel,
162 SourceRange(LParenLoc, RParenLoc));
163 if (!Method)
164 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
165
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000166 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
167 = ReferencedSelectors.find(Sel);
168 if (Pos == ReferencedSelectors.end())
169 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
170
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000171 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000172 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000173}
174
175Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
176 SourceLocation AtLoc,
177 SourceLocation ProtoLoc,
178 SourceLocation LParenLoc,
179 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000180 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000181 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000182 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000183 return true;
184 }
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000186 QualType Ty = Context.getObjCProtoType();
187 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000188 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000189 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000190 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000191}
192
Mike Stump1eb44332009-09-09 15:08:12 +0000193bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
194 Selector Sel, ObjCMethodDecl *Method,
Chris Lattner077bf5e2008-11-24 03:33:13 +0000195 bool isClassMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000196 SourceLocation lbrac, SourceLocation rbrac,
Mike Stump1eb44332009-09-09 15:08:12 +0000197 QualType &ReturnType) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000198 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000199 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000200 for (unsigned i = 0; i != NumArgs; i++) {
201 if (Args[i]->isTypeDependent())
202 continue;
203
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000204 DefaultArgumentPromotion(Args[i]);
Douglas Gregor92e986e2010-04-22 16:44:27 +0000205 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000206
Chris Lattner077bf5e2008-11-24 03:33:13 +0000207 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
208 diag::warn_inst_method_not_found;
209 Diag(lbrac, DiagID)
210 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000211 ReturnType = Context.getObjCIdType();
212 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000213 }
Mike Stump1eb44332009-09-09 15:08:12 +0000214
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000215 ReturnType = Method->getSendResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000216
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000217 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000218 // Method might have more arguments than selector indicates. This is due
219 // to addition of c-style arguments in method.
220 if (Method->param_size() > Sel.getNumArgs())
221 NumNamedArgs = Method->param_size();
222 // FIXME. This need be cleaned up.
223 if (NumArgs < NumNamedArgs) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000224 Diag(lbrac, diag::err_typecheck_call_too_few_args) << 2
225 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000226 return false;
227 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000228
Chris Lattner312531a2009-04-12 08:11:20 +0000229 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000230 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000231 // We can't do any type-checking on a type-dependent argument.
232 if (Args[i]->isTypeDependent())
233 continue;
234
Chris Lattner85a932e2008-01-04 22:32:30 +0000235 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000236
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000237 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000238 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000239
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000240 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
241 Param->getType(),
242 PDiag(diag::err_call_incomplete_argument)
243 << argExpr->getSourceRange()))
244 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000245
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000246 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
247 OwningExprResult ArgE = PerformCopyInitialization(Entity,
248 SourceLocation(),
249 Owned(argExpr->Retain()));
250 if (ArgE.isInvalid())
251 IsError = true;
252 else
253 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000254 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000255
256 // Promote additional arguments to variadic methods.
257 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000258 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
259 if (Args[i]->isTypeDependent())
260 continue;
261
Chris Lattner40378332010-05-16 04:01:30 +0000262 IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
Douglas Gregor92e986e2010-04-22 16:44:27 +0000263 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000264 } else {
265 // Check for extra arguments to non-variadic methods.
266 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000267 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000268 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000269 << 2 /*method*/ << NumNamedArgs << NumArgs
270 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000271 << SourceRange(Args[NumNamedArgs]->getLocStart(),
272 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000273 }
274 }
275
Douglas Gregor2725ca82010-04-21 19:57:20 +0000276 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000277 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000278}
279
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000280bool Sema::isSelfExpr(Expr *RExpr) {
281 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
282 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
283 return true;
284 return false;
285}
286
Steve Narofff1afaf62009-02-26 15:55:06 +0000287// Helper method for ActOnClassMethod/ActOnInstanceMethod.
288// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000289// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000290// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000291ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000292 ObjCInterfaceDecl *ClassDecl) {
293 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000294 // lookup in class and all superclasses
295 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000296 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000297 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000298
Steve Naroff5609ec02009-03-08 18:56:13 +0000299 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000300 if (!Method)
301 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000302
Steve Naroff5609ec02009-03-08 18:56:13 +0000303 // Before we give up, check if the selector is an instance method.
304 // But only in the root. This matches gcc's behaviour and what the
305 // runtime expects.
306 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000307 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000308 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000309 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000310 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000311 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
312 }
Mike Stump1eb44332009-09-09 15:08:12 +0000313
Steve Naroff5609ec02009-03-08 18:56:13 +0000314 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000315 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000316 return Method;
317}
318
319ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
320 ObjCInterfaceDecl *ClassDecl) {
321 ObjCMethodDecl *Method = 0;
322 while (ClassDecl && !Method) {
323 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000324 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000325 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000326
Steve Naroff5609ec02009-03-08 18:56:13 +0000327 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000328 if (!Method)
329 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000330 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000331 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000332 return Method;
333}
334
Chris Lattner7f816522010-04-11 07:45:24 +0000335/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
336/// objective C interface. This is a property reference expression.
337Action::OwningExprResult Sema::
338HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000339 Expr *BaseExpr, DeclarationName MemberName,
340 SourceLocation MemberLoc) {
Chris Lattner7f816522010-04-11 07:45:24 +0000341 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
342 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
343 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
344
345 // Search for a declared property first.
346 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
347 // Check whether we can reference this property.
348 if (DiagnoseUseOfDecl(PD, MemberLoc))
349 return ExprError();
350 QualType ResTy = PD->getType();
351 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
352 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
353 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000354 ResTy = Getter->getSendResultType();
Chris Lattner7f816522010-04-11 07:45:24 +0000355 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
356 MemberLoc, BaseExpr));
357 }
358 // Check protocols on qualified interfaces.
359 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
360 E = OPT->qual_end(); I != E; ++I)
361 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
362 // Check whether we can reference this property.
363 if (DiagnoseUseOfDecl(PD, MemberLoc))
364 return ExprError();
365
366 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
367 MemberLoc, BaseExpr));
368 }
369 // If that failed, look for an "implicit" property by seeing if the nullary
370 // selector is implemented.
371
372 // FIXME: The logic for looking up nullary and unary selectors should be
373 // shared with the code in ActOnInstanceMessage.
374
375 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
376 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
377
378 // If this reference is in an @implementation, check for 'private' methods.
379 if (!Getter)
380 Getter = IFace->lookupPrivateInstanceMethod(Sel);
381
382 // Look through local category implementations associated with the class.
383 if (!Getter)
384 Getter = IFace->getCategoryInstanceMethod(Sel);
385 if (Getter) {
386 // Check if we can reference this property.
387 if (DiagnoseUseOfDecl(Getter, MemberLoc))
388 return ExprError();
389 }
390 // If we found a getter then this may be a valid dot-reference, we
391 // will look for the matching setter, in case it is needed.
392 Selector SetterSel =
393 SelectorTable::constructSetterName(PP.getIdentifierTable(),
394 PP.getSelectorTable(), Member);
395 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
396 if (!Setter) {
397 // If this reference is in an @implementation, also check for 'private'
398 // methods.
399 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
400 }
401 // Look through local category implementations associated with the class.
402 if (!Setter)
403 Setter = IFace->getCategoryInstanceMethod(SetterSel);
404
405 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
406 return ExprError();
407
408 if (Getter) {
409 QualType PType;
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000410 PType = Getter->getSendResultType();
Chris Lattner7f816522010-04-11 07:45:24 +0000411 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
412 Setter, MemberLoc, BaseExpr));
413 }
414
415 // Attempt to correct for typos in property names.
416 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000417 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
Chris Lattner7f816522010-04-11 07:45:24 +0000418 Res.getAsSingle<ObjCPropertyDecl>()) {
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000419 DeclarationName TypoResult = Res.getLookupName();
Chris Lattner7f816522010-04-11 07:45:24 +0000420 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000421 << MemberName << QualType(OPT, 0) << TypoResult
422 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000423 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
424 Diag(Property->getLocation(), diag::note_previous_decl)
425 << Property->getDeclName();
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000426 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc);
Chris Lattner7f816522010-04-11 07:45:24 +0000427 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000428
Chris Lattner7f816522010-04-11 07:45:24 +0000429 Diag(MemberLoc, diag::err_property_not_found)
430 << MemberName << QualType(OPT, 0);
431 if (Setter && !Getter)
432 Diag(Setter->getLocation(), diag::note_getter_unavailable)
433 << MemberName << BaseExpr->getSourceRange();
434 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000435}
436
437
438
Chris Lattnereb483eb2010-04-11 08:28:14 +0000439Action::OwningExprResult Sema::
440ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
441 IdentifierInfo &propertyName,
442 SourceLocation receiverNameLoc,
443 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000445 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000446 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
447 receiverNameLoc);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000448 if (IFace == 0) {
449 // If the "receiver" is 'super' in a method, handle it as an expression-like
450 // property reference.
451 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
452 if (receiverNamePtr->isStr("super")) {
453 if (CurMethod->isInstanceMethod()) {
454 QualType T =
455 Context.getObjCInterfaceType(CurMethod->getClassInterface());
456 T = Context.getObjCObjectPointerType(T);
457 Expr *SuperExpr = new (Context) ObjCSuperExpr(receiverNameLoc, T);
458
459 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
460 SuperExpr, &propertyName,
461 propertyNameLoc);
462 }
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Chris Lattnereb483eb2010-04-11 08:28:14 +0000464 // Otherwise, if this is a class method, try dispatching to our
465 // superclass.
466 IFace = CurMethod->getClassInterface()->getSuperClass();
467 }
468
469 if (IFace == 0) {
470 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
471 return ExprError();
472 }
473 }
474
475 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000476 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000477 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000478
479 // If this reference is in an @implementation, check for 'private' methods.
480 if (!Getter)
481 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
482 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000483 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000484 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000485
486 if (Getter) {
487 // FIXME: refactor/share with ActOnMemberReference().
488 // Check if we can reference this property.
489 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
490 return ExprError();
491 }
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Steve Naroff61f72cb2009-03-09 21:12:44 +0000493 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000494 Selector SetterSel =
495 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000496 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000497
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000498 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000499 if (!Setter) {
500 // If this reference is in an @implementation, also check for 'private'
501 // methods.
502 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
503 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000504 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000505 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000506 }
507 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000508 if (!Setter)
509 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000510
511 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
512 return ExprError();
513
514 if (Getter || Setter) {
515 QualType PType;
516
517 if (Getter)
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000518 PType = Getter->getSendResultType();
Steve Naroff61f72cb2009-03-09 21:12:44 +0000519 else {
520 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
521 E = Setter->param_end(); PI != E; ++PI)
522 PType = (*PI)->getType();
523 }
Fariborz Jahanian09105f52009-08-20 17:02:02 +0000524 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(
Mike Stump1eb44332009-09-09 15:08:12 +0000525 Getter, PType, Setter,
Steve Naroff61f72cb2009-03-09 21:12:44 +0000526 propertyNameLoc, IFace, receiverNameLoc));
527 }
528 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
529 << &propertyName << Context.getObjCInterfaceType(IFace));
530}
531
Douglas Gregor47bd5432010-04-14 02:46:37 +0000532Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000533 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000534 SourceLocation NameLoc,
535 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000536 bool HasTrailingDot,
537 TypeTy *&ReceiverType) {
538 ReceiverType = 0;
539
Douglas Gregor47bd5432010-04-14 02:46:37 +0000540 // If the identifier is "super" and there is no trailing dot, we're
541 // messaging super.
542 if (IsSuper && !HasTrailingDot && S->isInObjcMethodScope())
543 return ObjCSuperMessage;
544
545 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
546 LookupName(Result, S);
547
548 switch (Result.getResultKind()) {
549 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000550 // Normal name lookup didn't find anything. If we're in an
551 // Objective-C method, look for ivars. If we find one, we're done!
552 // FIXME: This is a hack. Ivar lookup should be part of normal lookup.
553 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
554 ObjCInterfaceDecl *ClassDeclared;
555 if (Method->getClassInterface()->lookupInstanceVariable(Name,
556 ClassDeclared))
557 return ObjCInstanceMessage;
558 }
559
Douglas Gregor47bd5432010-04-14 02:46:37 +0000560 // Break out; we'll perform typo correction below.
561 break;
562
563 case LookupResult::NotFoundInCurrentInstantiation:
564 case LookupResult::FoundOverloaded:
565 case LookupResult::FoundUnresolvedValue:
566 case LookupResult::Ambiguous:
567 Result.suppressDiagnostics();
568 return ObjCInstanceMessage;
569
570 case LookupResult::Found: {
571 // We found something. If it's a type, then we have a class
572 // message. Otherwise, it's an instance message.
573 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000574 QualType T;
575 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
576 T = Context.getObjCInterfaceType(Class);
577 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
578 T = Context.getTypeDeclType(Type);
579 else
580 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000581
Douglas Gregor1569f952010-04-21 20:38:13 +0000582 // We have a class message, and T is the type we're
583 // messaging. Build source-location information for it.
584 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
585 ReceiverType = CreateLocInfoType(T, TSInfo).getAsOpaquePtr();
586 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000587 }
588 }
589
Douglas Gregoraaf87162010-04-14 20:04:41 +0000590 // Determine our typo-correction context.
591 CorrectTypoContext CTC = CTC_Expression;
592 if (ObjCMethodDecl *Method = getCurMethodDecl())
593 if (Method->getClassInterface() &&
594 Method->getClassInterface()->getSuperClass())
595 CTC = CTC_ObjCMessageReceiver;
596
597 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
598 if (Result.isSingleResult()) {
599 // If we found a declaration, correct when it refers to an Objective-C
600 // class.
601 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000602 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000603 Diag(NameLoc, diag::err_unknown_receiver_suggest)
604 << Name << Result.getLookupName()
605 << FixItHint::CreateReplacement(SourceRange(NameLoc),
606 ND->getNameAsString());
607 Diag(ND->getLocation(), diag::note_previous_decl)
608 << Corrected;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000609
Douglas Gregor1569f952010-04-21 20:38:13 +0000610 QualType T = Context.getObjCInterfaceType(Class);
611 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
612 ReceiverType = CreateLocInfoType(T, TSInfo).getAsOpaquePtr();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000613 return ObjCClassMessage;
614 }
615 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
616 Corrected.getAsIdentifierInfo()->isStr("super")) {
617 // If we've found the keyword "super", this is a send to super.
618 Diag(NameLoc, diag::err_unknown_receiver_suggest)
619 << Name << Corrected
620 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
621 Name = Corrected.getAsIdentifierInfo();
622 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000623 }
624 }
625
626 // Fall back: let the parser try to parse it as an instance message.
627 return ObjCInstanceMessage;
628}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000629
Douglas Gregor2725ca82010-04-21 19:57:20 +0000630Sema::OwningExprResult Sema::ActOnSuperMessage(Scope *S,
631 SourceLocation SuperLoc,
632 Selector Sel,
633 SourceLocation LBracLoc,
634 SourceLocation SelectorLoc,
635 SourceLocation RBracLoc,
636 MultiExprArg Args) {
637 // Determine whether we are inside a method or not.
638 ObjCMethodDecl *Method = getCurMethodDecl();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000639 if (!Method) {
640 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
641 return ExprError();
642 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000643
Douglas Gregorf95861a2010-04-21 20:01:04 +0000644 ObjCInterfaceDecl *Class = Method->getClassInterface();
645 if (!Class) {
646 Diag(SuperLoc, diag::error_no_super_class_message)
647 << Method->getDeclName();
648 return ExprError();
649 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000650
Douglas Gregorf95861a2010-04-21 20:01:04 +0000651 ObjCInterfaceDecl *Super = Class->getSuperClass();
652 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000653 // The current class does not have a superclass.
654 Diag(SuperLoc, diag::error_no_super_class) << Class->getIdentifier();
655 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000656 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000657
Douglas Gregorf95861a2010-04-21 20:01:04 +0000658 // We are in a method whose class has a superclass, so 'super'
659 // is acting as a keyword.
660 if (Method->isInstanceMethod()) {
661 // Since we are in an instance method, this is an instance
662 // message to the superclass instance.
663 QualType SuperTy = Context.getObjCInterfaceType(Super);
664 SuperTy = Context.getObjCObjectPointerType(SuperTy);
665 return BuildInstanceMessage(ExprArg(*this), SuperTy, SuperLoc,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000666 Sel, /*Method=*/0, LBracLoc, RBracLoc,
667 move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000668 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000669
670 // Since we are in a class method, this is a class message to
671 // the superclass.
672 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
673 Context.getObjCInterfaceType(Super),
Douglas Gregorf49bb082010-04-22 17:01:48 +0000674 SuperLoc, Sel, /*Method=*/0, LBracLoc, RBracLoc,
675 move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000676}
677
678/// \brief Build an Objective-C class message expression.
679///
680/// This routine takes care of both normal class messages and
681/// class messages to the superclass.
682///
683/// \param ReceiverTypeInfo Type source information that describes the
684/// receiver of this message. This may be NULL, in which case we are
685/// sending to the superclass and \p SuperLoc must be a valid source
686/// location.
687
688/// \param ReceiverType The type of the object receiving the
689/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
690/// type as that refers to. For a superclass send, this is the type of
691/// the superclass.
692///
693/// \param SuperLoc The location of the "super" keyword in a
694/// superclass message.
695///
696/// \param Sel The selector to which the message is being sent.
697///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000698/// \param Method The method that this class message is invoking, if
699/// already known.
700///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000701/// \param LBracLoc The location of the opening square bracket ']'.
702///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000703/// \param RBrac The location of the closing square bracket ']'.
704///
705/// \param Args The message arguments.
706Sema::OwningExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
707 QualType ReceiverType,
708 SourceLocation SuperLoc,
709 Selector Sel,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000710 ObjCMethodDecl *Method,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000711 SourceLocation LBracLoc,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000712 SourceLocation RBracLoc,
713 MultiExprArg ArgsIn) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000714 if (ReceiverType->isDependentType()) {
715 // If the receiver type is dependent, we can't type-check anything
716 // at this point. Build a dependent expression.
717 unsigned NumArgs = ArgsIn.size();
718 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
719 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
720 return Owned(ObjCMessageExpr::Create(Context, ReceiverType, LBracLoc,
721 ReceiverTypeInfo, Sel, /*Method=*/0,
722 Args, NumArgs, RBracLoc));
723 }
Chris Lattner15faee12010-04-12 05:38:43 +0000724
Douglas Gregor2725ca82010-04-21 19:57:20 +0000725 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Abramo Bagnarabd054db2010-05-20 10:00:11 +0000726 : ReceiverTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Douglas Gregor2725ca82010-04-21 19:57:20 +0000728 // Find the class to which we are sending this message.
729 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +0000730 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
731 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000732 Diag(Loc, diag::err_invalid_receiver_class_message)
733 << ReceiverType;
734 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +0000735 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000736 assert(Class && "We don't know which class we're messaging?");
737
738 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +0000739 if (!Method) {
740 if (Class->isForwardDecl()) {
741 // A forward class used in messaging is treated as a 'Class'
742 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
743 Method = LookupFactoryMethodInGlobalPool(Sel,
744 SourceRange(LBracLoc, RBracLoc));
745 if (Method)
746 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
747 << Method->getDeclName();
748 }
749 if (!Method)
750 Method = Class->lookupClassMethod(Sel);
751
752 // If we have an implementation in scope, check "private" methods.
753 if (!Method)
754 Method = LookupPrivateClassMethod(Sel, Class);
755
756 if (Method && DiagnoseUseOfDecl(Method, Loc))
757 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +0000758 }
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Douglas Gregor2725ca82010-04-21 19:57:20 +0000760 // Check the argument types and determine the result type.
761 QualType ReturnType;
762 unsigned NumArgs = ArgsIn.size();
763 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
764 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
765 LBracLoc, RBracLoc, ReturnType)) {
766 for (unsigned I = 0; I != NumArgs; ++I)
767 Args[I]->Destroy(Context);
768 return ExprError();
769 }
Ted Kremenek4df728e2008-06-24 15:50:53 +0000770
Douglas Gregor2725ca82010-04-21 19:57:20 +0000771 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000772 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +0000773 if (SuperLoc.isValid())
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000774 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
775 SuperLoc, /*IsInstanceSuper=*/false,
776 ReceiverType, Sel, Method, Args,
777 NumArgs, RBracLoc);
778 else
779 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
780 ReceiverTypeInfo, Sel, Method, Args,
781 NumArgs, RBracLoc);
782 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +0000783}
784
Douglas Gregor2725ca82010-04-21 19:57:20 +0000785// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +0000786// ArgExprs is optional - if it is present, the number of expressions
787// is obtained from Sel.getNumArgs().
Douglas Gregor2725ca82010-04-21 19:57:20 +0000788Sema::OwningExprResult Sema::ActOnClassMessage(Scope *S,
789 TypeTy *Receiver,
790 Selector Sel,
791 SourceLocation LBracLoc,
792 SourceLocation SelectorLoc,
793 SourceLocation RBracLoc,
794 MultiExprArg Args) {
795 TypeSourceInfo *ReceiverTypeInfo;
796 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
797 if (ReceiverType.isNull())
798 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Mike Stump1eb44332009-09-09 15:08:12 +0000800
Douglas Gregor2725ca82010-04-21 19:57:20 +0000801 if (!ReceiverTypeInfo)
802 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
803
804 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000805 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Douglas Gregor39968ad2010-04-22 16:50:51 +0000806 LBracLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000807}
808
809/// \brief Build an Objective-C instance message expression.
810///
811/// This routine takes care of both normal instance messages and
812/// instance messages to the superclass instance.
813///
814/// \param Receiver The expression that computes the object that will
815/// receive this message. This may be empty, in which case we are
816/// sending to the superclass instance and \p SuperLoc must be a valid
817/// source location.
818///
819/// \param ReceiverType The (static) type of the object receiving the
820/// message. When a \p Receiver expression is provided, this is the
821/// same type as that expression. For a superclass instance send, this
822/// is a pointer to the type of the superclass.
823///
824/// \param SuperLoc The location of the "super" keyword in a
825/// superclass instance message.
826///
827/// \param Sel The selector to which the message is being sent.
828///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000829/// \param Method The method that this instance message is invoking, if
830/// already known.
831///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000832/// \param LBracLoc The location of the opening square bracket ']'.
833///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000834/// \param RBrac The location of the closing square bracket ']'.
835///
836/// \param Args The message arguments.
837Sema::OwningExprResult Sema::BuildInstanceMessage(ExprArg ReceiverE,
838 QualType ReceiverType,
839 SourceLocation SuperLoc,
840 Selector Sel,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000841 ObjCMethodDecl *Method,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000842 SourceLocation LBracLoc,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000843 SourceLocation RBracLoc,
844 MultiExprArg ArgsIn) {
845 // If we have a receiver expression, perform appropriate promotions
846 // and determine receiver type.
847 Expr *Receiver = ReceiverE.takeAs<Expr>();
848 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000849 if (Receiver->isTypeDependent()) {
850 // If the receiver is type-dependent, we can't type-check anything
851 // at this point. Build a dependent expression.
852 unsigned NumArgs = ArgsIn.size();
853 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
854 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
855 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
856 LBracLoc, Receiver, Sel,
857 /*Method=*/0, Args, NumArgs,
858 RBracLoc));
859 }
860
Douglas Gregor2725ca82010-04-21 19:57:20 +0000861 // If necessary, apply function/array conversion to the receiver.
862 // C99 6.7.5.3p[7,8].
863 DefaultFunctionArrayLvalueConversion(Receiver);
864 ReceiverType = Receiver->getType();
865 }
866
867 // The location of the receiver.
868 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000869
Douglas Gregorf49bb082010-04-22 17:01:48 +0000870 if (!Method) {
871 // Handle messages to id.
872 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType() ||
873 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
874 Method = LookupInstanceMethodInGlobalPool(Sel,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000875 SourceRange(LBracLoc, RBracLoc));
Douglas Gregorf49bb082010-04-22 17:01:48 +0000876 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000877 Method = LookupFactoryMethodInGlobalPool(Sel,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000878 SourceRange(LBracLoc, RBracLoc));
879 } else if (ReceiverType->isObjCClassType() ||
880 ReceiverType->isObjCQualifiedClassType()) {
881 // Handle messages to Class.
882 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
883 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
884 // First check the public methods in the class interface.
885 Method = ClassDecl->lookupClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Douglas Gregorf49bb082010-04-22 17:01:48 +0000887 if (!Method)
888 Method = LookupPrivateClassMethod(Sel, ClassDecl);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000889
Douglas Gregorf49bb082010-04-22 17:01:48 +0000890 // FIXME: if we still haven't found a method, we need to look in
891 // protocols (if we have qualifiers).
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000892 }
Douglas Gregorf49bb082010-04-22 17:01:48 +0000893 if (Method && DiagnoseUseOfDecl(Method, Loc))
894 return ExprError();
Fariborz Jahanian268bc8c2009-03-03 22:19:15 +0000895 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000896 if (!Method) {
Douglas Gregorf49bb082010-04-22 17:01:48 +0000897 // If not messaging 'self', look for any factory method named 'Sel'.
898 if (!Receiver || !isSelfExpr(Receiver)) {
899 Method = LookupFactoryMethodInGlobalPool(Sel,
900 SourceRange(LBracLoc, RBracLoc));
901 if (!Method) {
902 // If no class (factory) method was found, check if an _instance_
903 // method of the same name exists in the root class only.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000904 Method = LookupInstanceMethodInGlobalPool(Sel,
905 SourceRange(LBracLoc, RBracLoc));
Douglas Gregorf49bb082010-04-22 17:01:48 +0000906 if (Method)
907 if (const ObjCInterfaceDecl *ID =
908 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
909 if (ID->getSuperClass())
910 Diag(Loc, diag::warn_root_inst_method_not_found)
911 << Sel << SourceRange(LBracLoc, RBracLoc);
912 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000913 }
914 }
915 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000916 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +0000917 ObjCInterfaceDecl* ClassDecl = 0;
918
919 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
920 // long as one of the protocols implements the selector (if not, warn).
921 if (const ObjCObjectPointerType *QIdTy
922 = ReceiverType->getAsObjCQualifiedIdType()) {
923 // Search protocols for instance methods.
924 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
925 E = QIdTy->qual_end(); I != E; ++I) {
926 ObjCProtocolDecl *PDecl = *I;
927 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
928 break;
929 // Since we aren't supporting "Class<foo>", look for a class method.
930 if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
931 break;
932 }
933 } else if (const ObjCObjectPointerType *OCIType
934 = ReceiverType->getAsObjCInterfacePointerType()) {
935 // We allow sending a message to a pointer to an interface (an object).
936 ClassDecl = OCIType->getInterfaceDecl();
937 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
938 // faster than the following method (which can do *many* linear searches).
939 // The idea is to add class info to InstanceMethodPool.
940 Method = ClassDecl->lookupInstanceMethod(Sel);
941
942 if (!Method) {
943 // Search protocol qualifiers.
944 for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(),
945 E = OCIType->qual_end(); QI != E; ++QI) {
946 if ((Method = (*QI)->lookupInstanceMethod(Sel)))
947 break;
948 }
949 }
950 if (!Method) {
951 // If we have implementations in scope, check "private" methods.
952 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
953
954 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
955 // If we still haven't found a method, look in the global pool. This
956 // behavior isn't very desirable, however we need it for GCC
957 // compatibility. FIXME: should we deviate??
958 if (OCIType->qual_empty()) {
959 Method = LookupInstanceMethodInGlobalPool(Sel,
960 SourceRange(LBracLoc, RBracLoc));
961 if (Method && !OCIType->getInterfaceDecl()->isForwardDecl())
962 Diag(Loc, diag::warn_maynot_respond)
963 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
964 }
965 }
966 }
967 if (Method && DiagnoseUseOfDecl(Method, Loc))
968 return ExprError();
969 } else if (!Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +0000970 (ReceiverType->isPointerType() ||
971 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +0000972 // Implicitly convert integers and pointers to 'id' but emit a warning.
973 Diag(Loc, diag::warn_bad_receiver_type)
974 << ReceiverType
975 << Receiver->getSourceRange();
976 if (ReceiverType->isPointerType())
977 ImpCastExprToType(Receiver, Context.getObjCIdType(),
978 CastExpr::CK_BitCast);
979 else
980 ImpCastExprToType(Receiver, Context.getObjCIdType(),
981 CastExpr::CK_IntegralToPointer);
982 ReceiverType = Receiver->getType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +0000983 }
Fariborz Jahanian3ba60612010-05-13 17:19:25 +0000984 else if (getLangOptions().CPlusPlus &&
985 !PerformContextuallyConvertToObjCId(Receiver)) {
986 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
987 Receiver = ICE->getSubExpr();
988 ReceiverType = Receiver->getType();
989 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +0000990 return BuildInstanceMessage(Owned(Receiver),
991 ReceiverType,
992 SuperLoc,
993 Sel,
994 Method,
995 LBracLoc,
996 RBracLoc,
997 move(ArgsIn));
Douglas Gregorf49bb082010-04-22 17:01:48 +0000998 } else {
999 // Reject other random receiver types (e.g. structs).
1000 Diag(Loc, diag::err_bad_receiver_type)
1001 << ReceiverType << Receiver->getSourceRange();
1002 return ExprError();
1003 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001004 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001005 }
Mike Stump1eb44332009-09-09 15:08:12 +00001006
Douglas Gregor2725ca82010-04-21 19:57:20 +00001007 // Check the message arguments.
1008 unsigned NumArgs = ArgsIn.size();
1009 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1010 QualType ReturnType;
1011 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, false,
1012 LBracLoc, RBracLoc, ReturnType))
1013 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001014
1015 if (!ReturnType->isVoidType()) {
1016 if (RequireCompleteType(LBracLoc, ReturnType,
1017 diag::err_illegal_message_expr_incomplete_type))
1018 return ExprError();
1019 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001020
Douglas Gregor2725ca82010-04-21 19:57:20 +00001021 // Construct the appropriate ObjCMessageExpr instance.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001022 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001023 if (SuperLoc.isValid())
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001024 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
1025 SuperLoc, /*IsInstanceSuper=*/true,
1026 ReceiverType, Sel, Method,
1027 Args, NumArgs, RBracLoc);
1028 else
1029 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, Receiver,
1030 Sel, Method, Args, NumArgs, RBracLoc);
1031 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001032}
1033
1034// ActOnInstanceMessage - used for both unary and keyword messages.
1035// ArgExprs is optional - if it is present, the number of expressions
1036// is obtained from Sel.getNumArgs().
1037Sema::OwningExprResult Sema::ActOnInstanceMessage(Scope *S,
1038 ExprArg ReceiverE,
1039 Selector Sel,
1040 SourceLocation LBracLoc,
1041 SourceLocation SelectorLoc,
1042 SourceLocation RBracLoc,
1043 MultiExprArg Args) {
1044 Expr *Receiver = static_cast<Expr *>(ReceiverE.get());
1045 if (!Receiver)
1046 return ExprError();
1047
1048 return BuildInstanceMessage(move(ReceiverE), Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001049 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1050 LBracLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001051}
Chris Lattnereca7be62008-04-07 05:30:13 +00001052