blob: dd402b074dd5275cf2a944054d5eb7542162d13c [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
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000166 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000167 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000168}
169
170Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
171 SourceLocation AtLoc,
172 SourceLocation ProtoLoc,
173 SourceLocation LParenLoc,
174 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000175 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000176 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000177 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000178 return true;
179 }
Mike Stump1eb44332009-09-09 15:08:12 +0000180
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000181 QualType Ty = Context.getObjCProtoType();
182 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000183 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000184 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000185 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000186}
187
Mike Stump1eb44332009-09-09 15:08:12 +0000188bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
189 Selector Sel, ObjCMethodDecl *Method,
Chris Lattner077bf5e2008-11-24 03:33:13 +0000190 bool isClassMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000191 SourceLocation lbrac, SourceLocation rbrac,
Mike Stump1eb44332009-09-09 15:08:12 +0000192 QualType &ReturnType) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000193 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000194 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000195 for (unsigned i = 0; i != NumArgs; i++) {
196 if (Args[i]->isTypeDependent())
197 continue;
198
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000199 DefaultArgumentPromotion(Args[i]);
Douglas Gregor92e986e2010-04-22 16:44:27 +0000200 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000201
Chris Lattner077bf5e2008-11-24 03:33:13 +0000202 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
203 diag::warn_inst_method_not_found;
204 Diag(lbrac, DiagID)
205 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000206 ReturnType = Context.getObjCIdType();
207 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000208 }
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Douglas Gregor2725ca82010-04-21 19:57:20 +0000210 ReturnType = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000212 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000213 // Method might have more arguments than selector indicates. This is due
214 // to addition of c-style arguments in method.
215 if (Method->param_size() > Sel.getNumArgs())
216 NumNamedArgs = Method->param_size();
217 // FIXME. This need be cleaned up.
218 if (NumArgs < NumNamedArgs) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000219 Diag(lbrac, diag::err_typecheck_call_too_few_args) << 2
220 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000221 return false;
222 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000223
Chris Lattner312531a2009-04-12 08:11:20 +0000224 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000225 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000226 // We can't do any type-checking on a type-dependent argument.
227 if (Args[i]->isTypeDependent())
228 continue;
229
Chris Lattner85a932e2008-01-04 22:32:30 +0000230 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000231
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000232 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000233 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000234
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000235 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
236 Param->getType(),
237 PDiag(diag::err_call_incomplete_argument)
238 << argExpr->getSourceRange()))
239 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000240
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000241 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
242 OwningExprResult ArgE = PerformCopyInitialization(Entity,
243 SourceLocation(),
244 Owned(argExpr->Retain()));
245 if (ArgE.isInvalid())
246 IsError = true;
247 else
248 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000249 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000250
251 // Promote additional arguments to variadic methods.
252 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000253 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
254 if (Args[i]->isTypeDependent())
255 continue;
256
Chris Lattner40378332010-05-16 04:01:30 +0000257 IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
Douglas Gregor92e986e2010-04-22 16:44:27 +0000258 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000259 } else {
260 // Check for extra arguments to non-variadic methods.
261 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000262 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000263 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000264 << 2 /*method*/ << NumNamedArgs << NumArgs
265 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000266 << SourceRange(Args[NumNamedArgs]->getLocStart(),
267 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000268 }
269 }
270
Douglas Gregor2725ca82010-04-21 19:57:20 +0000271 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000272 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000273}
274
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000275bool Sema::isSelfExpr(Expr *RExpr) {
276 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
277 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
278 return true;
279 return false;
280}
281
Steve Narofff1afaf62009-02-26 15:55:06 +0000282// Helper method for ActOnClassMethod/ActOnInstanceMethod.
283// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000284// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000285// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000286ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000287 ObjCInterfaceDecl *ClassDecl) {
288 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000289 // lookup in class and all superclasses
290 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000291 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000292 Method = ImpDecl->getClassMethod(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->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000297
Steve Naroff5609ec02009-03-08 18:56:13 +0000298 // Before we give up, check if the selector is an instance method.
299 // But only in the root. This matches gcc's behaviour and what the
300 // runtime expects.
301 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000302 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000303 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000304 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000305 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000306 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
307 }
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Steve Naroff5609ec02009-03-08 18:56:13 +0000309 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000310 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000311 return Method;
312}
313
314ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
315 ObjCInterfaceDecl *ClassDecl) {
316 ObjCMethodDecl *Method = 0;
317 while (ClassDecl && !Method) {
318 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000319 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000320 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Steve Naroff5609ec02009-03-08 18:56:13 +0000322 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000323 if (!Method)
324 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000325 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000326 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000327 return Method;
328}
329
Chris Lattner7f816522010-04-11 07:45:24 +0000330/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
331/// objective C interface. This is a property reference expression.
332Action::OwningExprResult Sema::
333HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000334 Expr *BaseExpr, DeclarationName MemberName,
335 SourceLocation MemberLoc) {
Chris Lattner7f816522010-04-11 07:45:24 +0000336 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
337 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
338 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
339
340 // Search for a declared property first.
341 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
342 // Check whether we can reference this property.
343 if (DiagnoseUseOfDecl(PD, MemberLoc))
344 return ExprError();
345 QualType ResTy = PD->getType();
346 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
347 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
348 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
349 ResTy = Getter->getResultType();
350 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
351 MemberLoc, BaseExpr));
352 }
353 // Check protocols on qualified interfaces.
354 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
355 E = OPT->qual_end(); I != E; ++I)
356 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
357 // Check whether we can reference this property.
358 if (DiagnoseUseOfDecl(PD, MemberLoc))
359 return ExprError();
360
361 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
362 MemberLoc, BaseExpr));
363 }
364 // If that failed, look for an "implicit" property by seeing if the nullary
365 // selector is implemented.
366
367 // FIXME: The logic for looking up nullary and unary selectors should be
368 // shared with the code in ActOnInstanceMessage.
369
370 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
371 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
372
373 // If this reference is in an @implementation, check for 'private' methods.
374 if (!Getter)
375 Getter = IFace->lookupPrivateInstanceMethod(Sel);
376
377 // Look through local category implementations associated with the class.
378 if (!Getter)
379 Getter = IFace->getCategoryInstanceMethod(Sel);
380 if (Getter) {
381 // Check if we can reference this property.
382 if (DiagnoseUseOfDecl(Getter, MemberLoc))
383 return ExprError();
384 }
385 // If we found a getter then this may be a valid dot-reference, we
386 // will look for the matching setter, in case it is needed.
387 Selector SetterSel =
388 SelectorTable::constructSetterName(PP.getIdentifierTable(),
389 PP.getSelectorTable(), Member);
390 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
391 if (!Setter) {
392 // If this reference is in an @implementation, also check for 'private'
393 // methods.
394 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
395 }
396 // Look through local category implementations associated with the class.
397 if (!Setter)
398 Setter = IFace->getCategoryInstanceMethod(SetterSel);
399
400 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
401 return ExprError();
402
403 if (Getter) {
404 QualType PType;
405 PType = Getter->getResultType();
406 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
407 Setter, MemberLoc, BaseExpr));
408 }
409
410 // Attempt to correct for typos in property names.
411 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000412 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
Chris Lattner7f816522010-04-11 07:45:24 +0000413 Res.getAsSingle<ObjCPropertyDecl>()) {
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000414 DeclarationName TypoResult = Res.getLookupName();
Chris Lattner7f816522010-04-11 07:45:24 +0000415 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000416 << MemberName << QualType(OPT, 0) << TypoResult
417 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000418 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
419 Diag(Property->getLocation(), diag::note_previous_decl)
420 << Property->getDeclName();
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000421 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc);
Chris Lattner7f816522010-04-11 07:45:24 +0000422 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000423
Chris Lattner7f816522010-04-11 07:45:24 +0000424 Diag(MemberLoc, diag::err_property_not_found)
425 << MemberName << QualType(OPT, 0);
426 if (Setter && !Getter)
427 Diag(Setter->getLocation(), diag::note_getter_unavailable)
428 << MemberName << BaseExpr->getSourceRange();
429 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000430}
431
432
433
Chris Lattnereb483eb2010-04-11 08:28:14 +0000434Action::OwningExprResult Sema::
435ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
436 IdentifierInfo &propertyName,
437 SourceLocation receiverNameLoc,
438 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000440 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000441 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
442 receiverNameLoc);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000443 if (IFace == 0) {
444 // If the "receiver" is 'super' in a method, handle it as an expression-like
445 // property reference.
446 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
447 if (receiverNamePtr->isStr("super")) {
448 if (CurMethod->isInstanceMethod()) {
449 QualType T =
450 Context.getObjCInterfaceType(CurMethod->getClassInterface());
451 T = Context.getObjCObjectPointerType(T);
452 Expr *SuperExpr = new (Context) ObjCSuperExpr(receiverNameLoc, T);
453
454 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
455 SuperExpr, &propertyName,
456 propertyNameLoc);
457 }
Mike Stump1eb44332009-09-09 15:08:12 +0000458
Chris Lattnereb483eb2010-04-11 08:28:14 +0000459 // Otherwise, if this is a class method, try dispatching to our
460 // superclass.
461 IFace = CurMethod->getClassInterface()->getSuperClass();
462 }
463
464 if (IFace == 0) {
465 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
466 return ExprError();
467 }
468 }
469
470 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000471 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000472 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000473
474 // If this reference is in an @implementation, check for 'private' methods.
475 if (!Getter)
476 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
477 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000478 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000479 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000480
481 if (Getter) {
482 // FIXME: refactor/share with ActOnMemberReference().
483 // Check if we can reference this property.
484 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
485 return ExprError();
486 }
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Steve Naroff61f72cb2009-03-09 21:12:44 +0000488 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000489 Selector SetterSel =
490 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000491 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000493 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000494 if (!Setter) {
495 // If this reference is in an @implementation, also check for 'private'
496 // methods.
497 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
498 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000499 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000500 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000501 }
502 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000503 if (!Setter)
504 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000505
506 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
507 return ExprError();
508
509 if (Getter || Setter) {
510 QualType PType;
511
512 if (Getter)
513 PType = Getter->getResultType();
514 else {
515 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
516 E = Setter->param_end(); PI != E; ++PI)
517 PType = (*PI)->getType();
518 }
Fariborz Jahanian09105f52009-08-20 17:02:02 +0000519 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(
Mike Stump1eb44332009-09-09 15:08:12 +0000520 Getter, PType, Setter,
Steve Naroff61f72cb2009-03-09 21:12:44 +0000521 propertyNameLoc, IFace, receiverNameLoc));
522 }
523 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
524 << &propertyName << Context.getObjCInterfaceType(IFace));
525}
526
Douglas Gregor47bd5432010-04-14 02:46:37 +0000527Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000528 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000529 SourceLocation NameLoc,
530 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000531 bool HasTrailingDot,
532 TypeTy *&ReceiverType) {
533 ReceiverType = 0;
534
Douglas Gregor47bd5432010-04-14 02:46:37 +0000535 // If the identifier is "super" and there is no trailing dot, we're
536 // messaging super.
537 if (IsSuper && !HasTrailingDot && S->isInObjcMethodScope())
538 return ObjCSuperMessage;
539
540 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
541 LookupName(Result, S);
542
543 switch (Result.getResultKind()) {
544 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000545 // Normal name lookup didn't find anything. If we're in an
546 // Objective-C method, look for ivars. If we find one, we're done!
547 // FIXME: This is a hack. Ivar lookup should be part of normal lookup.
548 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
549 ObjCInterfaceDecl *ClassDeclared;
550 if (Method->getClassInterface()->lookupInstanceVariable(Name,
551 ClassDeclared))
552 return ObjCInstanceMessage;
553 }
554
Douglas Gregor47bd5432010-04-14 02:46:37 +0000555 // Break out; we'll perform typo correction below.
556 break;
557
558 case LookupResult::NotFoundInCurrentInstantiation:
559 case LookupResult::FoundOverloaded:
560 case LookupResult::FoundUnresolvedValue:
561 case LookupResult::Ambiguous:
562 Result.suppressDiagnostics();
563 return ObjCInstanceMessage;
564
565 case LookupResult::Found: {
566 // We found something. If it's a type, then we have a class
567 // message. Otherwise, it's an instance message.
568 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000569 QualType T;
570 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
571 T = Context.getObjCInterfaceType(Class);
572 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
573 T = Context.getTypeDeclType(Type);
574 else
575 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000576
Douglas Gregor1569f952010-04-21 20:38:13 +0000577 // We have a class message, and T is the type we're
578 // messaging. Build source-location information for it.
579 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
580 ReceiverType = CreateLocInfoType(T, TSInfo).getAsOpaquePtr();
581 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000582 }
583 }
584
Douglas Gregoraaf87162010-04-14 20:04:41 +0000585 // Determine our typo-correction context.
586 CorrectTypoContext CTC = CTC_Expression;
587 if (ObjCMethodDecl *Method = getCurMethodDecl())
588 if (Method->getClassInterface() &&
589 Method->getClassInterface()->getSuperClass())
590 CTC = CTC_ObjCMessageReceiver;
591
592 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
593 if (Result.isSingleResult()) {
594 // If we found a declaration, correct when it refers to an Objective-C
595 // class.
596 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000597 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000598 Diag(NameLoc, diag::err_unknown_receiver_suggest)
599 << Name << Result.getLookupName()
600 << FixItHint::CreateReplacement(SourceRange(NameLoc),
601 ND->getNameAsString());
602 Diag(ND->getLocation(), diag::note_previous_decl)
603 << Corrected;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000604
Douglas Gregor1569f952010-04-21 20:38:13 +0000605 QualType T = Context.getObjCInterfaceType(Class);
606 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
607 ReceiverType = CreateLocInfoType(T, TSInfo).getAsOpaquePtr();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000608 return ObjCClassMessage;
609 }
610 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
611 Corrected.getAsIdentifierInfo()->isStr("super")) {
612 // If we've found the keyword "super", this is a send to super.
613 Diag(NameLoc, diag::err_unknown_receiver_suggest)
614 << Name << Corrected
615 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
616 Name = Corrected.getAsIdentifierInfo();
617 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000618 }
619 }
620
621 // Fall back: let the parser try to parse it as an instance message.
622 return ObjCInstanceMessage;
623}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000624
Douglas Gregor2725ca82010-04-21 19:57:20 +0000625Sema::OwningExprResult Sema::ActOnSuperMessage(Scope *S,
626 SourceLocation SuperLoc,
627 Selector Sel,
628 SourceLocation LBracLoc,
629 SourceLocation SelectorLoc,
630 SourceLocation RBracLoc,
631 MultiExprArg Args) {
632 // Determine whether we are inside a method or not.
633 ObjCMethodDecl *Method = getCurMethodDecl();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000634 if (!Method) {
635 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
636 return ExprError();
637 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000638
Douglas Gregorf95861a2010-04-21 20:01:04 +0000639 ObjCInterfaceDecl *Class = Method->getClassInterface();
640 if (!Class) {
641 Diag(SuperLoc, diag::error_no_super_class_message)
642 << Method->getDeclName();
643 return ExprError();
644 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000645
Douglas Gregorf95861a2010-04-21 20:01:04 +0000646 ObjCInterfaceDecl *Super = Class->getSuperClass();
647 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000648 // The current class does not have a superclass.
649 Diag(SuperLoc, diag::error_no_super_class) << Class->getIdentifier();
650 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000651 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000652
Douglas Gregorf95861a2010-04-21 20:01:04 +0000653 // We are in a method whose class has a superclass, so 'super'
654 // is acting as a keyword.
655 if (Method->isInstanceMethod()) {
656 // Since we are in an instance method, this is an instance
657 // message to the superclass instance.
658 QualType SuperTy = Context.getObjCInterfaceType(Super);
659 SuperTy = Context.getObjCObjectPointerType(SuperTy);
660 return BuildInstanceMessage(ExprArg(*this), SuperTy, SuperLoc,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000661 Sel, /*Method=*/0, LBracLoc, RBracLoc,
662 move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000663 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000664
665 // Since we are in a class method, this is a class message to
666 // the superclass.
667 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
668 Context.getObjCInterfaceType(Super),
Douglas Gregorf49bb082010-04-22 17:01:48 +0000669 SuperLoc, Sel, /*Method=*/0, LBracLoc, RBracLoc,
670 move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000671}
672
673/// \brief Build an Objective-C class message expression.
674///
675/// This routine takes care of both normal class messages and
676/// class messages to the superclass.
677///
678/// \param ReceiverTypeInfo Type source information that describes the
679/// receiver of this message. This may be NULL, in which case we are
680/// sending to the superclass and \p SuperLoc must be a valid source
681/// location.
682
683/// \param ReceiverType The type of the object receiving the
684/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
685/// type as that refers to. For a superclass send, this is the type of
686/// the superclass.
687///
688/// \param SuperLoc The location of the "super" keyword in a
689/// superclass message.
690///
691/// \param Sel The selector to which the message is being sent.
692///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000693/// \param Method The method that this class message is invoking, if
694/// already known.
695///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000696/// \param LBracLoc The location of the opening square bracket ']'.
697///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000698/// \param RBrac The location of the closing square bracket ']'.
699///
700/// \param Args The message arguments.
701Sema::OwningExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
702 QualType ReceiverType,
703 SourceLocation SuperLoc,
704 Selector Sel,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000705 ObjCMethodDecl *Method,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000706 SourceLocation LBracLoc,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000707 SourceLocation RBracLoc,
708 MultiExprArg ArgsIn) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000709 if (ReceiverType->isDependentType()) {
710 // If the receiver type is dependent, we can't type-check anything
711 // at this point. Build a dependent expression.
712 unsigned NumArgs = ArgsIn.size();
713 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
714 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
715 return Owned(ObjCMessageExpr::Create(Context, ReceiverType, LBracLoc,
716 ReceiverTypeInfo, Sel, /*Method=*/0,
717 Args, NumArgs, RBracLoc));
718 }
Chris Lattner15faee12010-04-12 05:38:43 +0000719
Douglas Gregor2725ca82010-04-21 19:57:20 +0000720 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Abramo Bagnarabd054db2010-05-20 10:00:11 +0000721 : ReceiverTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Douglas Gregor2725ca82010-04-21 19:57:20 +0000723 // Find the class to which we are sending this message.
724 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +0000725 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
726 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000727 Diag(Loc, diag::err_invalid_receiver_class_message)
728 << ReceiverType;
729 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +0000730 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000731 assert(Class && "We don't know which class we're messaging?");
732
733 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +0000734 if (!Method) {
735 if (Class->isForwardDecl()) {
736 // A forward class used in messaging is treated as a 'Class'
737 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
738 Method = LookupFactoryMethodInGlobalPool(Sel,
739 SourceRange(LBracLoc, RBracLoc));
740 if (Method)
741 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
742 << Method->getDeclName();
743 }
744 if (!Method)
745 Method = Class->lookupClassMethod(Sel);
746
747 // If we have an implementation in scope, check "private" methods.
748 if (!Method)
749 Method = LookupPrivateClassMethod(Sel, Class);
750
751 if (Method && DiagnoseUseOfDecl(Method, Loc))
752 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +0000753 }
Mike Stump1eb44332009-09-09 15:08:12 +0000754
Douglas Gregor2725ca82010-04-21 19:57:20 +0000755 // Check the argument types and determine the result type.
756 QualType ReturnType;
757 unsigned NumArgs = ArgsIn.size();
758 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
759 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
760 LBracLoc, RBracLoc, ReturnType)) {
761 for (unsigned I = 0; I != NumArgs; ++I)
762 Args[I]->Destroy(Context);
763 return ExprError();
764 }
Ted Kremenek4df728e2008-06-24 15:50:53 +0000765
Douglas Gregor2725ca82010-04-21 19:57:20 +0000766 // Construct the appropriate ObjCMessageExpr.
767 if (SuperLoc.isValid())
768 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
769 SuperLoc, /*IsInstanceSuper=*/false,
770 ReceiverType, Sel, Method, Args,
771 NumArgs, RBracLoc));
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Douglas Gregor2725ca82010-04-21 19:57:20 +0000773 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
774 ReceiverTypeInfo, Sel, Method, Args,
775 NumArgs, RBracLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000776}
777
Douglas Gregor2725ca82010-04-21 19:57:20 +0000778// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +0000779// ArgExprs is optional - if it is present, the number of expressions
780// is obtained from Sel.getNumArgs().
Douglas Gregor2725ca82010-04-21 19:57:20 +0000781Sema::OwningExprResult Sema::ActOnClassMessage(Scope *S,
782 TypeTy *Receiver,
783 Selector Sel,
784 SourceLocation LBracLoc,
785 SourceLocation SelectorLoc,
786 SourceLocation RBracLoc,
787 MultiExprArg Args) {
788 TypeSourceInfo *ReceiverTypeInfo;
789 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
790 if (ReceiverType.isNull())
791 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Douglas Gregor2725ca82010-04-21 19:57:20 +0000794 if (!ReceiverTypeInfo)
795 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
796
797 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000798 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Douglas Gregor39968ad2010-04-22 16:50:51 +0000799 LBracLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000800}
801
802/// \brief Build an Objective-C instance message expression.
803///
804/// This routine takes care of both normal instance messages and
805/// instance messages to the superclass instance.
806///
807/// \param Receiver The expression that computes the object that will
808/// receive this message. This may be empty, in which case we are
809/// sending to the superclass instance and \p SuperLoc must be a valid
810/// source location.
811///
812/// \param ReceiverType The (static) type of the object receiving the
813/// message. When a \p Receiver expression is provided, this is the
814/// same type as that expression. For a superclass instance send, this
815/// is a pointer to the type of the superclass.
816///
817/// \param SuperLoc The location of the "super" keyword in a
818/// superclass instance message.
819///
820/// \param Sel The selector to which the message is being sent.
821///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000822/// \param Method The method that this instance message is invoking, if
823/// already known.
824///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000825/// \param LBracLoc The location of the opening square bracket ']'.
826///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000827/// \param RBrac The location of the closing square bracket ']'.
828///
829/// \param Args The message arguments.
830Sema::OwningExprResult Sema::BuildInstanceMessage(ExprArg ReceiverE,
831 QualType ReceiverType,
832 SourceLocation SuperLoc,
833 Selector Sel,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000834 ObjCMethodDecl *Method,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000835 SourceLocation LBracLoc,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000836 SourceLocation RBracLoc,
837 MultiExprArg ArgsIn) {
838 // If we have a receiver expression, perform appropriate promotions
839 // and determine receiver type.
840 Expr *Receiver = ReceiverE.takeAs<Expr>();
841 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000842 if (Receiver->isTypeDependent()) {
843 // If the receiver is type-dependent, we can't type-check anything
844 // at this point. Build a dependent expression.
845 unsigned NumArgs = ArgsIn.size();
846 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
847 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
848 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
849 LBracLoc, Receiver, Sel,
850 /*Method=*/0, Args, NumArgs,
851 RBracLoc));
852 }
853
Douglas Gregor2725ca82010-04-21 19:57:20 +0000854 // If necessary, apply function/array conversion to the receiver.
855 // C99 6.7.5.3p[7,8].
856 DefaultFunctionArrayLvalueConversion(Receiver);
857 ReceiverType = Receiver->getType();
858 }
859
860 // The location of the receiver.
861 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Douglas Gregorf49bb082010-04-22 17:01:48 +0000863 if (!Method) {
864 // Handle messages to id.
865 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType() ||
866 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
867 Method = LookupInstanceMethodInGlobalPool(Sel,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000868 SourceRange(LBracLoc, RBracLoc));
Douglas Gregorf49bb082010-04-22 17:01:48 +0000869 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000870 Method = LookupFactoryMethodInGlobalPool(Sel,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000871 SourceRange(LBracLoc, RBracLoc));
872 } else if (ReceiverType->isObjCClassType() ||
873 ReceiverType->isObjCQualifiedClassType()) {
874 // Handle messages to Class.
875 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
876 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
877 // First check the public methods in the class interface.
878 Method = ClassDecl->lookupClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Douglas Gregorf49bb082010-04-22 17:01:48 +0000880 if (!Method)
881 Method = LookupPrivateClassMethod(Sel, ClassDecl);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000882
Douglas Gregorf49bb082010-04-22 17:01:48 +0000883 // FIXME: if we still haven't found a method, we need to look in
884 // protocols (if we have qualifiers).
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000885 }
Douglas Gregorf49bb082010-04-22 17:01:48 +0000886 if (Method && DiagnoseUseOfDecl(Method, Loc))
887 return ExprError();
Fariborz Jahanian268bc8c2009-03-03 22:19:15 +0000888 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000889 if (!Method) {
Douglas Gregorf49bb082010-04-22 17:01:48 +0000890 // If not messaging 'self', look for any factory method named 'Sel'.
891 if (!Receiver || !isSelfExpr(Receiver)) {
892 Method = LookupFactoryMethodInGlobalPool(Sel,
893 SourceRange(LBracLoc, RBracLoc));
894 if (!Method) {
895 // If no class (factory) method was found, check if an _instance_
896 // method of the same name exists in the root class only.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000897 Method = LookupInstanceMethodInGlobalPool(Sel,
898 SourceRange(LBracLoc, RBracLoc));
Douglas Gregorf49bb082010-04-22 17:01:48 +0000899 if (Method)
900 if (const ObjCInterfaceDecl *ID =
901 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
902 if (ID->getSuperClass())
903 Diag(Loc, diag::warn_root_inst_method_not_found)
904 << Sel << SourceRange(LBracLoc, RBracLoc);
905 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000906 }
907 }
908 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000909 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +0000910 ObjCInterfaceDecl* ClassDecl = 0;
911
912 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
913 // long as one of the protocols implements the selector (if not, warn).
914 if (const ObjCObjectPointerType *QIdTy
915 = ReceiverType->getAsObjCQualifiedIdType()) {
916 // Search protocols for instance methods.
917 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
918 E = QIdTy->qual_end(); I != E; ++I) {
919 ObjCProtocolDecl *PDecl = *I;
920 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
921 break;
922 // Since we aren't supporting "Class<foo>", look for a class method.
923 if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
924 break;
925 }
926 } else if (const ObjCObjectPointerType *OCIType
927 = ReceiverType->getAsObjCInterfacePointerType()) {
928 // We allow sending a message to a pointer to an interface (an object).
929 ClassDecl = OCIType->getInterfaceDecl();
930 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
931 // faster than the following method (which can do *many* linear searches).
932 // The idea is to add class info to InstanceMethodPool.
933 Method = ClassDecl->lookupInstanceMethod(Sel);
934
935 if (!Method) {
936 // Search protocol qualifiers.
937 for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(),
938 E = OCIType->qual_end(); QI != E; ++QI) {
939 if ((Method = (*QI)->lookupInstanceMethod(Sel)))
940 break;
941 }
942 }
943 if (!Method) {
944 // If we have implementations in scope, check "private" methods.
945 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
946
947 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
948 // If we still haven't found a method, look in the global pool. This
949 // behavior isn't very desirable, however we need it for GCC
950 // compatibility. FIXME: should we deviate??
951 if (OCIType->qual_empty()) {
952 Method = LookupInstanceMethodInGlobalPool(Sel,
953 SourceRange(LBracLoc, RBracLoc));
954 if (Method && !OCIType->getInterfaceDecl()->isForwardDecl())
955 Diag(Loc, diag::warn_maynot_respond)
956 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
957 }
958 }
959 }
960 if (Method && DiagnoseUseOfDecl(Method, Loc))
961 return ExprError();
962 } else if (!Context.getObjCIdType().isNull() &&
963 (ReceiverType->isPointerType() ||
964 (ReceiverType->isIntegerType() &&
965 ReceiverType->isScalarType()))) {
966 // Implicitly convert integers and pointers to 'id' but emit a warning.
967 Diag(Loc, diag::warn_bad_receiver_type)
968 << ReceiverType
969 << Receiver->getSourceRange();
970 if (ReceiverType->isPointerType())
971 ImpCastExprToType(Receiver, Context.getObjCIdType(),
972 CastExpr::CK_BitCast);
973 else
974 ImpCastExprToType(Receiver, Context.getObjCIdType(),
975 CastExpr::CK_IntegralToPointer);
976 ReceiverType = Receiver->getType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +0000977 }
Fariborz Jahanian3ba60612010-05-13 17:19:25 +0000978 else if (getLangOptions().CPlusPlus &&
979 !PerformContextuallyConvertToObjCId(Receiver)) {
980 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
981 Receiver = ICE->getSubExpr();
982 ReceiverType = Receiver->getType();
983 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +0000984 return BuildInstanceMessage(Owned(Receiver),
985 ReceiverType,
986 SuperLoc,
987 Sel,
988 Method,
989 LBracLoc,
990 RBracLoc,
991 move(ArgsIn));
Douglas Gregorf49bb082010-04-22 17:01:48 +0000992 } else {
993 // Reject other random receiver types (e.g. structs).
994 Diag(Loc, diag::err_bad_receiver_type)
995 << ReceiverType << Receiver->getSourceRange();
996 return ExprError();
997 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000998 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +0000999 }
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Douglas Gregor2725ca82010-04-21 19:57:20 +00001001 // Check the message arguments.
1002 unsigned NumArgs = ArgsIn.size();
1003 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1004 QualType ReturnType;
1005 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, false,
1006 LBracLoc, RBracLoc, ReturnType))
1007 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001008
Douglas Gregor2725ca82010-04-21 19:57:20 +00001009 // Construct the appropriate ObjCMessageExpr instance.
1010 if (SuperLoc.isValid())
1011 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
1012 SuperLoc, /*IsInstanceSuper=*/true,
1013 ReceiverType, Sel, Method,
1014 Args, NumArgs, RBracLoc));
Douglas Gregor04badcf2010-04-21 00:45:42 +00001015
Douglas Gregor2725ca82010-04-21 19:57:20 +00001016 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, Receiver,
1017 Sel, Method, Args, NumArgs, RBracLoc));
1018}
1019
1020// ActOnInstanceMessage - used for both unary and keyword messages.
1021// ArgExprs is optional - if it is present, the number of expressions
1022// is obtained from Sel.getNumArgs().
1023Sema::OwningExprResult Sema::ActOnInstanceMessage(Scope *S,
1024 ExprArg ReceiverE,
1025 Selector Sel,
1026 SourceLocation LBracLoc,
1027 SourceLocation SelectorLoc,
1028 SourceLocation RBracLoc,
1029 MultiExprArg Args) {
1030 Expr *Receiver = static_cast<Expr *>(ReceiverE.get());
1031 if (!Receiver)
1032 return ExprError();
1033
1034 return BuildInstanceMessage(move(ReceiverE), Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001035 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1036 LBracLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001037}
Chris Lattnereca7be62008-04-07 05:30:13 +00001038