blob: e6884bac333bcebb979a63139d1a064898371c7b [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);
Chris Lattner13fd7e52008-06-21 21:44:18 +000081 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +000082 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +000083 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
84 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +000085 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
86 Context.setObjCConstantStringInterface(StrIF);
87 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +000088 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +000089 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +000090 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +000091 // strings as untyped objects and let the runtime figure it out later.
92 Ty = Context.getObjCIdType();
93 }
Chris Lattner13fd7e52008-06-21 21:44:18 +000094 }
Mike Stump1eb44332009-09-09 15:08:12 +000095
Chris Lattnerf4b136f2009-02-18 06:13:04 +000096 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +000097}
98
Mike Stump1eb44332009-09-09 15:08:12 +000099Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000100 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000101 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000102 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000103 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000104 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000105 StrTy = Context.DependentTy;
106 else {
107 std::string Str;
108 Context.getObjCEncodingForType(EncodedType, Str);
109
110 // The type of @encode is the same as the type of the corresponding string,
111 // which is an array type.
112 StrTy = Context.CharTy;
113 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000114 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000115 StrTy.addConst();
116 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
117 ArrayType::Normal, 0);
118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Douglas Gregor81d34662010-04-20 15:39:42 +0000120 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000121}
122
Chris Lattner85a932e2008-01-04 22:32:30 +0000123Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
124 SourceLocation EncodeLoc,
125 SourceLocation LParenLoc,
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000126 TypeTy *ty,
Chris Lattner85a932e2008-01-04 22:32:30 +0000127 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000128 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000129 TypeSourceInfo *TInfo;
130 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
131 if (!TInfo)
132 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
133 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000134
Douglas Gregor81d34662010-04-20 15:39:42 +0000135 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000136}
137
138Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
139 SourceLocation AtLoc,
140 SourceLocation SelLoc,
141 SourceLocation LParenLoc,
142 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000143 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian835ed7f2009-08-22 21:13:55 +0000144 SourceRange(LParenLoc, RParenLoc), false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000145 if (!Method)
146 Method = LookupFactoryMethodInGlobalPool(Sel,
147 SourceRange(LParenLoc, RParenLoc));
148 if (!Method)
149 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
150
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000151 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000152 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000153}
154
155Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
156 SourceLocation AtLoc,
157 SourceLocation ProtoLoc,
158 SourceLocation LParenLoc,
159 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000160 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000161 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000162 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000163 return true;
164 }
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000166 QualType Ty = Context.getObjCProtoType();
167 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000168 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000169 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000170 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000171}
172
Mike Stump1eb44332009-09-09 15:08:12 +0000173bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
174 Selector Sel, ObjCMethodDecl *Method,
Chris Lattner077bf5e2008-11-24 03:33:13 +0000175 bool isClassMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000176 SourceLocation lbrac, SourceLocation rbrac,
Mike Stump1eb44332009-09-09 15:08:12 +0000177 QualType &ReturnType) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000178 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000179 // Apply default argument promotion as for (C99 6.5.2.2p6).
180 for (unsigned i = 0; i != NumArgs; i++)
181 DefaultArgumentPromotion(Args[i]);
182
Chris Lattner077bf5e2008-11-24 03:33:13 +0000183 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
184 diag::warn_inst_method_not_found;
185 Diag(lbrac, DiagID)
186 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000187 ReturnType = Context.getObjCIdType();
188 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000189 }
Mike Stump1eb44332009-09-09 15:08:12 +0000190
Douglas Gregor2725ca82010-04-21 19:57:20 +0000191 ReturnType = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +0000192
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000193 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000194 // Method might have more arguments than selector indicates. This is due
195 // to addition of c-style arguments in method.
196 if (Method->param_size() > Sel.getNumArgs())
197 NumNamedArgs = Method->param_size();
198 // FIXME. This need be cleaned up.
199 if (NumArgs < NumNamedArgs) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000200 Diag(lbrac, diag::err_typecheck_call_too_few_args) << 2
201 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000202 return false;
203 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000204
Chris Lattner312531a2009-04-12 08:11:20 +0000205 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000206 for (unsigned i = 0; i < NumNamedArgs; i++) {
Chris Lattner85a932e2008-01-04 22:32:30 +0000207 Expr *argExpr = Args[i];
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000208 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000209 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000210
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000211 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
212 Param->getType(),
213 PDiag(diag::err_call_incomplete_argument)
214 << argExpr->getSourceRange()))
215 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000216
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000217 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
218 OwningExprResult ArgE = PerformCopyInitialization(Entity,
219 SourceLocation(),
220 Owned(argExpr->Retain()));
221 if (ArgE.isInvalid())
222 IsError = true;
223 else
224 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000225 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000226
227 // Promote additional arguments to variadic methods.
228 if (Method->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000229 for (unsigned i = NumNamedArgs; i < NumArgs; ++i)
Chris Lattner312531a2009-04-12 08:11:20 +0000230 IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod);
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000231 } else {
232 // Check for extra arguments to non-variadic methods.
233 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000234 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000235 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000236 << 2 /*method*/ << NumNamedArgs << NumArgs
237 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000238 << SourceRange(Args[NumNamedArgs]->getLocStart(),
239 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000240 }
241 }
242
Douglas Gregor2725ca82010-04-21 19:57:20 +0000243 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000244 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000245}
246
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000247bool Sema::isSelfExpr(Expr *RExpr) {
248 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
249 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
250 return true;
251 return false;
252}
253
Steve Narofff1afaf62009-02-26 15:55:06 +0000254// Helper method for ActOnClassMethod/ActOnInstanceMethod.
255// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000256// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000257// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000258ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000259 ObjCInterfaceDecl *ClassDecl) {
260 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000261 // lookup in class and all superclasses
262 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000263 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000264 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000265
Steve Naroff5609ec02009-03-08 18:56:13 +0000266 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000267 if (!Method)
268 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000269
Steve Naroff5609ec02009-03-08 18:56:13 +0000270 // Before we give up, check if the selector is an instance method.
271 // But only in the root. This matches gcc's behaviour and what the
272 // runtime expects.
273 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000274 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000275 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000276 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000277 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000278 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
279 }
Mike Stump1eb44332009-09-09 15:08:12 +0000280
Steve Naroff5609ec02009-03-08 18:56:13 +0000281 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000282 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000283 return Method;
284}
285
286ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
287 ObjCInterfaceDecl *ClassDecl) {
288 ObjCMethodDecl *Method = 0;
289 while (ClassDecl && !Method) {
290 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000291 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000292 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Steve Naroff5609ec02009-03-08 18:56:13 +0000294 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000295 if (!Method)
296 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000297 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000298 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000299 return Method;
300}
301
Chris Lattner7f816522010-04-11 07:45:24 +0000302/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
303/// objective C interface. This is a property reference expression.
304Action::OwningExprResult Sema::
305HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000306 Expr *BaseExpr, DeclarationName MemberName,
307 SourceLocation MemberLoc) {
Chris Lattner7f816522010-04-11 07:45:24 +0000308 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
309 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
310 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
311
312 // Search for a declared property first.
313 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
314 // Check whether we can reference this property.
315 if (DiagnoseUseOfDecl(PD, MemberLoc))
316 return ExprError();
317 QualType ResTy = PD->getType();
318 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
319 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
320 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
321 ResTy = Getter->getResultType();
322 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
323 MemberLoc, BaseExpr));
324 }
325 // Check protocols on qualified interfaces.
326 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
327 E = OPT->qual_end(); I != E; ++I)
328 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
329 // Check whether we can reference this property.
330 if (DiagnoseUseOfDecl(PD, MemberLoc))
331 return ExprError();
332
333 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
334 MemberLoc, BaseExpr));
335 }
336 // If that failed, look for an "implicit" property by seeing if the nullary
337 // selector is implemented.
338
339 // FIXME: The logic for looking up nullary and unary selectors should be
340 // shared with the code in ActOnInstanceMessage.
341
342 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
343 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
344
345 // If this reference is in an @implementation, check for 'private' methods.
346 if (!Getter)
347 Getter = IFace->lookupPrivateInstanceMethod(Sel);
348
349 // Look through local category implementations associated with the class.
350 if (!Getter)
351 Getter = IFace->getCategoryInstanceMethod(Sel);
352 if (Getter) {
353 // Check if we can reference this property.
354 if (DiagnoseUseOfDecl(Getter, MemberLoc))
355 return ExprError();
356 }
357 // If we found a getter then this may be a valid dot-reference, we
358 // will look for the matching setter, in case it is needed.
359 Selector SetterSel =
360 SelectorTable::constructSetterName(PP.getIdentifierTable(),
361 PP.getSelectorTable(), Member);
362 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
363 if (!Setter) {
364 // If this reference is in an @implementation, also check for 'private'
365 // methods.
366 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
367 }
368 // Look through local category implementations associated with the class.
369 if (!Setter)
370 Setter = IFace->getCategoryInstanceMethod(SetterSel);
371
372 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
373 return ExprError();
374
375 if (Getter) {
376 QualType PType;
377 PType = Getter->getResultType();
378 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
379 Setter, MemberLoc, BaseExpr));
380 }
381
382 // Attempt to correct for typos in property names.
383 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000384 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
Chris Lattner7f816522010-04-11 07:45:24 +0000385 Res.getAsSingle<ObjCPropertyDecl>()) {
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000386 DeclarationName TypoResult = Res.getLookupName();
Chris Lattner7f816522010-04-11 07:45:24 +0000387 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000388 << MemberName << QualType(OPT, 0) << TypoResult
389 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000390 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
391 Diag(Property->getLocation(), diag::note_previous_decl)
392 << Property->getDeclName();
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000393 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc);
Chris Lattner7f816522010-04-11 07:45:24 +0000394 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000395
Chris Lattner7f816522010-04-11 07:45:24 +0000396 Diag(MemberLoc, diag::err_property_not_found)
397 << MemberName << QualType(OPT, 0);
398 if (Setter && !Getter)
399 Diag(Setter->getLocation(), diag::note_getter_unavailable)
400 << MemberName << BaseExpr->getSourceRange();
401 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000402}
403
404
405
Chris Lattnereb483eb2010-04-11 08:28:14 +0000406Action::OwningExprResult Sema::
407ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
408 IdentifierInfo &propertyName,
409 SourceLocation receiverNameLoc,
410 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000412 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000413 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
414 receiverNameLoc);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000415 if (IFace == 0) {
416 // If the "receiver" is 'super' in a method, handle it as an expression-like
417 // property reference.
418 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
419 if (receiverNamePtr->isStr("super")) {
420 if (CurMethod->isInstanceMethod()) {
421 QualType T =
422 Context.getObjCInterfaceType(CurMethod->getClassInterface());
423 T = Context.getObjCObjectPointerType(T);
424 Expr *SuperExpr = new (Context) ObjCSuperExpr(receiverNameLoc, T);
425
426 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
427 SuperExpr, &propertyName,
428 propertyNameLoc);
429 }
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Chris Lattnereb483eb2010-04-11 08:28:14 +0000431 // Otherwise, if this is a class method, try dispatching to our
432 // superclass.
433 IFace = CurMethod->getClassInterface()->getSuperClass();
434 }
435
436 if (IFace == 0) {
437 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
438 return ExprError();
439 }
440 }
441
442 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000443 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000444 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000445
446 // If this reference is in an @implementation, check for 'private' methods.
447 if (!Getter)
448 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
449 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000450 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000451 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000452
453 if (Getter) {
454 // FIXME: refactor/share with ActOnMemberReference().
455 // Check if we can reference this property.
456 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
457 return ExprError();
458 }
Mike Stump1eb44332009-09-09 15:08:12 +0000459
Steve Naroff61f72cb2009-03-09 21:12:44 +0000460 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000461 Selector SetterSel =
462 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000463 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000465 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000466 if (!Setter) {
467 // If this reference is in an @implementation, also check for 'private'
468 // methods.
469 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
470 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000471 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000472 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000473 }
474 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000475 if (!Setter)
476 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000477
478 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
479 return ExprError();
480
481 if (Getter || Setter) {
482 QualType PType;
483
484 if (Getter)
485 PType = Getter->getResultType();
486 else {
487 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
488 E = Setter->param_end(); PI != E; ++PI)
489 PType = (*PI)->getType();
490 }
Fariborz Jahanian09105f52009-08-20 17:02:02 +0000491 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(
Mike Stump1eb44332009-09-09 15:08:12 +0000492 Getter, PType, Setter,
Steve Naroff61f72cb2009-03-09 21:12:44 +0000493 propertyNameLoc, IFace, receiverNameLoc));
494 }
495 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
496 << &propertyName << Context.getObjCInterfaceType(IFace));
497}
498
Douglas Gregor47bd5432010-04-14 02:46:37 +0000499Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000500 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000501 SourceLocation NameLoc,
502 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000503 bool HasTrailingDot,
504 TypeTy *&ReceiverType) {
505 ReceiverType = 0;
506
Douglas Gregor47bd5432010-04-14 02:46:37 +0000507 // If the identifier is "super" and there is no trailing dot, we're
508 // messaging super.
509 if (IsSuper && !HasTrailingDot && S->isInObjcMethodScope())
510 return ObjCSuperMessage;
511
512 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
513 LookupName(Result, S);
514
515 switch (Result.getResultKind()) {
516 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000517 // Normal name lookup didn't find anything. If we're in an
518 // Objective-C method, look for ivars. If we find one, we're done!
519 // FIXME: This is a hack. Ivar lookup should be part of normal lookup.
520 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
521 ObjCInterfaceDecl *ClassDeclared;
522 if (Method->getClassInterface()->lookupInstanceVariable(Name,
523 ClassDeclared))
524 return ObjCInstanceMessage;
525 }
526
Douglas Gregor47bd5432010-04-14 02:46:37 +0000527 // Break out; we'll perform typo correction below.
528 break;
529
530 case LookupResult::NotFoundInCurrentInstantiation:
531 case LookupResult::FoundOverloaded:
532 case LookupResult::FoundUnresolvedValue:
533 case LookupResult::Ambiguous:
534 Result.suppressDiagnostics();
535 return ObjCInstanceMessage;
536
537 case LookupResult::Found: {
538 // We found something. If it's a type, then we have a class
539 // message. Otherwise, it's an instance message.
540 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000541 QualType T;
542 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
543 T = Context.getObjCInterfaceType(Class);
544 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
545 T = Context.getTypeDeclType(Type);
546 else
547 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000548
Douglas Gregor1569f952010-04-21 20:38:13 +0000549 // We have a class message, and T is the type we're
550 // messaging. Build source-location information for it.
551 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
552 ReceiverType = CreateLocInfoType(T, TSInfo).getAsOpaquePtr();
553 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000554 }
555 }
556
Douglas Gregoraaf87162010-04-14 20:04:41 +0000557 // Determine our typo-correction context.
558 CorrectTypoContext CTC = CTC_Expression;
559 if (ObjCMethodDecl *Method = getCurMethodDecl())
560 if (Method->getClassInterface() &&
561 Method->getClassInterface()->getSuperClass())
562 CTC = CTC_ObjCMessageReceiver;
563
564 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
565 if (Result.isSingleResult()) {
566 // If we found a declaration, correct when it refers to an Objective-C
567 // class.
568 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000569 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000570 Diag(NameLoc, diag::err_unknown_receiver_suggest)
571 << Name << Result.getLookupName()
572 << FixItHint::CreateReplacement(SourceRange(NameLoc),
573 ND->getNameAsString());
574 Diag(ND->getLocation(), diag::note_previous_decl)
575 << Corrected;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000576
Douglas Gregor1569f952010-04-21 20:38:13 +0000577 QualType T = Context.getObjCInterfaceType(Class);
578 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
579 ReceiverType = CreateLocInfoType(T, TSInfo).getAsOpaquePtr();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000580 return ObjCClassMessage;
581 }
582 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
583 Corrected.getAsIdentifierInfo()->isStr("super")) {
584 // If we've found the keyword "super", this is a send to super.
585 Diag(NameLoc, diag::err_unknown_receiver_suggest)
586 << Name << Corrected
587 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
588 Name = Corrected.getAsIdentifierInfo();
589 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000590 }
591 }
592
593 // Fall back: let the parser try to parse it as an instance message.
594 return ObjCInstanceMessage;
595}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000596
Douglas Gregor2725ca82010-04-21 19:57:20 +0000597Sema::OwningExprResult Sema::ActOnSuperMessage(Scope *S,
598 SourceLocation SuperLoc,
599 Selector Sel,
600 SourceLocation LBracLoc,
601 SourceLocation SelectorLoc,
602 SourceLocation RBracLoc,
603 MultiExprArg Args) {
604 // Determine whether we are inside a method or not.
605 ObjCMethodDecl *Method = getCurMethodDecl();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000606 if (!Method) {
607 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
608 return ExprError();
609 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000610
Douglas Gregorf95861a2010-04-21 20:01:04 +0000611 ObjCInterfaceDecl *Class = Method->getClassInterface();
612 if (!Class) {
613 Diag(SuperLoc, diag::error_no_super_class_message)
614 << Method->getDeclName();
615 return ExprError();
616 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000617
Douglas Gregorf95861a2010-04-21 20:01:04 +0000618 ObjCInterfaceDecl *Super = Class->getSuperClass();
619 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000620 // The current class does not have a superclass.
621 Diag(SuperLoc, diag::error_no_super_class) << Class->getIdentifier();
622 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000623 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000624
Douglas Gregorf95861a2010-04-21 20:01:04 +0000625 // We are in a method whose class has a superclass, so 'super'
626 // is acting as a keyword.
627 if (Method->isInstanceMethod()) {
628 // Since we are in an instance method, this is an instance
629 // message to the superclass instance.
630 QualType SuperTy = Context.getObjCInterfaceType(Super);
631 SuperTy = Context.getObjCObjectPointerType(SuperTy);
632 return BuildInstanceMessage(ExprArg(*this), SuperTy, SuperLoc,
633 Sel, LBracLoc, SelectorLoc, RBracLoc,
634 move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000635 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000636
637 // Since we are in a class method, this is a class message to
638 // the superclass.
639 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
640 Context.getObjCInterfaceType(Super),
641 SuperLoc, Sel, LBracLoc, SelectorLoc,
642 RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000643}
644
645/// \brief Build an Objective-C class message expression.
646///
647/// This routine takes care of both normal class messages and
648/// class messages to the superclass.
649///
650/// \param ReceiverTypeInfo Type source information that describes the
651/// receiver of this message. This may be NULL, in which case we are
652/// sending to the superclass and \p SuperLoc must be a valid source
653/// location.
654
655/// \param ReceiverType The type of the object receiving the
656/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
657/// type as that refers to. For a superclass send, this is the type of
658/// the superclass.
659///
660/// \param SuperLoc The location of the "super" keyword in a
661/// superclass message.
662///
663/// \param Sel The selector to which the message is being sent.
664///
665/// \param LBracLoc The location of the opening square bracket ']'.
666///
667/// \param SelectorLoc The location of the first identifier in the selector.
668///
669/// \param RBrac The location of the closing square bracket ']'.
670///
671/// \param Args The message arguments.
672Sema::OwningExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
673 QualType ReceiverType,
674 SourceLocation SuperLoc,
675 Selector Sel,
676 SourceLocation LBracLoc,
677 SourceLocation SelectorLoc,
678 SourceLocation RBracLoc,
679 MultiExprArg ArgsIn) {
680 assert(!ReceiverType->isDependentType() &&
681 "Dependent class messages not yet implemented");
Chris Lattner15faee12010-04-12 05:38:43 +0000682
Douglas Gregor2725ca82010-04-21 19:57:20 +0000683 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
684 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000685
Douglas Gregor2725ca82010-04-21 19:57:20 +0000686 // Find the class to which we are sending this message.
687 ObjCInterfaceDecl *Class = 0;
688 if (const ObjCInterfaceType *ClassType
689 = ReceiverType->getAs<ObjCInterfaceType>())
690 Class = ClassType->getDecl();
691 else {
692 Diag(Loc, diag::err_invalid_receiver_class_message)
693 << ReceiverType;
694 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +0000695 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000696 assert(Class && "We don't know which class we're messaging?");
697
698 // Find the method we are messaging.
Steve Naroffcb28be62008-06-04 23:08:38 +0000699 ObjCMethodDecl *Method = 0;
Douglas Gregor2725ca82010-04-21 19:57:20 +0000700 if (Class->isForwardDecl()) {
701 // A forward class used in messaging is treated as a 'Class'
702 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
703 Method = LookupFactoryMethodInGlobalPool(Sel,
704 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89bc3142009-05-08 23:02:36 +0000705 if (Method)
Mike Stump1eb44332009-09-09 15:08:12 +0000706 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
Fariborz Jahanian9f8f0262009-05-08 23:45:49 +0000707 << Method->getDeclName();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +0000708 }
709 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000710 Method = Class->lookupClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Steve Naroff7c778f12008-07-25 19:39:00 +0000712 // If we have an implementation in scope, check "private" methods.
Steve Narofff1afaf62009-02-26 15:55:06 +0000713 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000714 Method = LookupPrivateClassMethod(Sel, Class);
Steve Naroff7c778f12008-07-25 19:39:00 +0000715
Douglas Gregor2725ca82010-04-21 19:57:20 +0000716 if (Method && DiagnoseUseOfDecl(Method, Loc))
717 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Douglas Gregor2725ca82010-04-21 19:57:20 +0000719 // Check the argument types and determine the result type.
720 QualType ReturnType;
721 unsigned NumArgs = ArgsIn.size();
722 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
723 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
724 LBracLoc, RBracLoc, ReturnType)) {
725 for (unsigned I = 0; I != NumArgs; ++I)
726 Args[I]->Destroy(Context);
727 return ExprError();
728 }
Ted Kremenek4df728e2008-06-24 15:50:53 +0000729
Douglas Gregor2725ca82010-04-21 19:57:20 +0000730 // Construct the appropriate ObjCMessageExpr.
731 if (SuperLoc.isValid())
732 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
733 SuperLoc, /*IsInstanceSuper=*/false,
734 ReceiverType, Sel, Method, Args,
735 NumArgs, RBracLoc));
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Douglas Gregor2725ca82010-04-21 19:57:20 +0000737 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
738 ReceiverTypeInfo, Sel, Method, Args,
739 NumArgs, RBracLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000740}
741
Douglas Gregor2725ca82010-04-21 19:57:20 +0000742// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +0000743// ArgExprs is optional - if it is present, the number of expressions
744// is obtained from Sel.getNumArgs().
Douglas Gregor2725ca82010-04-21 19:57:20 +0000745Sema::OwningExprResult Sema::ActOnClassMessage(Scope *S,
746 TypeTy *Receiver,
747 Selector Sel,
748 SourceLocation LBracLoc,
749 SourceLocation SelectorLoc,
750 SourceLocation RBracLoc,
751 MultiExprArg Args) {
752 TypeSourceInfo *ReceiverTypeInfo;
753 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
754 if (ReceiverType.isNull())
755 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Douglas Gregor2725ca82010-04-21 19:57:20 +0000758 if (!ReceiverTypeInfo)
759 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
760
761 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
762 /*SuperLoc=*/SourceLocation(), Sel,
763 LBracLoc, SelectorLoc, RBracLoc, move(Args));
764}
765
766/// \brief Build an Objective-C instance message expression.
767///
768/// This routine takes care of both normal instance messages and
769/// instance messages to the superclass instance.
770///
771/// \param Receiver The expression that computes the object that will
772/// receive this message. This may be empty, in which case we are
773/// sending to the superclass instance and \p SuperLoc must be a valid
774/// source location.
775///
776/// \param ReceiverType The (static) type of the object receiving the
777/// message. When a \p Receiver expression is provided, this is the
778/// same type as that expression. For a superclass instance send, this
779/// is a pointer to the type of the superclass.
780///
781/// \param SuperLoc The location of the "super" keyword in a
782/// superclass instance message.
783///
784/// \param Sel The selector to which the message is being sent.
785///
786/// \param LBracLoc The location of the opening square bracket ']'.
787///
788/// \param SelectorLoc The location of the first identifier in the selector.
789///
790/// \param RBrac The location of the closing square bracket ']'.
791///
792/// \param Args The message arguments.
793Sema::OwningExprResult Sema::BuildInstanceMessage(ExprArg ReceiverE,
794 QualType ReceiverType,
795 SourceLocation SuperLoc,
796 Selector Sel,
797 SourceLocation LBracLoc,
798 SourceLocation SelectorLoc,
799 SourceLocation RBracLoc,
800 MultiExprArg ArgsIn) {
801 // If we have a receiver expression, perform appropriate promotions
802 // and determine receiver type.
803 Expr *Receiver = ReceiverE.takeAs<Expr>();
804 if (Receiver) {
805 // If necessary, apply function/array conversion to the receiver.
806 // C99 6.7.5.3p[7,8].
807 DefaultFunctionArrayLvalueConversion(Receiver);
808 ReceiverType = Receiver->getType();
809 }
810
811 // The location of the receiver.
812 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Douglas Gregor04badcf2010-04-21 00:45:42 +0000814 ObjCMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000815 // Handle messages to id.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000816 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType() ||
817 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
818 Method = LookupInstanceMethodInGlobalPool(Sel,
819 SourceRange(LBracLoc, RBracLoc));
Chris Lattner6e10a082008-02-01 06:57:39 +0000820 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000821 Method = LookupFactoryMethodInGlobalPool(Sel,
822 SourceRange(LBracLoc, RBracLoc));
823 } else if (ReceiverType->isObjCClassType() ||
824 ReceiverType->isObjCQualifiedClassType()) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000825 // Handle messages to Class.
Chris Lattner6562fda2008-07-21 06:44:27 +0000826 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
Steve Naroffd526c2f2009-02-23 02:25:40 +0000827 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
828 // First check the public methods in the class interface.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000829 Method = ClassDecl->lookupClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000830
Steve Narofff1afaf62009-02-26 15:55:06 +0000831 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000832 Method = LookupPrivateClassMethod(Sel, ClassDecl);
Mike Stump1eb44332009-09-09 15:08:12 +0000833
834 // FIXME: if we still haven't found a method, we need to look in
Steve Naroff470301b2009-07-22 16:07:01 +0000835 // protocols (if we have qualifiers).
Steve Naroffd526c2f2009-02-23 02:25:40 +0000836 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000837 if (Method && DiagnoseUseOfDecl(Method, Loc))
838 return ExprError();
Steve Naroffd526c2f2009-02-23 02:25:40 +0000839 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000840 if (!Method) {
841 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000842 if (!Receiver || !isSelfExpr(Receiver)) {
843 Method = LookupFactoryMethodInGlobalPool(Sel,
844 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanianb1006c72009-03-04 17:50:39 +0000845 if (!Method) {
Fariborz Jahanian041f2fd2009-05-05 18:34:37 +0000846 // If no class (factory) method was found, check if an _instance_
847 // method of the same name exists in the root class only.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000848 Method = LookupInstanceMethodInGlobalPool(Sel,
849 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian041f2fd2009-05-05 18:34:37 +0000850 if (Method)
851 if (const ObjCInterfaceDecl *ID =
852 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
853 if (ID->getSuperClass())
Douglas Gregor2725ca82010-04-21 19:57:20 +0000854 Diag(Loc, diag::warn_root_inst_method_not_found)
855 << Sel << SourceRange(LBracLoc, RBracLoc);
Fariborz Jahanian041f2fd2009-05-05 18:34:37 +0000856 }
Fariborz Jahanianb1006c72009-03-04 17:50:39 +0000857 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000858 }
859 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000860 } else {
861 ObjCInterfaceDecl* ClassDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Douglas Gregor04badcf2010-04-21 00:45:42 +0000863 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
864 // long as one of the protocols implements the selector (if not, warn).
Douglas Gregor2725ca82010-04-21 19:57:20 +0000865 if (const ObjCObjectPointerType *QIdTy
866 = ReceiverType->getAsObjCQualifiedIdType()) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000867 // Search protocols for instance methods.
868 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
869 E = QIdTy->qual_end(); I != E; ++I) {
870 ObjCProtocolDecl *PDecl = *I;
871 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
872 break;
873 // Since we aren't supporting "Class<foo>", look for a class method.
874 if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
Chris Lattner85a932e2008-01-04 22:32:30 +0000875 break;
876 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000877 } else if (const ObjCObjectPointerType *OCIType
878 = ReceiverType->getAsObjCInterfacePointerType()) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000879 // We allow sending a message to a pointer to an interface (an object).
Douglas Gregor04badcf2010-04-21 00:45:42 +0000880 ClassDecl = OCIType->getInterfaceDecl();
881 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
882 // faster than the following method (which can do *many* linear searches).
883 // The idea is to add class info to InstanceMethodPool.
884 Method = ClassDecl->lookupInstanceMethod(Sel);
885
886 if (!Method) {
887 // Search protocol qualifiers.
888 for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(),
889 E = OCIType->qual_end(); QI != E; ++QI) {
890 if ((Method = (*QI)->lookupInstanceMethod(Sel)))
891 break;
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000892 }
Fariborz Jahanian268bc8c2009-03-03 22:19:15 +0000893 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000894 if (!Method) {
895 // If we have implementations in scope, check "private" methods.
896 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
897
Douglas Gregor2725ca82010-04-21 19:57:20 +0000898 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000899 // If we still haven't found a method, look in the global pool. This
900 // behavior isn't very desirable, however we need it for GCC
901 // compatibility. FIXME: should we deviate??
902 if (OCIType->qual_empty()) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000903 Method = LookupInstanceMethodInGlobalPool(Sel,
904 SourceRange(LBracLoc, RBracLoc));
Douglas Gregor04badcf2010-04-21 00:45:42 +0000905 if (Method && !OCIType->getInterfaceDecl()->isForwardDecl())
Douglas Gregor2725ca82010-04-21 19:57:20 +0000906 Diag(Loc, diag::warn_maynot_respond)
Douglas Gregor04badcf2010-04-21 00:45:42 +0000907 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
908 }
909 }
910 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000911 if (Method && DiagnoseUseOfDecl(Method, Loc))
912 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000913 } else if (!Context.getObjCIdType().isNull() &&
Douglas Gregor2725ca82010-04-21 19:57:20 +0000914 (ReceiverType->isPointerType() ||
915 (ReceiverType->isIntegerType() &&
916 ReceiverType->isScalarType()))) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000917 // Implicitly convert integers and pointers to 'id' but emit a warning.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000918 Diag(Loc, diag::warn_bad_receiver_type)
919 << ReceiverType
920 << Receiver->getSourceRange();
921 if (ReceiverType->isPointerType())
922 ImpCastExprToType(Receiver, Context.getObjCIdType(),
923 CastExpr::CK_BitCast);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000924 else
Douglas Gregor2725ca82010-04-21 19:57:20 +0000925 ImpCastExprToType(Receiver, Context.getObjCIdType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +0000926 CastExpr::CK_IntegralToPointer);
Douglas Gregor2725ca82010-04-21 19:57:20 +0000927 ReceiverType = Receiver->getType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000928 } else {
929 // Reject other random receiver types (e.g. structs).
Douglas Gregor2725ca82010-04-21 19:57:20 +0000930 Diag(Loc, diag::err_bad_receiver_type)
931 << ReceiverType << Receiver->getSourceRange();
932 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000933 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +0000934 }
Mike Stump1eb44332009-09-09 15:08:12 +0000935
Douglas Gregor2725ca82010-04-21 19:57:20 +0000936 // Check the message arguments.
937 unsigned NumArgs = ArgsIn.size();
938 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
939 QualType ReturnType;
940 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, false,
941 LBracLoc, RBracLoc, ReturnType))
942 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000943
Douglas Gregor2725ca82010-04-21 19:57:20 +0000944 // Construct the appropriate ObjCMessageExpr instance.
945 if (SuperLoc.isValid())
946 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
947 SuperLoc, /*IsInstanceSuper=*/true,
948 ReceiverType, Sel, Method,
949 Args, NumArgs, RBracLoc));
Douglas Gregor04badcf2010-04-21 00:45:42 +0000950
Douglas Gregor2725ca82010-04-21 19:57:20 +0000951 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, Receiver,
952 Sel, Method, Args, NumArgs, RBracLoc));
953}
954
955// ActOnInstanceMessage - used for both unary and keyword messages.
956// ArgExprs is optional - if it is present, the number of expressions
957// is obtained from Sel.getNumArgs().
958Sema::OwningExprResult Sema::ActOnInstanceMessage(Scope *S,
959 ExprArg ReceiverE,
960 Selector Sel,
961 SourceLocation LBracLoc,
962 SourceLocation SelectorLoc,
963 SourceLocation RBracLoc,
964 MultiExprArg Args) {
965 Expr *Receiver = static_cast<Expr *>(ReceiverE.get());
966 if (!Receiver)
967 return ExprError();
968
969 return BuildInstanceMessage(move(ReceiverE), Receiver->getType(),
970 /*SuperLoc=*/SourceLocation(),
971 Sel, LBracLoc, SelectorLoc, RBracLoc,
972 move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +0000973}
Chris Lattnereca7be62008-04-07 05:30:13 +0000974