blob: 71833f254c4077a2311088647beb3b9627411b70 [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,
646 Sel, LBracLoc, SelectorLoc, 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),
654 SuperLoc, Sel, LBracLoc, SelectorLoc,
655 RBracLoc, 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///
678/// \param LBracLoc The location of the opening square bracket ']'.
679///
680/// \param SelectorLoc The location of the first identifier in the selector.
681///
682/// \param RBrac The location of the closing square bracket ']'.
683///
684/// \param Args The message arguments.
685Sema::OwningExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
686 QualType ReceiverType,
687 SourceLocation SuperLoc,
688 Selector Sel,
689 SourceLocation LBracLoc,
690 SourceLocation SelectorLoc,
691 SourceLocation RBracLoc,
692 MultiExprArg ArgsIn) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000693 if (ReceiverType->isDependentType()) {
694 // If the receiver type is dependent, we can't type-check anything
695 // at this point. Build a dependent expression.
696 unsigned NumArgs = ArgsIn.size();
697 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
698 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
699 return Owned(ObjCMessageExpr::Create(Context, ReceiverType, LBracLoc,
700 ReceiverTypeInfo, Sel, /*Method=*/0,
701 Args, NumArgs, RBracLoc));
702 }
Chris Lattner15faee12010-04-12 05:38:43 +0000703
Douglas Gregor2725ca82010-04-21 19:57:20 +0000704 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
705 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000706
Douglas Gregor2725ca82010-04-21 19:57:20 +0000707 // Find the class to which we are sending this message.
708 ObjCInterfaceDecl *Class = 0;
709 if (const ObjCInterfaceType *ClassType
710 = ReceiverType->getAs<ObjCInterfaceType>())
711 Class = ClassType->getDecl();
712 else {
713 Diag(Loc, diag::err_invalid_receiver_class_message)
714 << ReceiverType;
715 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +0000716 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000717 assert(Class && "We don't know which class we're messaging?");
718
719 // Find the method we are messaging.
Steve Naroffcb28be62008-06-04 23:08:38 +0000720 ObjCMethodDecl *Method = 0;
Douglas Gregor2725ca82010-04-21 19:57:20 +0000721 if (Class->isForwardDecl()) {
722 // A forward class used in messaging is treated as a 'Class'
723 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
724 Method = LookupFactoryMethodInGlobalPool(Sel,
725 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89bc3142009-05-08 23:02:36 +0000726 if (Method)
Mike Stump1eb44332009-09-09 15:08:12 +0000727 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
Fariborz Jahanian9f8f0262009-05-08 23:45:49 +0000728 << Method->getDeclName();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +0000729 }
730 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000731 Method = Class->lookupClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Steve Naroff7c778f12008-07-25 19:39:00 +0000733 // If we have an implementation in scope, check "private" methods.
Steve Narofff1afaf62009-02-26 15:55:06 +0000734 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000735 Method = LookupPrivateClassMethod(Sel, Class);
Steve Naroff7c778f12008-07-25 19:39:00 +0000736
Douglas Gregor2725ca82010-04-21 19:57:20 +0000737 if (Method && DiagnoseUseOfDecl(Method, Loc))
738 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000739
Douglas Gregor2725ca82010-04-21 19:57:20 +0000740 // Check the argument types and determine the result type.
741 QualType ReturnType;
742 unsigned NumArgs = ArgsIn.size();
743 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
744 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
745 LBracLoc, RBracLoc, ReturnType)) {
746 for (unsigned I = 0; I != NumArgs; ++I)
747 Args[I]->Destroy(Context);
748 return ExprError();
749 }
Ted Kremenek4df728e2008-06-24 15:50:53 +0000750
Douglas Gregor2725ca82010-04-21 19:57:20 +0000751 // Construct the appropriate ObjCMessageExpr.
752 if (SuperLoc.isValid())
753 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
754 SuperLoc, /*IsInstanceSuper=*/false,
755 ReceiverType, Sel, Method, Args,
756 NumArgs, RBracLoc));
Mike Stump1eb44332009-09-09 15:08:12 +0000757
Douglas Gregor2725ca82010-04-21 19:57:20 +0000758 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
759 ReceiverTypeInfo, Sel, Method, Args,
760 NumArgs, RBracLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000761}
762
Douglas Gregor2725ca82010-04-21 19:57:20 +0000763// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +0000764// ArgExprs is optional - if it is present, the number of expressions
765// is obtained from Sel.getNumArgs().
Douglas Gregor2725ca82010-04-21 19:57:20 +0000766Sema::OwningExprResult Sema::ActOnClassMessage(Scope *S,
767 TypeTy *Receiver,
768 Selector Sel,
769 SourceLocation LBracLoc,
770 SourceLocation SelectorLoc,
771 SourceLocation RBracLoc,
772 MultiExprArg Args) {
773 TypeSourceInfo *ReceiverTypeInfo;
774 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
775 if (ReceiverType.isNull())
776 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Mike Stump1eb44332009-09-09 15:08:12 +0000778
Douglas Gregor2725ca82010-04-21 19:57:20 +0000779 if (!ReceiverTypeInfo)
780 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
781
782 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
783 /*SuperLoc=*/SourceLocation(), Sel,
784 LBracLoc, SelectorLoc, RBracLoc, move(Args));
785}
786
787/// \brief Build an Objective-C instance message expression.
788///
789/// This routine takes care of both normal instance messages and
790/// instance messages to the superclass instance.
791///
792/// \param Receiver The expression that computes the object that will
793/// receive this message. This may be empty, in which case we are
794/// sending to the superclass instance and \p SuperLoc must be a valid
795/// source location.
796///
797/// \param ReceiverType The (static) type of the object receiving the
798/// message. When a \p Receiver expression is provided, this is the
799/// same type as that expression. For a superclass instance send, this
800/// is a pointer to the type of the superclass.
801///
802/// \param SuperLoc The location of the "super" keyword in a
803/// superclass instance message.
804///
805/// \param Sel The selector to which the message is being sent.
806///
807/// \param LBracLoc The location of the opening square bracket ']'.
808///
809/// \param SelectorLoc The location of the first identifier in the selector.
810///
811/// \param RBrac The location of the closing square bracket ']'.
812///
813/// \param Args The message arguments.
814Sema::OwningExprResult Sema::BuildInstanceMessage(ExprArg ReceiverE,
815 QualType ReceiverType,
816 SourceLocation SuperLoc,
817 Selector Sel,
818 SourceLocation LBracLoc,
819 SourceLocation SelectorLoc,
820 SourceLocation RBracLoc,
821 MultiExprArg ArgsIn) {
822 // If we have a receiver expression, perform appropriate promotions
823 // and determine receiver type.
824 Expr *Receiver = ReceiverE.takeAs<Expr>();
825 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000826 if (Receiver->isTypeDependent()) {
827 // If the receiver is type-dependent, we can't type-check anything
828 // at this point. Build a dependent expression.
829 unsigned NumArgs = ArgsIn.size();
830 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
831 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
832 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
833 LBracLoc, Receiver, Sel,
834 /*Method=*/0, Args, NumArgs,
835 RBracLoc));
836 }
837
Douglas Gregor2725ca82010-04-21 19:57:20 +0000838 // If necessary, apply function/array conversion to the receiver.
839 // C99 6.7.5.3p[7,8].
840 DefaultFunctionArrayLvalueConversion(Receiver);
841 ReceiverType = Receiver->getType();
842 }
843
844 // The location of the receiver.
845 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000846
Douglas Gregor04badcf2010-04-21 00:45:42 +0000847 ObjCMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000848 // Handle messages to id.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000849 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType() ||
850 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
851 Method = LookupInstanceMethodInGlobalPool(Sel,
852 SourceRange(LBracLoc, RBracLoc));
Chris Lattner6e10a082008-02-01 06:57:39 +0000853 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000854 Method = LookupFactoryMethodInGlobalPool(Sel,
855 SourceRange(LBracLoc, RBracLoc));
856 } else if (ReceiverType->isObjCClassType() ||
857 ReceiverType->isObjCQualifiedClassType()) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000858 // Handle messages to Class.
Chris Lattner6562fda2008-07-21 06:44:27 +0000859 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
Steve Naroffd526c2f2009-02-23 02:25:40 +0000860 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
861 // First check the public methods in the class interface.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000862 Method = ClassDecl->lookupClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Steve Narofff1afaf62009-02-26 15:55:06 +0000864 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000865 Method = LookupPrivateClassMethod(Sel, ClassDecl);
Mike Stump1eb44332009-09-09 15:08:12 +0000866
867 // FIXME: if we still haven't found a method, we need to look in
Steve Naroff470301b2009-07-22 16:07:01 +0000868 // protocols (if we have qualifiers).
Steve Naroffd526c2f2009-02-23 02:25:40 +0000869 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000870 if (Method && DiagnoseUseOfDecl(Method, Loc))
871 return ExprError();
Steve Naroffd526c2f2009-02-23 02:25:40 +0000872 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000873 if (!Method) {
874 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000875 if (!Receiver || !isSelfExpr(Receiver)) {
876 Method = LookupFactoryMethodInGlobalPool(Sel,
877 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanianb1006c72009-03-04 17:50:39 +0000878 if (!Method) {
Fariborz Jahanian041f2fd2009-05-05 18:34:37 +0000879 // If no class (factory) method was found, check if an _instance_
880 // method of the same name exists in the root class only.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000881 Method = LookupInstanceMethodInGlobalPool(Sel,
882 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian041f2fd2009-05-05 18:34:37 +0000883 if (Method)
884 if (const ObjCInterfaceDecl *ID =
885 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
886 if (ID->getSuperClass())
Douglas Gregor2725ca82010-04-21 19:57:20 +0000887 Diag(Loc, diag::warn_root_inst_method_not_found)
888 << Sel << SourceRange(LBracLoc, RBracLoc);
Fariborz Jahanian041f2fd2009-05-05 18:34:37 +0000889 }
Fariborz Jahanianb1006c72009-03-04 17:50:39 +0000890 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000891 }
892 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000893 } else {
894 ObjCInterfaceDecl* ClassDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000895
Douglas Gregor04badcf2010-04-21 00:45:42 +0000896 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
897 // long as one of the protocols implements the selector (if not, warn).
Douglas Gregor2725ca82010-04-21 19:57:20 +0000898 if (const ObjCObjectPointerType *QIdTy
899 = ReceiverType->getAsObjCQualifiedIdType()) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000900 // Search protocols for instance methods.
901 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
902 E = QIdTy->qual_end(); I != E; ++I) {
903 ObjCProtocolDecl *PDecl = *I;
904 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
905 break;
906 // Since we aren't supporting "Class<foo>", look for a class method.
907 if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
Chris Lattner85a932e2008-01-04 22:32:30 +0000908 break;
909 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000910 } else if (const ObjCObjectPointerType *OCIType
911 = ReceiverType->getAsObjCInterfacePointerType()) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000912 // We allow sending a message to a pointer to an interface (an object).
Douglas Gregor04badcf2010-04-21 00:45:42 +0000913 ClassDecl = OCIType->getInterfaceDecl();
914 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
915 // faster than the following method (which can do *many* linear searches).
916 // The idea is to add class info to InstanceMethodPool.
917 Method = ClassDecl->lookupInstanceMethod(Sel);
918
919 if (!Method) {
920 // Search protocol qualifiers.
921 for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(),
922 E = OCIType->qual_end(); QI != E; ++QI) {
923 if ((Method = (*QI)->lookupInstanceMethod(Sel)))
924 break;
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000925 }
Fariborz Jahanian268bc8c2009-03-03 22:19:15 +0000926 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000927 if (!Method) {
928 // If we have implementations in scope, check "private" methods.
929 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
930
Douglas Gregor2725ca82010-04-21 19:57:20 +0000931 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000932 // If we still haven't found a method, look in the global pool. This
933 // behavior isn't very desirable, however we need it for GCC
934 // compatibility. FIXME: should we deviate??
935 if (OCIType->qual_empty()) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000936 Method = LookupInstanceMethodInGlobalPool(Sel,
937 SourceRange(LBracLoc, RBracLoc));
Douglas Gregor04badcf2010-04-21 00:45:42 +0000938 if (Method && !OCIType->getInterfaceDecl()->isForwardDecl())
Douglas Gregor2725ca82010-04-21 19:57:20 +0000939 Diag(Loc, diag::warn_maynot_respond)
Douglas Gregor04badcf2010-04-21 00:45:42 +0000940 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
941 }
942 }
943 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000944 if (Method && DiagnoseUseOfDecl(Method, Loc))
945 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000946 } else if (!Context.getObjCIdType().isNull() &&
Douglas Gregor2725ca82010-04-21 19:57:20 +0000947 (ReceiverType->isPointerType() ||
948 (ReceiverType->isIntegerType() &&
949 ReceiverType->isScalarType()))) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000950 // Implicitly convert integers and pointers to 'id' but emit a warning.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000951 Diag(Loc, diag::warn_bad_receiver_type)
952 << ReceiverType
953 << Receiver->getSourceRange();
954 if (ReceiverType->isPointerType())
955 ImpCastExprToType(Receiver, Context.getObjCIdType(),
956 CastExpr::CK_BitCast);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000957 else
Douglas Gregor2725ca82010-04-21 19:57:20 +0000958 ImpCastExprToType(Receiver, Context.getObjCIdType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +0000959 CastExpr::CK_IntegralToPointer);
Douglas Gregor2725ca82010-04-21 19:57:20 +0000960 ReceiverType = Receiver->getType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000961 } else {
962 // Reject other random receiver types (e.g. structs).
Douglas Gregor2725ca82010-04-21 19:57:20 +0000963 Diag(Loc, diag::err_bad_receiver_type)
964 << ReceiverType << Receiver->getSourceRange();
965 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000966 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +0000967 }
Mike Stump1eb44332009-09-09 15:08:12 +0000968
Douglas Gregor2725ca82010-04-21 19:57:20 +0000969 // Check the message arguments.
970 unsigned NumArgs = ArgsIn.size();
971 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
972 QualType ReturnType;
973 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, false,
974 LBracLoc, RBracLoc, ReturnType))
975 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000976
Douglas Gregor2725ca82010-04-21 19:57:20 +0000977 // Construct the appropriate ObjCMessageExpr instance.
978 if (SuperLoc.isValid())
979 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
980 SuperLoc, /*IsInstanceSuper=*/true,
981 ReceiverType, Sel, Method,
982 Args, NumArgs, RBracLoc));
Douglas Gregor04badcf2010-04-21 00:45:42 +0000983
Douglas Gregor2725ca82010-04-21 19:57:20 +0000984 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, Receiver,
985 Sel, Method, Args, NumArgs, RBracLoc));
986}
987
988// ActOnInstanceMessage - used for both unary and keyword messages.
989// ArgExprs is optional - if it is present, the number of expressions
990// is obtained from Sel.getNumArgs().
991Sema::OwningExprResult Sema::ActOnInstanceMessage(Scope *S,
992 ExprArg ReceiverE,
993 Selector Sel,
994 SourceLocation LBracLoc,
995 SourceLocation SelectorLoc,
996 SourceLocation RBracLoc,
997 MultiExprArg Args) {
998 Expr *Receiver = static_cast<Expr *>(ReceiverE.get());
999 if (!Receiver)
1000 return ExprError();
1001
1002 return BuildInstanceMessage(move(ReceiverE), Receiver->getType(),
1003 /*SuperLoc=*/SourceLocation(),
1004 Sel, LBracLoc, SelectorLoc, RBracLoc,
1005 move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001006}
Chris Lattnereca7be62008-04-07 05:30:13 +00001007