blob: b9071e689480ef2dff446d116a0f9da9f39592c5 [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
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.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
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +000053 // Append the string.
54 StrBuf += S->getString();
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());
Chris Lattner85a932e2008-01-04 22:32:30 +000058 }
Mike Stump1eb44332009-09-09 15:08:12 +000059
Chris Lattner39c28bb2009-02-18 06:48:40 +000060 // Create the aggregate string with the appropriate content and location
61 // information.
62 S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(), false,
Chris Lattner2085fd62009-02-18 06:40:38 +000063 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000064 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000065 }
Mike Stump1eb44332009-09-09 15:08:12 +000066
Chris Lattner69039812009-02-18 06:01:06 +000067 // Verify that this composite string is acceptable for ObjC strings.
68 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000069 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000070
71 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000072 // the NSString interface is seen in this translation unit. Note: We
73 // don't use NSConstantString, since the runtime team considers this
74 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000075 QualType Ty = Context.getObjCConstantStringInterface();
76 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000077 Ty = Context.getObjCObjectPointerType(Ty);
Fariborz Jahanian8a437762010-04-23 23:19:04 +000078 } else if (getLangOptions().NoConstantCFStrings) {
79 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
80 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
81 LookupOrdinaryName);
82 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
83 Context.setObjCConstantStringInterface(StrIF);
84 Ty = Context.getObjCConstantStringInterface();
85 Ty = Context.getObjCObjectPointerType(Ty);
86 } else {
87 // If there is no NSConstantString interface defined then treat this
88 // as error and recover from it.
89 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
90 << S->getSourceRange();
91 Ty = Context.getObjCIdType();
92 }
Chris Lattner13fd7e52008-06-21 21:44:18 +000093 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +000094 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +000095 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
96 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +000097 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
98 Context.setObjCConstantStringInterface(StrIF);
99 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000100 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000101 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000102 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000103 // strings as untyped objects and let the runtime figure it out later.
104 Ty = Context.getObjCIdType();
105 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000106 }
Mike Stump1eb44332009-09-09 15:08:12 +0000107
Chris Lattnerf4b136f2009-02-18 06:13:04 +0000108 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +0000109}
110
Mike Stump1eb44332009-09-09 15:08:12 +0000111Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000112 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000113 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000114 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000115 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000116 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000117 StrTy = Context.DependentTy;
118 else {
119 std::string Str;
120 Context.getObjCEncodingForType(EncodedType, Str);
121
122 // The type of @encode is the same as the type of the corresponding string,
123 // which is an array type.
124 StrTy = Context.CharTy;
125 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000126 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000127 StrTy.addConst();
128 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
129 ArrayType::Normal, 0);
130 }
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Douglas Gregor81d34662010-04-20 15:39:42 +0000132 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000133}
134
Chris Lattner85a932e2008-01-04 22:32:30 +0000135Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
136 SourceLocation EncodeLoc,
137 SourceLocation LParenLoc,
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000138 TypeTy *ty,
Chris Lattner85a932e2008-01-04 22:32:30 +0000139 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000140 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000141 TypeSourceInfo *TInfo;
142 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
143 if (!TInfo)
144 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
145 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000146
Douglas Gregor81d34662010-04-20 15:39:42 +0000147 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000148}
149
150Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
151 SourceLocation AtLoc,
152 SourceLocation SelLoc,
153 SourceLocation LParenLoc,
154 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000155 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000156 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000157 if (!Method)
158 Method = LookupFactoryMethodInGlobalPool(Sel,
159 SourceRange(LParenLoc, RParenLoc));
160 if (!Method)
161 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
162
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000163 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
164 = ReferencedSelectors.find(Sel);
165 if (Pos == ReferencedSelectors.end())
166 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
167
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000168 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000169 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000170}
171
172Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
173 SourceLocation AtLoc,
174 SourceLocation ProtoLoc,
175 SourceLocation LParenLoc,
176 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000177 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000178 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000179 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000180 return true;
181 }
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000183 QualType Ty = Context.getObjCProtoType();
184 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000185 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000186 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000187 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000188}
189
Mike Stump1eb44332009-09-09 15:08:12 +0000190bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
191 Selector Sel, ObjCMethodDecl *Method,
Chris Lattner077bf5e2008-11-24 03:33:13 +0000192 bool isClassMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000193 SourceLocation lbrac, SourceLocation rbrac,
Mike Stump1eb44332009-09-09 15:08:12 +0000194 QualType &ReturnType) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000195 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000196 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000197 for (unsigned i = 0; i != NumArgs; i++) {
198 if (Args[i]->isTypeDependent())
199 continue;
200
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000201 DefaultArgumentPromotion(Args[i]);
Douglas Gregor92e986e2010-04-22 16:44:27 +0000202 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000203
Chris Lattner077bf5e2008-11-24 03:33:13 +0000204 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
205 diag::warn_inst_method_not_found;
206 Diag(lbrac, DiagID)
207 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000208 ReturnType = Context.getObjCIdType();
209 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000210 }
Mike Stump1eb44332009-09-09 15:08:12 +0000211
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000212 ReturnType = Method->getSendResultType();
Mike Stump1eb44332009-09-09 15:08:12 +0000213
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000214 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000215 // Method might have more arguments than selector indicates. This is due
216 // to addition of c-style arguments in method.
217 if (Method->param_size() > Sel.getNumArgs())
218 NumNamedArgs = Method->param_size();
219 // FIXME. This need be cleaned up.
220 if (NumArgs < NumNamedArgs) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000221 Diag(lbrac, diag::err_typecheck_call_too_few_args) << 2
222 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000223 return false;
224 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000225
Chris Lattner312531a2009-04-12 08:11:20 +0000226 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000227 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000228 // We can't do any type-checking on a type-dependent argument.
229 if (Args[i]->isTypeDependent())
230 continue;
231
Chris Lattner85a932e2008-01-04 22:32:30 +0000232 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000233
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000234 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000235 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000237 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
238 Param->getType(),
239 PDiag(diag::err_call_incomplete_argument)
240 << argExpr->getSourceRange()))
241 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000242
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000243 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
244 OwningExprResult ArgE = PerformCopyInitialization(Entity,
245 SourceLocation(),
246 Owned(argExpr->Retain()));
247 if (ArgE.isInvalid())
248 IsError = true;
249 else
250 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000251 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000252
253 // Promote additional arguments to variadic methods.
254 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000255 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
256 if (Args[i]->isTypeDependent())
257 continue;
258
Chris Lattner40378332010-05-16 04:01:30 +0000259 IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
Douglas Gregor92e986e2010-04-22 16:44:27 +0000260 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000261 } else {
262 // Check for extra arguments to non-variadic methods.
263 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000264 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000265 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000266 << 2 /*method*/ << NumNamedArgs << NumArgs
267 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000268 << SourceRange(Args[NumNamedArgs]->getLocStart(),
269 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000270 }
271 }
272
Douglas Gregor2725ca82010-04-21 19:57:20 +0000273 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000274 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000275}
276
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000277bool Sema::isSelfExpr(Expr *RExpr) {
278 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
279 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
280 return true;
281 return false;
282}
283
Steve Narofff1afaf62009-02-26 15:55:06 +0000284// Helper method for ActOnClassMethod/ActOnInstanceMethod.
285// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000286// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000287// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000288ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000289 ObjCInterfaceDecl *ClassDecl) {
290 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000291 // lookup in class and all superclasses
292 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000293 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000294 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000295
Steve Naroff5609ec02009-03-08 18:56:13 +0000296 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000297 if (!Method)
298 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Steve Naroff5609ec02009-03-08 18:56:13 +0000300 // Before we give up, check if the selector is an instance method.
301 // But only in the root. This matches gcc's behaviour and what the
302 // runtime expects.
303 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000304 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000305 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000306 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000307 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000308 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
309 }
Mike Stump1eb44332009-09-09 15:08:12 +0000310
Steve Naroff5609ec02009-03-08 18:56:13 +0000311 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000312 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000313 return Method;
314}
315
316ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
317 ObjCInterfaceDecl *ClassDecl) {
318 ObjCMethodDecl *Method = 0;
319 while (ClassDecl && !Method) {
320 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000321 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000322 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000323
Steve Naroff5609ec02009-03-08 18:56:13 +0000324 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000325 if (!Method)
326 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000327 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000328 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000329 return Method;
330}
331
Chris Lattner7f816522010-04-11 07:45:24 +0000332/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
333/// objective C interface. This is a property reference expression.
334Action::OwningExprResult Sema::
335HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000336 Expr *BaseExpr, DeclarationName MemberName,
337 SourceLocation MemberLoc) {
Chris Lattner7f816522010-04-11 07:45:24 +0000338 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
339 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
340 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
341
342 // Search for a declared property first.
343 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
344 // Check whether we can reference this property.
345 if (DiagnoseUseOfDecl(PD, MemberLoc))
346 return ExprError();
347 QualType ResTy = PD->getType();
348 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
349 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
350 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000351 ResTy = Getter->getSendResultType();
Chris Lattner7f816522010-04-11 07:45:24 +0000352 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
353 MemberLoc, BaseExpr));
354 }
355 // Check protocols on qualified interfaces.
356 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
357 E = OPT->qual_end(); I != E; ++I)
358 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
359 // Check whether we can reference this property.
360 if (DiagnoseUseOfDecl(PD, MemberLoc))
361 return ExprError();
362
363 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
364 MemberLoc, BaseExpr));
365 }
366 // If that failed, look for an "implicit" property by seeing if the nullary
367 // selector is implemented.
368
369 // FIXME: The logic for looking up nullary and unary selectors should be
370 // shared with the code in ActOnInstanceMessage.
371
372 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
373 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
374
375 // If this reference is in an @implementation, check for 'private' methods.
376 if (!Getter)
377 Getter = IFace->lookupPrivateInstanceMethod(Sel);
378
379 // Look through local category implementations associated with the class.
380 if (!Getter)
381 Getter = IFace->getCategoryInstanceMethod(Sel);
382 if (Getter) {
383 // Check if we can reference this property.
384 if (DiagnoseUseOfDecl(Getter, MemberLoc))
385 return ExprError();
386 }
387 // If we found a getter then this may be a valid dot-reference, we
388 // will look for the matching setter, in case it is needed.
389 Selector SetterSel =
390 SelectorTable::constructSetterName(PP.getIdentifierTable(),
391 PP.getSelectorTable(), Member);
392 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
393 if (!Setter) {
394 // If this reference is in an @implementation, also check for 'private'
395 // methods.
396 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
397 }
398 // Look through local category implementations associated with the class.
399 if (!Setter)
400 Setter = IFace->getCategoryInstanceMethod(SetterSel);
401
402 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
403 return ExprError();
404
405 if (Getter) {
406 QualType PType;
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000407 PType = Getter->getSendResultType();
Chris Lattner7f816522010-04-11 07:45:24 +0000408 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
409 Setter, MemberLoc, BaseExpr));
410 }
411
412 // Attempt to correct for typos in property names.
413 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000414 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
Chris Lattner7f816522010-04-11 07:45:24 +0000415 Res.getAsSingle<ObjCPropertyDecl>()) {
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000416 DeclarationName TypoResult = Res.getLookupName();
Chris Lattner7f816522010-04-11 07:45:24 +0000417 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000418 << MemberName << QualType(OPT, 0) << TypoResult
419 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000420 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
421 Diag(Property->getLocation(), diag::note_previous_decl)
422 << Property->getDeclName();
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000423 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc);
Chris Lattner7f816522010-04-11 07:45:24 +0000424 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000425
Chris Lattner7f816522010-04-11 07:45:24 +0000426 Diag(MemberLoc, diag::err_property_not_found)
427 << MemberName << QualType(OPT, 0);
428 if (Setter && !Getter)
429 Diag(Setter->getLocation(), diag::note_getter_unavailable)
430 << MemberName << BaseExpr->getSourceRange();
431 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000432}
433
434
435
Chris Lattnereb483eb2010-04-11 08:28:14 +0000436Action::OwningExprResult Sema::
437ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
438 IdentifierInfo &propertyName,
439 SourceLocation receiverNameLoc,
440 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000442 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000443 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
444 receiverNameLoc);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000445 if (IFace == 0) {
446 // If the "receiver" is 'super' in a method, handle it as an expression-like
447 // property reference.
448 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
449 if (receiverNamePtr->isStr("super")) {
450 if (CurMethod->isInstanceMethod()) {
451 QualType T =
452 Context.getObjCInterfaceType(CurMethod->getClassInterface());
453 T = Context.getObjCObjectPointerType(T);
454 Expr *SuperExpr = new (Context) ObjCSuperExpr(receiverNameLoc, T);
455
456 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
457 SuperExpr, &propertyName,
458 propertyNameLoc);
459 }
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Chris Lattnereb483eb2010-04-11 08:28:14 +0000461 // Otherwise, if this is a class method, try dispatching to our
462 // superclass.
463 IFace = CurMethod->getClassInterface()->getSuperClass();
464 }
465
466 if (IFace == 0) {
467 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
468 return ExprError();
469 }
470 }
471
472 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000473 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000474 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000475
476 // If this reference is in an @implementation, check for 'private' methods.
477 if (!Getter)
478 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
479 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000480 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000481 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000482
483 if (Getter) {
484 // FIXME: refactor/share with ActOnMemberReference().
485 // Check if we can reference this property.
486 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
487 return ExprError();
488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Steve Naroff61f72cb2009-03-09 21:12:44 +0000490 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000491 Selector SetterSel =
492 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000493 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000495 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000496 if (!Setter) {
497 // If this reference is in an @implementation, also check for 'private'
498 // methods.
499 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
500 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000501 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000502 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000503 }
504 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000505 if (!Setter)
506 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000507
508 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
509 return ExprError();
510
511 if (Getter || Setter) {
512 QualType PType;
513
514 if (Getter)
Douglas Gregor5291c3c2010-07-13 08:18:22 +0000515 PType = Getter->getSendResultType();
Steve Naroff61f72cb2009-03-09 21:12:44 +0000516 else {
517 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
518 E = Setter->param_end(); PI != E; ++PI)
519 PType = (*PI)->getType();
520 }
Fariborz Jahanian09105f52009-08-20 17:02:02 +0000521 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(
Mike Stump1eb44332009-09-09 15:08:12 +0000522 Getter, PType, Setter,
Steve Naroff61f72cb2009-03-09 21:12:44 +0000523 propertyNameLoc, IFace, receiverNameLoc));
524 }
525 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
526 << &propertyName << Context.getObjCInterfaceType(IFace));
527}
528
Douglas Gregor47bd5432010-04-14 02:46:37 +0000529Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000530 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000531 SourceLocation NameLoc,
532 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000533 bool HasTrailingDot,
534 TypeTy *&ReceiverType) {
535 ReceiverType = 0;
536
Douglas Gregor47bd5432010-04-14 02:46:37 +0000537 // If the identifier is "super" and there is no trailing dot, we're
538 // messaging super.
539 if (IsSuper && !HasTrailingDot && S->isInObjcMethodScope())
540 return ObjCSuperMessage;
541
542 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
543 LookupName(Result, S);
544
545 switch (Result.getResultKind()) {
546 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000547 // Normal name lookup didn't find anything. If we're in an
548 // Objective-C method, look for ivars. If we find one, we're done!
549 // FIXME: This is a hack. Ivar lookup should be part of normal lookup.
550 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
551 ObjCInterfaceDecl *ClassDeclared;
552 if (Method->getClassInterface()->lookupInstanceVariable(Name,
553 ClassDeclared))
554 return ObjCInstanceMessage;
555 }
556
Douglas Gregor47bd5432010-04-14 02:46:37 +0000557 // Break out; we'll perform typo correction below.
558 break;
559
560 case LookupResult::NotFoundInCurrentInstantiation:
561 case LookupResult::FoundOverloaded:
562 case LookupResult::FoundUnresolvedValue:
563 case LookupResult::Ambiguous:
564 Result.suppressDiagnostics();
565 return ObjCInstanceMessage;
566
567 case LookupResult::Found: {
568 // We found something. If it's a type, then we have a class
569 // message. Otherwise, it's an instance message.
570 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000571 QualType T;
572 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
573 T = Context.getObjCInterfaceType(Class);
574 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
575 T = Context.getTypeDeclType(Type);
576 else
577 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000578
Douglas Gregor1569f952010-04-21 20:38:13 +0000579 // We have a class message, and T is the type we're
580 // messaging. Build source-location information for it.
581 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
582 ReceiverType = CreateLocInfoType(T, TSInfo).getAsOpaquePtr();
583 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000584 }
585 }
586
Douglas Gregoraaf87162010-04-14 20:04:41 +0000587 // Determine our typo-correction context.
588 CorrectTypoContext CTC = CTC_Expression;
589 if (ObjCMethodDecl *Method = getCurMethodDecl())
590 if (Method->getClassInterface() &&
591 Method->getClassInterface()->getSuperClass())
592 CTC = CTC_ObjCMessageReceiver;
593
594 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
595 if (Result.isSingleResult()) {
596 // If we found a declaration, correct when it refers to an Objective-C
597 // class.
598 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000599 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000600 Diag(NameLoc, diag::err_unknown_receiver_suggest)
601 << Name << Result.getLookupName()
602 << FixItHint::CreateReplacement(SourceRange(NameLoc),
603 ND->getNameAsString());
604 Diag(ND->getLocation(), diag::note_previous_decl)
605 << Corrected;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000606
Douglas Gregor1569f952010-04-21 20:38:13 +0000607 QualType T = Context.getObjCInterfaceType(Class);
608 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
609 ReceiverType = CreateLocInfoType(T, TSInfo).getAsOpaquePtr();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000610 return ObjCClassMessage;
611 }
612 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
613 Corrected.getAsIdentifierInfo()->isStr("super")) {
614 // If we've found the keyword "super", this is a send to super.
615 Diag(NameLoc, diag::err_unknown_receiver_suggest)
616 << Name << Corrected
617 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
618 Name = Corrected.getAsIdentifierInfo();
619 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000620 }
621 }
622
623 // Fall back: let the parser try to parse it as an instance message.
624 return ObjCInstanceMessage;
625}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000626
Douglas Gregor2725ca82010-04-21 19:57:20 +0000627Sema::OwningExprResult Sema::ActOnSuperMessage(Scope *S,
628 SourceLocation SuperLoc,
629 Selector Sel,
630 SourceLocation LBracLoc,
631 SourceLocation SelectorLoc,
632 SourceLocation RBracLoc,
633 MultiExprArg Args) {
634 // Determine whether we are inside a method or not.
635 ObjCMethodDecl *Method = getCurMethodDecl();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000636 if (!Method) {
637 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
638 return ExprError();
639 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000640
Douglas Gregorf95861a2010-04-21 20:01:04 +0000641 ObjCInterfaceDecl *Class = Method->getClassInterface();
642 if (!Class) {
643 Diag(SuperLoc, diag::error_no_super_class_message)
644 << Method->getDeclName();
645 return ExprError();
646 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000647
Douglas Gregorf95861a2010-04-21 20:01:04 +0000648 ObjCInterfaceDecl *Super = Class->getSuperClass();
649 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000650 // The current class does not have a superclass.
651 Diag(SuperLoc, diag::error_no_super_class) << Class->getIdentifier();
652 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000653 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000654
Douglas Gregorf95861a2010-04-21 20:01:04 +0000655 // We are in a method whose class has a superclass, so 'super'
656 // is acting as a keyword.
657 if (Method->isInstanceMethod()) {
658 // Since we are in an instance method, this is an instance
659 // message to the superclass instance.
660 QualType SuperTy = Context.getObjCInterfaceType(Super);
661 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +0000662 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000663 Sel, /*Method=*/0, LBracLoc, RBracLoc,
664 move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000665 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000666
667 // Since we are in a class method, this is a class message to
668 // the superclass.
669 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
670 Context.getObjCInterfaceType(Super),
Douglas Gregorf49bb082010-04-22 17:01:48 +0000671 SuperLoc, Sel, /*Method=*/0, LBracLoc, RBracLoc,
672 move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000673}
674
675/// \brief Build an Objective-C class message expression.
676///
677/// This routine takes care of both normal class messages and
678/// class messages to the superclass.
679///
680/// \param ReceiverTypeInfo Type source information that describes the
681/// receiver of this message. This may be NULL, in which case we are
682/// sending to the superclass and \p SuperLoc must be a valid source
683/// location.
684
685/// \param ReceiverType The type of the object receiving the
686/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
687/// type as that refers to. For a superclass send, this is the type of
688/// the superclass.
689///
690/// \param SuperLoc The location of the "super" keyword in a
691/// superclass message.
692///
693/// \param Sel The selector to which the message is being sent.
694///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000695/// \param Method The method that this class message is invoking, if
696/// already known.
697///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000698/// \param LBracLoc The location of the opening square bracket ']'.
699///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000700/// \param RBrac The location of the closing square bracket ']'.
701///
702/// \param Args The message arguments.
703Sema::OwningExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
704 QualType ReceiverType,
705 SourceLocation SuperLoc,
706 Selector Sel,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000707 ObjCMethodDecl *Method,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000708 SourceLocation LBracLoc,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000709 SourceLocation RBracLoc,
710 MultiExprArg ArgsIn) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000711 if (ReceiverType->isDependentType()) {
712 // If the receiver type is dependent, we can't type-check anything
713 // at this point. Build a dependent expression.
714 unsigned NumArgs = ArgsIn.size();
715 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
716 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
717 return Owned(ObjCMessageExpr::Create(Context, ReceiverType, LBracLoc,
718 ReceiverTypeInfo, Sel, /*Method=*/0,
719 Args, NumArgs, RBracLoc));
720 }
Chris Lattner15faee12010-04-12 05:38:43 +0000721
Douglas Gregor2725ca82010-04-21 19:57:20 +0000722 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Abramo Bagnarabd054db2010-05-20 10:00:11 +0000723 : ReceiverTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Douglas Gregor2725ca82010-04-21 19:57:20 +0000725 // Find the class to which we are sending this message.
726 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +0000727 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
728 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000729 Diag(Loc, diag::err_invalid_receiver_class_message)
730 << ReceiverType;
731 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +0000732 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000733 assert(Class && "We don't know which class we're messaging?");
734
735 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +0000736 if (!Method) {
737 if (Class->isForwardDecl()) {
738 // A forward class used in messaging is treated as a 'Class'
739 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
740 Method = LookupFactoryMethodInGlobalPool(Sel,
741 SourceRange(LBracLoc, RBracLoc));
742 if (Method)
743 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
744 << Method->getDeclName();
745 }
746 if (!Method)
747 Method = Class->lookupClassMethod(Sel);
748
749 // If we have an implementation in scope, check "private" methods.
750 if (!Method)
751 Method = LookupPrivateClassMethod(Sel, Class);
752
753 if (Method && DiagnoseUseOfDecl(Method, Loc))
754 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +0000755 }
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Douglas Gregor2725ca82010-04-21 19:57:20 +0000757 // Check the argument types and determine the result type.
758 QualType ReturnType;
759 unsigned NumArgs = ArgsIn.size();
760 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
761 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
Douglas Gregorff331c12010-07-25 18:17:45 +0000762 LBracLoc, RBracLoc, ReturnType))
Douglas Gregor2725ca82010-04-21 19:57:20 +0000763 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +0000764
Douglas Gregor2725ca82010-04-21 19:57:20 +0000765 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000766 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +0000767 if (SuperLoc.isValid())
Douglas Gregor2d6b0e92010-05-22 05:17:18 +0000768 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
769 SuperLoc, /*IsInstanceSuper=*/false,
770 ReceiverType, Sel, Method, Args,
771 NumArgs, RBracLoc);
772 else
773 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
774 ReceiverTypeInfo, Sel, Method, Args,
775 NumArgs, RBracLoc);
776 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +0000777}
778
Douglas Gregor2725ca82010-04-21 19:57:20 +0000779// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +0000780// ArgExprs is optional - if it is present, the number of expressions
781// is obtained from Sel.getNumArgs().
Douglas Gregor2725ca82010-04-21 19:57:20 +0000782Sema::OwningExprResult Sema::ActOnClassMessage(Scope *S,
783 TypeTy *Receiver,
784 Selector Sel,
785 SourceLocation LBracLoc,
786 SourceLocation SelectorLoc,
787 SourceLocation RBracLoc,
788 MultiExprArg Args) {
789 TypeSourceInfo *ReceiverTypeInfo;
790 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
791 if (ReceiverType.isNull())
792 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Mike Stump1eb44332009-09-09 15:08:12 +0000794
Douglas Gregor2725ca82010-04-21 19:57:20 +0000795 if (!ReceiverTypeInfo)
796 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
797
798 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000799 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Douglas Gregor39968ad2010-04-22 16:50:51 +0000800 LBracLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000801}
802
803/// \brief Build an Objective-C instance message expression.
804///
805/// This routine takes care of both normal instance messages and
806/// instance messages to the superclass instance.
807///
808/// \param Receiver The expression that computes the object that will
809/// receive this message. This may be empty, in which case we are
810/// sending to the superclass instance and \p SuperLoc must be a valid
811/// source location.
812///
813/// \param ReceiverType The (static) type of the object receiving the
814/// message. When a \p Receiver expression is provided, this is the
815/// same type as that expression. For a superclass instance send, this
816/// is a pointer to the type of the superclass.
817///
818/// \param SuperLoc The location of the "super" keyword in a
819/// superclass instance message.
820///
821/// \param Sel The selector to which the message is being sent.
822///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000823/// \param Method The method that this instance message is invoking, if
824/// already known.
825///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000826/// \param LBracLoc The location of the opening square bracket ']'.
827///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000828/// \param RBrac The location of the closing square bracket ']'.
829///
830/// \param Args The message arguments.
John McCall9ae2f072010-08-23 23:25:46 +0000831Sema::OwningExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000832 QualType ReceiverType,
833 SourceLocation SuperLoc,
834 Selector Sel,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000835 ObjCMethodDecl *Method,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000836 SourceLocation LBracLoc,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000837 SourceLocation RBracLoc,
838 MultiExprArg ArgsIn) {
839 // If we have a receiver expression, perform appropriate promotions
840 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000841 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.
Fariborz Jahanianba551982010-08-10 18:10:50 +0000865 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000866 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +0000867 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
868 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000869 SourceRange(LBracLoc, RBracLoc),
870 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +0000871 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000872 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000873 SourceRange(LBracLoc, RBracLoc),
874 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +0000875 } else if (ReceiverType->isObjCClassType() ||
876 ReceiverType->isObjCQualifiedClassType()) {
877 // Handle messages to Class.
878 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
879 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
880 // First check the public methods in the class interface.
881 Method = ClassDecl->lookupClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Douglas Gregorf49bb082010-04-22 17:01:48 +0000883 if (!Method)
884 Method = LookupPrivateClassMethod(Sel, ClassDecl);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000885
Douglas Gregorf49bb082010-04-22 17:01:48 +0000886 // FIXME: if we still haven't found a method, we need to look in
887 // protocols (if we have qualifiers).
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000888 }
Douglas Gregorf49bb082010-04-22 17:01:48 +0000889 if (Method && DiagnoseUseOfDecl(Method, Loc))
890 return ExprError();
Fariborz Jahanian268bc8c2009-03-03 22:19:15 +0000891 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000892 if (!Method) {
Douglas Gregorf49bb082010-04-22 17:01:48 +0000893 // If not messaging 'self', look for any factory method named 'Sel'.
894 if (!Receiver || !isSelfExpr(Receiver)) {
895 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000896 SourceRange(LBracLoc, RBracLoc),
897 true);
Douglas Gregorf49bb082010-04-22 17:01:48 +0000898 if (!Method) {
899 // If no class (factory) method was found, check if an _instance_
900 // method of the same name exists in the root class only.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000901 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000902 SourceRange(LBracLoc, RBracLoc),
903 true);
Douglas Gregorf49bb082010-04-22 17:01:48 +0000904 if (Method)
905 if (const ObjCInterfaceDecl *ID =
906 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
907 if (ID->getSuperClass())
908 Diag(Loc, diag::warn_root_inst_method_not_found)
909 << Sel << SourceRange(LBracLoc, RBracLoc);
910 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000911 }
912 }
913 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000914 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +0000915 ObjCInterfaceDecl* ClassDecl = 0;
916
917 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
918 // long as one of the protocols implements the selector (if not, warn).
919 if (const ObjCObjectPointerType *QIdTy
920 = ReceiverType->getAsObjCQualifiedIdType()) {
921 // Search protocols for instance methods.
922 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
923 E = QIdTy->qual_end(); I != E; ++I) {
924 ObjCProtocolDecl *PDecl = *I;
925 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
926 break;
927 // Since we aren't supporting "Class<foo>", look for a class method.
928 if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
929 break;
930 }
931 } else if (const ObjCObjectPointerType *OCIType
932 = ReceiverType->getAsObjCInterfacePointerType()) {
933 // We allow sending a message to a pointer to an interface (an object).
934 ClassDecl = OCIType->getInterfaceDecl();
935 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
936 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +0000937 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +0000938 Method = ClassDecl->lookupInstanceMethod(Sel);
939
940 if (!Method) {
941 // Search protocol qualifiers.
942 for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(),
943 E = OCIType->qual_end(); QI != E; ++QI) {
944 if ((Method = (*QI)->lookupInstanceMethod(Sel)))
945 break;
946 }
947 }
948 if (!Method) {
949 // If we have implementations in scope, check "private" methods.
950 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
951
952 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
953 // If we still haven't found a method, look in the global pool. This
954 // behavior isn't very desirable, however we need it for GCC
955 // compatibility. FIXME: should we deviate??
956 if (OCIType->qual_empty()) {
957 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000958 SourceRange(LBracLoc, RBracLoc));
Douglas Gregorf49bb082010-04-22 17:01:48 +0000959 if (Method && !OCIType->getInterfaceDecl()->isForwardDecl())
960 Diag(Loc, diag::warn_maynot_respond)
961 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
962 }
963 }
964 }
965 if (Method && DiagnoseUseOfDecl(Method, Loc))
966 return ExprError();
967 } else if (!Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +0000968 (ReceiverType->isPointerType() ||
969 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +0000970 // Implicitly convert integers and pointers to 'id' but emit a warning.
971 Diag(Loc, diag::warn_bad_receiver_type)
972 << ReceiverType
973 << Receiver->getSourceRange();
974 if (ReceiverType->isPointerType())
975 ImpCastExprToType(Receiver, Context.getObjCIdType(),
976 CastExpr::CK_BitCast);
977 else
978 ImpCastExprToType(Receiver, Context.getObjCIdType(),
979 CastExpr::CK_IntegralToPointer);
980 ReceiverType = Receiver->getType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +0000981 }
Fariborz Jahanian3ba60612010-05-13 17:19:25 +0000982 else if (getLangOptions().CPlusPlus &&
983 !PerformContextuallyConvertToObjCId(Receiver)) {
984 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
985 Receiver = ICE->getSubExpr();
986 ReceiverType = Receiver->getType();
987 }
John McCall9ae2f072010-08-23 23:25:46 +0000988 return BuildInstanceMessage(Receiver,
Fariborz Jahanian79d3f042010-05-12 23:29:11 +0000989 ReceiverType,
990 SuperLoc,
991 Sel,
992 Method,
993 LBracLoc,
994 RBracLoc,
995 move(ArgsIn));
Douglas Gregorf49bb082010-04-22 17:01:48 +0000996 } else {
997 // Reject other random receiver types (e.g. structs).
998 Diag(Loc, diag::err_bad_receiver_type)
999 << ReceiverType << Receiver->getSourceRange();
1000 return ExprError();
1001 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001002 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001003 }
Mike Stump1eb44332009-09-09 15:08:12 +00001004
Douglas Gregor2725ca82010-04-21 19:57:20 +00001005 // Check the message arguments.
1006 unsigned NumArgs = ArgsIn.size();
1007 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1008 QualType ReturnType;
1009 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, false,
1010 LBracLoc, RBracLoc, ReturnType))
1011 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001012
1013 if (!ReturnType->isVoidType()) {
1014 if (RequireCompleteType(LBracLoc, ReturnType,
1015 diag::err_illegal_message_expr_incomplete_type))
1016 return ExprError();
1017 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001018
Douglas Gregor2725ca82010-04-21 19:57:20 +00001019 // Construct the appropriate ObjCMessageExpr instance.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001020 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001021 if (SuperLoc.isValid())
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001022 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
1023 SuperLoc, /*IsInstanceSuper=*/true,
1024 ReceiverType, Sel, Method,
1025 Args, NumArgs, RBracLoc);
1026 else
1027 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, Receiver,
1028 Sel, Method, Args, NumArgs, RBracLoc);
1029 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001030}
1031
1032// ActOnInstanceMessage - used for both unary and keyword messages.
1033// ArgExprs is optional - if it is present, the number of expressions
1034// is obtained from Sel.getNumArgs().
1035Sema::OwningExprResult Sema::ActOnInstanceMessage(Scope *S,
John McCall9ae2f072010-08-23 23:25:46 +00001036 Expr *Receiver,
Douglas Gregor2725ca82010-04-21 19:57:20 +00001037 Selector Sel,
1038 SourceLocation LBracLoc,
1039 SourceLocation SelectorLoc,
1040 SourceLocation RBracLoc,
1041 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001042 if (!Receiver)
1043 return ExprError();
1044
John McCall9ae2f072010-08-23 23:25:46 +00001045 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001046 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1047 LBracLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001048}
Chris Lattnereca7be62008-04-07 05:30:13 +00001049