blob: fcf2df6987caa8ccfc5f2dc79b63a53d3b9ea69e [file] [log] [blame]
Chris Lattner85a932e2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattner7f816522010-04-11 07:45:24 +000015#include "Lookup.h"
Douglas Gregor688fc9b2010-04-21 23:24:10 +000016#include "SemaInit.h"
Chris Lattner85a932e2008-01-04 22:32:30 +000017#include "clang/AST/ASTContext.h"
18#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000019#include "clang/AST/ExprObjC.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000020#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000021#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000022#include "clang/Lex/Preprocessor.h"
23
Chris Lattner85a932e2008-01-04 22:32:30 +000024using namespace clang;
25
Mike Stump1eb44332009-09-09 15:08:12 +000026Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
Chris Lattner39c28bb2009-02-18 06:48:40 +000027 ExprTy **strings,
Chris Lattner85a932e2008-01-04 22:32:30 +000028 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000029 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
30
Chris Lattnerf4b136f2009-02-18 06:13:04 +000031 // Most ObjC strings are formed out of a single piece. However, we *can*
32 // have strings formed out of multiple @ strings with multiple pptokens in
33 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
34 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner39c28bb2009-02-18 06:48:40 +000035 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000036
Chris Lattnerf4b136f2009-02-18 06:13:04 +000037 // If we have a multi-part string, merge it all together.
38 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000039 // Concatenate objc strings.
Chris Lattner39c28bb2009-02-18 06:48:40 +000040 llvm::SmallString<128> StrBuf;
41 llvm::SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000042
Chris Lattner726e1682009-02-18 05:49:11 +000043 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000044 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000045
Chris Lattner39c28bb2009-02-18 06:48:40 +000046 // ObjC strings can't be wide.
Chris Lattnerf4b136f2009-02-18 06:13:04 +000047 if (S->isWide()) {
48 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
49 << S->getSourceRange();
50 return true;
51 }
Mike Stump1eb44332009-09-09 15:08:12 +000052
Chris Lattner39c28bb2009-02-18 06:48:40 +000053 // Get the string data.
54 StrBuf.append(S->getStrData(), S->getStrData()+S->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +000055
Chris Lattner39c28bb2009-02-18 06:48:40 +000056 // Get the locations of the string tokens.
57 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Mike Stump1eb44332009-09-09 15:08:12 +000058
Chris Lattner39c28bb2009-02-18 06:48:40 +000059 // Free the temporary string.
Ted Kremenek8189cde2009-02-07 01:47:29 +000060 S->Destroy(Context);
Chris Lattner85a932e2008-01-04 22:32:30 +000061 }
Mike Stump1eb44332009-09-09 15:08:12 +000062
Chris Lattner39c28bb2009-02-18 06:48:40 +000063 // Create the aggregate string with the appropriate content and location
64 // information.
65 S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(), false,
Chris Lattner2085fd62009-02-18 06:40:38 +000066 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000067 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000068 }
Mike Stump1eb44332009-09-09 15:08:12 +000069
Chris Lattner69039812009-02-18 06:01:06 +000070 // Verify that this composite string is acceptable for ObjC strings.
71 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000072 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000073
74 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000075 // the NSString interface is seen in this translation unit. Note: We
76 // don't use NSConstantString, since the runtime team considers this
77 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000078 QualType Ty = Context.getObjCConstantStringInterface();
79 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000080 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattner13fd7e52008-06-21 21:44:18 +000081 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +000082 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +000083 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
84 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +000085 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
86 Context.setObjCConstantStringInterface(StrIF);
87 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +000088 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +000089 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +000090 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +000091 // strings as untyped objects and let the runtime figure it out later.
92 Ty = Context.getObjCIdType();
93 }
Chris Lattner13fd7e52008-06-21 21:44:18 +000094 }
Mike Stump1eb44332009-09-09 15:08:12 +000095
Chris Lattnerf4b136f2009-02-18 06:13:04 +000096 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +000097}
98
Mike Stump1eb44332009-09-09 15:08:12 +000099Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000100 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000101 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000102 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000103 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000104 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000105 StrTy = Context.DependentTy;
106 else {
107 std::string Str;
108 Context.getObjCEncodingForType(EncodedType, Str);
109
110 // The type of @encode is the same as the type of the corresponding string,
111 // which is an array type.
112 StrTy = Context.CharTy;
113 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000114 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000115 StrTy.addConst();
116 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
117 ArrayType::Normal, 0);
118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Douglas Gregor81d34662010-04-20 15:39:42 +0000120 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000121}
122
Chris Lattner85a932e2008-01-04 22:32:30 +0000123Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
124 SourceLocation EncodeLoc,
125 SourceLocation LParenLoc,
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000126 TypeTy *ty,
Chris Lattner85a932e2008-01-04 22:32:30 +0000127 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000128 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000129 TypeSourceInfo *TInfo;
130 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
131 if (!TInfo)
132 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
133 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000134
Douglas Gregor81d34662010-04-20 15:39:42 +0000135 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000136}
137
138Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
139 SourceLocation AtLoc,
140 SourceLocation SelLoc,
141 SourceLocation LParenLoc,
142 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000143 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian835ed7f2009-08-22 21:13:55 +0000144 SourceRange(LParenLoc, RParenLoc), false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000145 if (!Method)
146 Method = LookupFactoryMethodInGlobalPool(Sel,
147 SourceRange(LParenLoc, RParenLoc));
148 if (!Method)
149 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
150
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000151 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000152 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000153}
154
155Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
156 SourceLocation AtLoc,
157 SourceLocation ProtoLoc,
158 SourceLocation LParenLoc,
159 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000160 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000161 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000162 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000163 return true;
164 }
Mike Stump1eb44332009-09-09 15:08:12 +0000165
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000166 QualType Ty = Context.getObjCProtoType();
167 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000168 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000169 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000170 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000171}
172
Mike Stump1eb44332009-09-09 15:08:12 +0000173bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
174 Selector Sel, ObjCMethodDecl *Method,
Chris Lattner077bf5e2008-11-24 03:33:13 +0000175 bool isClassMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000176 SourceLocation lbrac, SourceLocation rbrac,
Mike Stump1eb44332009-09-09 15:08:12 +0000177 QualType &ReturnType) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000178 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000179 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000180 for (unsigned i = 0; i != NumArgs; i++) {
181 if (Args[i]->isTypeDependent())
182 continue;
183
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000184 DefaultArgumentPromotion(Args[i]);
Douglas Gregor92e986e2010-04-22 16:44:27 +0000185 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000186
Chris Lattner077bf5e2008-11-24 03:33:13 +0000187 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
188 diag::warn_inst_method_not_found;
189 Diag(lbrac, DiagID)
190 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000191 ReturnType = Context.getObjCIdType();
192 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000193 }
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Douglas Gregor2725ca82010-04-21 19:57:20 +0000195 ReturnType = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000197 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000198 // Method might have more arguments than selector indicates. This is due
199 // to addition of c-style arguments in method.
200 if (Method->param_size() > Sel.getNumArgs())
201 NumNamedArgs = Method->param_size();
202 // FIXME. This need be cleaned up.
203 if (NumArgs < NumNamedArgs) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000204 Diag(lbrac, diag::err_typecheck_call_too_few_args) << 2
205 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000206 return false;
207 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000208
Chris Lattner312531a2009-04-12 08:11:20 +0000209 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000210 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000211 // We can't do any type-checking on a type-dependent argument.
212 if (Args[i]->isTypeDependent())
213 continue;
214
Chris Lattner85a932e2008-01-04 22:32:30 +0000215 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000216
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000217 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000218 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000219
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000220 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
221 Param->getType(),
222 PDiag(diag::err_call_incomplete_argument)
223 << argExpr->getSourceRange()))
224 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000225
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000226 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
227 OwningExprResult ArgE = PerformCopyInitialization(Entity,
228 SourceLocation(),
229 Owned(argExpr->Retain()));
230 if (ArgE.isInvalid())
231 IsError = true;
232 else
233 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000234 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000235
236 // Promote additional arguments to variadic methods.
237 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000238 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
239 if (Args[i]->isTypeDependent())
240 continue;
241
Chris Lattner312531a2009-04-12 08:11:20 +0000242 IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod);
Douglas Gregor92e986e2010-04-22 16:44:27 +0000243 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000244 } else {
245 // Check for extra arguments to non-variadic methods.
246 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000247 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000248 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000249 << 2 /*method*/ << NumNamedArgs << NumArgs
250 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000251 << SourceRange(Args[NumNamedArgs]->getLocStart(),
252 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000253 }
254 }
255
Douglas Gregor2725ca82010-04-21 19:57:20 +0000256 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000257 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000258}
259
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000260bool Sema::isSelfExpr(Expr *RExpr) {
261 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
262 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
263 return true;
264 return false;
265}
266
Steve Narofff1afaf62009-02-26 15:55:06 +0000267// Helper method for ActOnClassMethod/ActOnInstanceMethod.
268// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000269// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000270// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000271ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000272 ObjCInterfaceDecl *ClassDecl) {
273 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000274 // lookup in class and all superclasses
275 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000276 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000277 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Steve Naroff5609ec02009-03-08 18:56:13 +0000279 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000280 if (!Method)
281 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Steve Naroff5609ec02009-03-08 18:56:13 +0000283 // Before we give up, check if the selector is an instance method.
284 // But only in the root. This matches gcc's behaviour and what the
285 // runtime expects.
286 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000287 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000288 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000289 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000290 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000291 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
292 }
Mike Stump1eb44332009-09-09 15:08:12 +0000293
Steve Naroff5609ec02009-03-08 18:56:13 +0000294 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000295 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000296 return Method;
297}
298
299ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
300 ObjCInterfaceDecl *ClassDecl) {
301 ObjCMethodDecl *Method = 0;
302 while (ClassDecl && !Method) {
303 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000304 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000305 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000306
Steve Naroff5609ec02009-03-08 18:56:13 +0000307 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000308 if (!Method)
309 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000310 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000311 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000312 return Method;
313}
314
Chris Lattner7f816522010-04-11 07:45:24 +0000315/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
316/// objective C interface. This is a property reference expression.
317Action::OwningExprResult Sema::
318HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000319 Expr *BaseExpr, DeclarationName MemberName,
320 SourceLocation MemberLoc) {
Chris Lattner7f816522010-04-11 07:45:24 +0000321 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
322 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
323 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
324
325 // Search for a declared property first.
326 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
327 // Check whether we can reference this property.
328 if (DiagnoseUseOfDecl(PD, MemberLoc))
329 return ExprError();
330 QualType ResTy = PD->getType();
331 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
332 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
333 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
334 ResTy = Getter->getResultType();
335 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
336 MemberLoc, BaseExpr));
337 }
338 // Check protocols on qualified interfaces.
339 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
340 E = OPT->qual_end(); I != E; ++I)
341 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
342 // Check whether we can reference this property.
343 if (DiagnoseUseOfDecl(PD, MemberLoc))
344 return ExprError();
345
346 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
347 MemberLoc, BaseExpr));
348 }
349 // If that failed, look for an "implicit" property by seeing if the nullary
350 // selector is implemented.
351
352 // FIXME: The logic for looking up nullary and unary selectors should be
353 // shared with the code in ActOnInstanceMessage.
354
355 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
356 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
357
358 // If this reference is in an @implementation, check for 'private' methods.
359 if (!Getter)
360 Getter = IFace->lookupPrivateInstanceMethod(Sel);
361
362 // Look through local category implementations associated with the class.
363 if (!Getter)
364 Getter = IFace->getCategoryInstanceMethod(Sel);
365 if (Getter) {
366 // Check if we can reference this property.
367 if (DiagnoseUseOfDecl(Getter, MemberLoc))
368 return ExprError();
369 }
370 // If we found a getter then this may be a valid dot-reference, we
371 // will look for the matching setter, in case it is needed.
372 Selector SetterSel =
373 SelectorTable::constructSetterName(PP.getIdentifierTable(),
374 PP.getSelectorTable(), Member);
375 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
376 if (!Setter) {
377 // If this reference is in an @implementation, also check for 'private'
378 // methods.
379 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
380 }
381 // Look through local category implementations associated with the class.
382 if (!Setter)
383 Setter = IFace->getCategoryInstanceMethod(SetterSel);
384
385 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
386 return ExprError();
387
388 if (Getter) {
389 QualType PType;
390 PType = Getter->getResultType();
391 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
392 Setter, MemberLoc, BaseExpr));
393 }
394
395 // Attempt to correct for typos in property names.
396 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000397 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
Chris Lattner7f816522010-04-11 07:45:24 +0000398 Res.getAsSingle<ObjCPropertyDecl>()) {
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000399 DeclarationName TypoResult = Res.getLookupName();
Chris Lattner7f816522010-04-11 07:45:24 +0000400 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000401 << MemberName << QualType(OPT, 0) << TypoResult
402 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000403 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
404 Diag(Property->getLocation(), diag::note_previous_decl)
405 << Property->getDeclName();
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000406 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc);
Chris Lattner7f816522010-04-11 07:45:24 +0000407 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000408
Chris Lattner7f816522010-04-11 07:45:24 +0000409 Diag(MemberLoc, diag::err_property_not_found)
410 << MemberName << QualType(OPT, 0);
411 if (Setter && !Getter)
412 Diag(Setter->getLocation(), diag::note_getter_unavailable)
413 << MemberName << BaseExpr->getSourceRange();
414 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000415}
416
417
418
Chris Lattnereb483eb2010-04-11 08:28:14 +0000419Action::OwningExprResult Sema::
420ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
421 IdentifierInfo &propertyName,
422 SourceLocation receiverNameLoc,
423 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000425 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000426 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
427 receiverNameLoc);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000428 if (IFace == 0) {
429 // If the "receiver" is 'super' in a method, handle it as an expression-like
430 // property reference.
431 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
432 if (receiverNamePtr->isStr("super")) {
433 if (CurMethod->isInstanceMethod()) {
434 QualType T =
435 Context.getObjCInterfaceType(CurMethod->getClassInterface());
436 T = Context.getObjCObjectPointerType(T);
437 Expr *SuperExpr = new (Context) ObjCSuperExpr(receiverNameLoc, T);
438
439 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
440 SuperExpr, &propertyName,
441 propertyNameLoc);
442 }
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Chris Lattnereb483eb2010-04-11 08:28:14 +0000444 // Otherwise, if this is a class method, try dispatching to our
445 // superclass.
446 IFace = CurMethod->getClassInterface()->getSuperClass();
447 }
448
449 if (IFace == 0) {
450 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
451 return ExprError();
452 }
453 }
454
455 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000456 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000457 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000458
459 // If this reference is in an @implementation, check for 'private' methods.
460 if (!Getter)
461 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
462 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000463 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000464 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000465
466 if (Getter) {
467 // FIXME: refactor/share with ActOnMemberReference().
468 // Check if we can reference this property.
469 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
470 return ExprError();
471 }
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Steve Naroff61f72cb2009-03-09 21:12:44 +0000473 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000474 Selector SetterSel =
475 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000476 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000477
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000478 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000479 if (!Setter) {
480 // If this reference is in an @implementation, also check for 'private'
481 // methods.
482 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
483 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000484 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000485 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000486 }
487 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000488 if (!Setter)
489 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000490
491 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
492 return ExprError();
493
494 if (Getter || Setter) {
495 QualType PType;
496
497 if (Getter)
498 PType = Getter->getResultType();
499 else {
500 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
501 E = Setter->param_end(); PI != E; ++PI)
502 PType = (*PI)->getType();
503 }
Fariborz Jahanian09105f52009-08-20 17:02:02 +0000504 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(
Mike Stump1eb44332009-09-09 15:08:12 +0000505 Getter, PType, Setter,
Steve Naroff61f72cb2009-03-09 21:12:44 +0000506 propertyNameLoc, IFace, receiverNameLoc));
507 }
508 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
509 << &propertyName << Context.getObjCInterfaceType(IFace));
510}
511
Douglas Gregor47bd5432010-04-14 02:46:37 +0000512Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000513 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000514 SourceLocation NameLoc,
515 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000516 bool HasTrailingDot,
517 TypeTy *&ReceiverType) {
518 ReceiverType = 0;
519
Douglas Gregor47bd5432010-04-14 02:46:37 +0000520 // If the identifier is "super" and there is no trailing dot, we're
521 // messaging super.
522 if (IsSuper && !HasTrailingDot && S->isInObjcMethodScope())
523 return ObjCSuperMessage;
524
525 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
526 LookupName(Result, S);
527
528 switch (Result.getResultKind()) {
529 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000530 // Normal name lookup didn't find anything. If we're in an
531 // Objective-C method, look for ivars. If we find one, we're done!
532 // FIXME: This is a hack. Ivar lookup should be part of normal lookup.
533 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
534 ObjCInterfaceDecl *ClassDeclared;
535 if (Method->getClassInterface()->lookupInstanceVariable(Name,
536 ClassDeclared))
537 return ObjCInstanceMessage;
538 }
539
Douglas Gregor47bd5432010-04-14 02:46:37 +0000540 // Break out; we'll perform typo correction below.
541 break;
542
543 case LookupResult::NotFoundInCurrentInstantiation:
544 case LookupResult::FoundOverloaded:
545 case LookupResult::FoundUnresolvedValue:
546 case LookupResult::Ambiguous:
547 Result.suppressDiagnostics();
548 return ObjCInstanceMessage;
549
550 case LookupResult::Found: {
551 // We found something. If it's a type, then we have a class
552 // message. Otherwise, it's an instance message.
553 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000554 QualType T;
555 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
556 T = Context.getObjCInterfaceType(Class);
557 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
558 T = Context.getTypeDeclType(Type);
559 else
560 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000561
Douglas Gregor1569f952010-04-21 20:38:13 +0000562 // We have a class message, and T is the type we're
563 // messaging. Build source-location information for it.
564 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
565 ReceiverType = CreateLocInfoType(T, TSInfo).getAsOpaquePtr();
566 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000567 }
568 }
569
Douglas Gregoraaf87162010-04-14 20:04:41 +0000570 // Determine our typo-correction context.
571 CorrectTypoContext CTC = CTC_Expression;
572 if (ObjCMethodDecl *Method = getCurMethodDecl())
573 if (Method->getClassInterface() &&
574 Method->getClassInterface()->getSuperClass())
575 CTC = CTC_ObjCMessageReceiver;
576
577 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
578 if (Result.isSingleResult()) {
579 // If we found a declaration, correct when it refers to an Objective-C
580 // class.
581 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000582 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000583 Diag(NameLoc, diag::err_unknown_receiver_suggest)
584 << Name << Result.getLookupName()
585 << FixItHint::CreateReplacement(SourceRange(NameLoc),
586 ND->getNameAsString());
587 Diag(ND->getLocation(), diag::note_previous_decl)
588 << Corrected;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000589
Douglas Gregor1569f952010-04-21 20:38:13 +0000590 QualType T = Context.getObjCInterfaceType(Class);
591 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
592 ReceiverType = CreateLocInfoType(T, TSInfo).getAsOpaquePtr();
Douglas Gregoraaf87162010-04-14 20:04:41 +0000593 return ObjCClassMessage;
594 }
595 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
596 Corrected.getAsIdentifierInfo()->isStr("super")) {
597 // If we've found the keyword "super", this is a send to super.
598 Diag(NameLoc, diag::err_unknown_receiver_suggest)
599 << Name << Corrected
600 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
601 Name = Corrected.getAsIdentifierInfo();
602 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000603 }
604 }
605
606 // Fall back: let the parser try to parse it as an instance message.
607 return ObjCInstanceMessage;
608}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000609
Douglas Gregor2725ca82010-04-21 19:57:20 +0000610Sema::OwningExprResult Sema::ActOnSuperMessage(Scope *S,
611 SourceLocation SuperLoc,
612 Selector Sel,
613 SourceLocation LBracLoc,
614 SourceLocation SelectorLoc,
615 SourceLocation RBracLoc,
616 MultiExprArg Args) {
617 // Determine whether we are inside a method or not.
618 ObjCMethodDecl *Method = getCurMethodDecl();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000619 if (!Method) {
620 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
621 return ExprError();
622 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000623
Douglas Gregorf95861a2010-04-21 20:01:04 +0000624 ObjCInterfaceDecl *Class = Method->getClassInterface();
625 if (!Class) {
626 Diag(SuperLoc, diag::error_no_super_class_message)
627 << Method->getDeclName();
628 return ExprError();
629 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000630
Douglas Gregorf95861a2010-04-21 20:01:04 +0000631 ObjCInterfaceDecl *Super = Class->getSuperClass();
632 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000633 // The current class does not have a superclass.
634 Diag(SuperLoc, diag::error_no_super_class) << Class->getIdentifier();
635 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000636 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000637
Douglas Gregorf95861a2010-04-21 20:01:04 +0000638 // We are in a method whose class has a superclass, so 'super'
639 // is acting as a keyword.
640 if (Method->isInstanceMethod()) {
641 // Since we are in an instance method, this is an instance
642 // message to the superclass instance.
643 QualType SuperTy = Context.getObjCInterfaceType(Super);
644 SuperTy = Context.getObjCObjectPointerType(SuperTy);
645 return BuildInstanceMessage(ExprArg(*this), SuperTy, SuperLoc,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000646 Sel, /*Method=*/0, LBracLoc, RBracLoc,
647 move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000648 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000649
650 // Since we are in a class method, this is a class message to
651 // the superclass.
652 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
653 Context.getObjCInterfaceType(Super),
Douglas Gregorf49bb082010-04-22 17:01:48 +0000654 SuperLoc, Sel, /*Method=*/0, LBracLoc, RBracLoc,
655 move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000656}
657
658/// \brief Build an Objective-C class message expression.
659///
660/// This routine takes care of both normal class messages and
661/// class messages to the superclass.
662///
663/// \param ReceiverTypeInfo Type source information that describes the
664/// receiver of this message. This may be NULL, in which case we are
665/// sending to the superclass and \p SuperLoc must be a valid source
666/// location.
667
668/// \param ReceiverType The type of the object receiving the
669/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
670/// type as that refers to. For a superclass send, this is the type of
671/// the superclass.
672///
673/// \param SuperLoc The location of the "super" keyword in a
674/// superclass message.
675///
676/// \param Sel The selector to which the message is being sent.
677///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000678/// \param Method The method that this class message is invoking, if
679/// already known.
680///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000681/// \param LBracLoc The location of the opening square bracket ']'.
682///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000683/// \param RBrac The location of the closing square bracket ']'.
684///
685/// \param Args The message arguments.
686Sema::OwningExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
687 QualType ReceiverType,
688 SourceLocation SuperLoc,
689 Selector Sel,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000690 ObjCMethodDecl *Method,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000691 SourceLocation LBracLoc,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000692 SourceLocation RBracLoc,
693 MultiExprArg ArgsIn) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000694 if (ReceiverType->isDependentType()) {
695 // If the receiver type is dependent, we can't type-check anything
696 // at this point. Build a dependent expression.
697 unsigned NumArgs = ArgsIn.size();
698 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
699 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
700 return Owned(ObjCMessageExpr::Create(Context, ReceiverType, LBracLoc,
701 ReceiverTypeInfo, Sel, /*Method=*/0,
702 Args, NumArgs, RBracLoc));
703 }
Chris Lattner15faee12010-04-12 05:38:43 +0000704
Douglas Gregor2725ca82010-04-21 19:57:20 +0000705 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
706 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000707
Douglas Gregor2725ca82010-04-21 19:57:20 +0000708 // Find the class to which we are sending this message.
709 ObjCInterfaceDecl *Class = 0;
710 if (const ObjCInterfaceType *ClassType
711 = ReceiverType->getAs<ObjCInterfaceType>())
712 Class = ClassType->getDecl();
713 else {
714 Diag(Loc, diag::err_invalid_receiver_class_message)
715 << ReceiverType;
716 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +0000717 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000718 assert(Class && "We don't know which class we're messaging?");
719
720 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +0000721 if (!Method) {
722 if (Class->isForwardDecl()) {
723 // A forward class used in messaging is treated as a 'Class'
724 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
725 Method = LookupFactoryMethodInGlobalPool(Sel,
726 SourceRange(LBracLoc, RBracLoc));
727 if (Method)
728 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
729 << Method->getDeclName();
730 }
731 if (!Method)
732 Method = Class->lookupClassMethod(Sel);
733
734 // If we have an implementation in scope, check "private" methods.
735 if (!Method)
736 Method = LookupPrivateClassMethod(Sel, Class);
737
738 if (Method && DiagnoseUseOfDecl(Method, Loc))
739 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +0000740 }
Mike Stump1eb44332009-09-09 15:08:12 +0000741
Douglas Gregor2725ca82010-04-21 19:57:20 +0000742 // Check the argument types and determine the result type.
743 QualType ReturnType;
744 unsigned NumArgs = ArgsIn.size();
745 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
746 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
747 LBracLoc, RBracLoc, ReturnType)) {
748 for (unsigned I = 0; I != NumArgs; ++I)
749 Args[I]->Destroy(Context);
750 return ExprError();
751 }
Ted Kremenek4df728e2008-06-24 15:50:53 +0000752
Douglas Gregor2725ca82010-04-21 19:57:20 +0000753 // Construct the appropriate ObjCMessageExpr.
754 if (SuperLoc.isValid())
755 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
756 SuperLoc, /*IsInstanceSuper=*/false,
757 ReceiverType, Sel, Method, Args,
758 NumArgs, RBracLoc));
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Douglas Gregor2725ca82010-04-21 19:57:20 +0000760 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
761 ReceiverTypeInfo, Sel, Method, Args,
762 NumArgs, RBracLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000763}
764
Douglas Gregor2725ca82010-04-21 19:57:20 +0000765// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +0000766// ArgExprs is optional - if it is present, the number of expressions
767// is obtained from Sel.getNumArgs().
Douglas Gregor2725ca82010-04-21 19:57:20 +0000768Sema::OwningExprResult Sema::ActOnClassMessage(Scope *S,
769 TypeTy *Receiver,
770 Selector Sel,
771 SourceLocation LBracLoc,
772 SourceLocation SelectorLoc,
773 SourceLocation RBracLoc,
774 MultiExprArg Args) {
775 TypeSourceInfo *ReceiverTypeInfo;
776 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
777 if (ReceiverType.isNull())
778 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000779
Mike Stump1eb44332009-09-09 15:08:12 +0000780
Douglas Gregor2725ca82010-04-21 19:57:20 +0000781 if (!ReceiverTypeInfo)
782 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
783
784 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000785 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Douglas Gregor39968ad2010-04-22 16:50:51 +0000786 LBracLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000787}
788
789/// \brief Build an Objective-C instance message expression.
790///
791/// This routine takes care of both normal instance messages and
792/// instance messages to the superclass instance.
793///
794/// \param Receiver The expression that computes the object that will
795/// receive this message. This may be empty, in which case we are
796/// sending to the superclass instance and \p SuperLoc must be a valid
797/// source location.
798///
799/// \param ReceiverType The (static) type of the object receiving the
800/// message. When a \p Receiver expression is provided, this is the
801/// same type as that expression. For a superclass instance send, this
802/// is a pointer to the type of the superclass.
803///
804/// \param SuperLoc The location of the "super" keyword in a
805/// superclass instance message.
806///
807/// \param Sel The selector to which the message is being sent.
808///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000809/// \param Method The method that this instance message is invoking, if
810/// already known.
811///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000812/// \param LBracLoc The location of the opening square bracket ']'.
813///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000814/// \param RBrac The location of the closing square bracket ']'.
815///
816/// \param Args The message arguments.
817Sema::OwningExprResult Sema::BuildInstanceMessage(ExprArg ReceiverE,
818 QualType ReceiverType,
819 SourceLocation SuperLoc,
820 Selector Sel,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000821 ObjCMethodDecl *Method,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000822 SourceLocation LBracLoc,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000823 SourceLocation RBracLoc,
824 MultiExprArg ArgsIn) {
825 // If we have a receiver expression, perform appropriate promotions
826 // and determine receiver type.
827 Expr *Receiver = ReceiverE.takeAs<Expr>();
828 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000829 if (Receiver->isTypeDependent()) {
830 // If the receiver is type-dependent, we can't type-check anything
831 // at this point. Build a dependent expression.
832 unsigned NumArgs = ArgsIn.size();
833 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
834 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
835 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
836 LBracLoc, Receiver, Sel,
837 /*Method=*/0, Args, NumArgs,
838 RBracLoc));
839 }
840
Douglas Gregor2725ca82010-04-21 19:57:20 +0000841 // If necessary, apply function/array conversion to the receiver.
842 // C99 6.7.5.3p[7,8].
843 DefaultFunctionArrayLvalueConversion(Receiver);
844 ReceiverType = Receiver->getType();
845 }
846
847 // The location of the receiver.
848 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000849
Douglas Gregorf49bb082010-04-22 17:01:48 +0000850 if (!Method) {
851 // Handle messages to id.
852 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType() ||
853 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
854 Method = LookupInstanceMethodInGlobalPool(Sel,
Douglas Gregor2725ca82010-04-21 19:57:20 +0000855 SourceRange(LBracLoc, RBracLoc));
Douglas Gregorf49bb082010-04-22 17:01:48 +0000856 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000857 Method = LookupFactoryMethodInGlobalPool(Sel,
Douglas Gregorf49bb082010-04-22 17:01:48 +0000858 SourceRange(LBracLoc, RBracLoc));
859 } else if (ReceiverType->isObjCClassType() ||
860 ReceiverType->isObjCQualifiedClassType()) {
861 // Handle messages to Class.
862 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
863 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
864 // First check the public methods in the class interface.
865 Method = ClassDecl->lookupClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000866
Douglas Gregorf49bb082010-04-22 17:01:48 +0000867 if (!Method)
868 Method = LookupPrivateClassMethod(Sel, ClassDecl);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000869
Douglas Gregorf49bb082010-04-22 17:01:48 +0000870 // FIXME: if we still haven't found a method, we need to look in
871 // protocols (if we have qualifiers).
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000872 }
Douglas Gregorf49bb082010-04-22 17:01:48 +0000873 if (Method && DiagnoseUseOfDecl(Method, Loc))
874 return ExprError();
Fariborz Jahanian268bc8c2009-03-03 22:19:15 +0000875 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000876 if (!Method) {
Douglas Gregorf49bb082010-04-22 17:01:48 +0000877 // If not messaging 'self', look for any factory method named 'Sel'.
878 if (!Receiver || !isSelfExpr(Receiver)) {
879 Method = LookupFactoryMethodInGlobalPool(Sel,
880 SourceRange(LBracLoc, RBracLoc));
881 if (!Method) {
882 // If no class (factory) method was found, check if an _instance_
883 // method of the same name exists in the root class only.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000884 Method = LookupInstanceMethodInGlobalPool(Sel,
885 SourceRange(LBracLoc, RBracLoc));
Douglas Gregorf49bb082010-04-22 17:01:48 +0000886 if (Method)
887 if (const ObjCInterfaceDecl *ID =
888 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
889 if (ID->getSuperClass())
890 Diag(Loc, diag::warn_root_inst_method_not_found)
891 << Sel << SourceRange(LBracLoc, RBracLoc);
892 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000893 }
894 }
895 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000896 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +0000897 ObjCInterfaceDecl* ClassDecl = 0;
898
899 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
900 // long as one of the protocols implements the selector (if not, warn).
901 if (const ObjCObjectPointerType *QIdTy
902 = ReceiverType->getAsObjCQualifiedIdType()) {
903 // Search protocols for instance methods.
904 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
905 E = QIdTy->qual_end(); I != E; ++I) {
906 ObjCProtocolDecl *PDecl = *I;
907 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
908 break;
909 // Since we aren't supporting "Class<foo>", look for a class method.
910 if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
911 break;
912 }
913 } else if (const ObjCObjectPointerType *OCIType
914 = ReceiverType->getAsObjCInterfacePointerType()) {
915 // We allow sending a message to a pointer to an interface (an object).
916 ClassDecl = OCIType->getInterfaceDecl();
917 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
918 // faster than the following method (which can do *many* linear searches).
919 // The idea is to add class info to InstanceMethodPool.
920 Method = ClassDecl->lookupInstanceMethod(Sel);
921
922 if (!Method) {
923 // Search protocol qualifiers.
924 for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(),
925 E = OCIType->qual_end(); QI != E; ++QI) {
926 if ((Method = (*QI)->lookupInstanceMethod(Sel)))
927 break;
928 }
929 }
930 if (!Method) {
931 // If we have implementations in scope, check "private" methods.
932 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
933
934 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
935 // If we still haven't found a method, look in the global pool. This
936 // behavior isn't very desirable, however we need it for GCC
937 // compatibility. FIXME: should we deviate??
938 if (OCIType->qual_empty()) {
939 Method = LookupInstanceMethodInGlobalPool(Sel,
940 SourceRange(LBracLoc, RBracLoc));
941 if (Method && !OCIType->getInterfaceDecl()->isForwardDecl())
942 Diag(Loc, diag::warn_maynot_respond)
943 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
944 }
945 }
946 }
947 if (Method && DiagnoseUseOfDecl(Method, Loc))
948 return ExprError();
949 } else if (!Context.getObjCIdType().isNull() &&
950 (ReceiverType->isPointerType() ||
951 (ReceiverType->isIntegerType() &&
952 ReceiverType->isScalarType()))) {
953 // Implicitly convert integers and pointers to 'id' but emit a warning.
954 Diag(Loc, diag::warn_bad_receiver_type)
955 << ReceiverType
956 << Receiver->getSourceRange();
957 if (ReceiverType->isPointerType())
958 ImpCastExprToType(Receiver, Context.getObjCIdType(),
959 CastExpr::CK_BitCast);
960 else
961 ImpCastExprToType(Receiver, Context.getObjCIdType(),
962 CastExpr::CK_IntegralToPointer);
963 ReceiverType = Receiver->getType();
964 } else {
965 // Reject other random receiver types (e.g. structs).
966 Diag(Loc, diag::err_bad_receiver_type)
967 << ReceiverType << Receiver->getSourceRange();
968 return ExprError();
969 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000970 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +0000971 }
Mike Stump1eb44332009-09-09 15:08:12 +0000972
Douglas Gregor2725ca82010-04-21 19:57:20 +0000973 // Check the message arguments.
974 unsigned NumArgs = ArgsIn.size();
975 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
976 QualType ReturnType;
977 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, false,
978 LBracLoc, RBracLoc, ReturnType))
979 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000980
Douglas Gregor2725ca82010-04-21 19:57:20 +0000981 // Construct the appropriate ObjCMessageExpr instance.
982 if (SuperLoc.isValid())
983 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
984 SuperLoc, /*IsInstanceSuper=*/true,
985 ReceiverType, Sel, Method,
986 Args, NumArgs, RBracLoc));
Douglas Gregor04badcf2010-04-21 00:45:42 +0000987
Douglas Gregor2725ca82010-04-21 19:57:20 +0000988 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, Receiver,
989 Sel, Method, Args, NumArgs, RBracLoc));
990}
991
992// ActOnInstanceMessage - used for both unary and keyword messages.
993// ArgExprs is optional - if it is present, the number of expressions
994// is obtained from Sel.getNumArgs().
995Sema::OwningExprResult Sema::ActOnInstanceMessage(Scope *S,
996 ExprArg ReceiverE,
997 Selector Sel,
998 SourceLocation LBracLoc,
999 SourceLocation SelectorLoc,
1000 SourceLocation RBracLoc,
1001 MultiExprArg Args) {
1002 Expr *Receiver = static_cast<Expr *>(ReceiverE.get());
1003 if (!Receiver)
1004 return ExprError();
1005
1006 return BuildInstanceMessage(move(ReceiverE), Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001007 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1008 LBracLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001009}
Chris Lattnereca7be62008-04-07 05:30:13 +00001010