blob: aa9b4748a03914c68808aca593bf58c74ccc2509 [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
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
John McCall5f1e0942010-08-24 08:50:51 +000016#include "clang/Sema/Scope.h"
John McCall26743b22011-02-03 09:00:02 +000017#include "clang/Sema/ScopeInfo.h"
Douglas Gregore737f502010-08-12 20:07:10 +000018#include "clang/Sema/Initialization.h"
Chris Lattner85a932e2008-01-04 22:32:30 +000019#include "clang/AST/ASTContext.h"
20#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000021#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000022#include "clang/AST/StmtVisitor.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000023#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000024#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000025#include "clang/Lex/Preprocessor.h"
26
Chris Lattner85a932e2008-01-04 22:32:30 +000027using namespace clang;
John McCall26743b22011-02-03 09:00:02 +000028using namespace sema;
Chris Lattner85a932e2008-01-04 22:32:30 +000029
John McCallf312b1e2010-08-26 23:41:50 +000030ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
31 Expr **strings,
32 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000033 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
34
Chris Lattnerf4b136f2009-02-18 06:13:04 +000035 // Most ObjC strings are formed out of a single piece. However, we *can*
36 // have strings formed out of multiple @ strings with multiple pptokens in
37 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
38 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner39c28bb2009-02-18 06:48:40 +000039 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000040
Chris Lattnerf4b136f2009-02-18 06:13:04 +000041 // If we have a multi-part string, merge it all together.
42 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000043 // Concatenate objc strings.
Chris Lattner39c28bb2009-02-18 06:48:40 +000044 llvm::SmallString<128> StrBuf;
Chris Lattner5f9e2722011-07-23 10:55:15 +000045 SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000046
Chris Lattner726e1682009-02-18 05:49:11 +000047 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000048 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000049
Douglas Gregor5cee1192011-07-27 05:40:30 +000050 // ObjC strings can't be wide or UTF.
51 if (!S->isAscii()) {
Chris Lattnerf4b136f2009-02-18 06:13:04 +000052 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
53 << S->getSourceRange();
54 return true;
55 }
Mike Stump1eb44332009-09-09 15:08:12 +000056
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +000057 // Append the string.
58 StrBuf += S->getString();
Mike Stump1eb44332009-09-09 15:08:12 +000059
Chris Lattner39c28bb2009-02-18 06:48:40 +000060 // Get the locations of the string tokens.
61 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Chris Lattner85a932e2008-01-04 22:32:30 +000062 }
Mike Stump1eb44332009-09-09 15:08:12 +000063
Chris Lattner39c28bb2009-02-18 06:48:40 +000064 // Create the aggregate string with the appropriate content and location
65 // information.
Jay Foad65aa6882011-06-21 15:13:30 +000066 S = StringLiteral::Create(Context, StrBuf,
Douglas Gregor5cee1192011-07-27 05:40:30 +000067 StringLiteral::Ascii, /*Pascal=*/false,
Chris Lattner2085fd62009-02-18 06:40:38 +000068 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000069 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000070 }
Mike Stump1eb44332009-09-09 15:08:12 +000071
Chris Lattner69039812009-02-18 06:01:06 +000072 // Verify that this composite string is acceptable for ObjC strings.
73 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000074 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000075
76 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000077 // the NSString interface is seen in this translation unit. Note: We
78 // don't use NSConstantString, since the runtime team considers this
79 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000080 QualType Ty = Context.getObjCConstantStringInterface();
81 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000082 Ty = Context.getObjCObjectPointerType(Ty);
Fariborz Jahanian8a437762010-04-23 23:19:04 +000083 } else if (getLangOptions().NoConstantCFStrings) {
Fariborz Jahanian4c733072010-10-19 17:19:29 +000084 IdentifierInfo *NSIdent=0;
85 std::string StringClass(getLangOptions().ObjCConstantStringClass);
86
87 if (StringClass.empty())
88 NSIdent = &Context.Idents.get("NSConstantString");
89 else
90 NSIdent = &Context.Idents.get(StringClass);
91
Fariborz Jahanian8a437762010-04-23 23:19:04 +000092 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
93 LookupOrdinaryName);
94 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
95 Context.setObjCConstantStringInterface(StrIF);
96 Ty = Context.getObjCConstantStringInterface();
97 Ty = Context.getObjCObjectPointerType(Ty);
98 } else {
99 // If there is no NSConstantString interface defined then treat this
100 // as error and recover from it.
101 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
102 << S->getSourceRange();
103 Ty = Context.getObjCIdType();
104 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000105 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000106 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +0000107 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
108 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000109 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
110 Context.setObjCConstantStringInterface(StrIF);
111 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +0000112 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000113 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +0000114 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000115 // strings as untyped objects and let the runtime figure it out later.
116 Ty = Context.getObjCIdType();
117 }
Chris Lattner13fd7e52008-06-21 21:44:18 +0000118 }
Mike Stump1eb44332009-09-09 15:08:12 +0000119
Chris Lattnerf4b136f2009-02-18 06:13:04 +0000120 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +0000121}
122
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000123ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +0000124 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000125 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000126 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000127 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000128 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000129 StrTy = Context.DependentTy;
130 else {
Fariborz Jahanian6c916152011-06-16 22:34:44 +0000131 if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled.
132 !EncodedType->isVoidType()) // void is handled too.
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000133 if (RequireCompleteType(AtLoc, EncodedType,
134 PDiag(diag::err_incomplete_type_objc_at_encode)
135 << EncodedTypeInfo->getTypeLoc().getSourceRange()))
136 return ExprError();
137
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000138 std::string Str;
139 Context.getObjCEncodingForType(EncodedType, Str);
140
141 // The type of @encode is the same as the type of the corresponding string,
142 // which is an array type.
143 StrTy = Context.CharTy;
144 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000145 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000146 StrTy.addConst();
147 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
148 ArrayType::Normal, 0);
149 }
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Douglas Gregor81d34662010-04-20 15:39:42 +0000151 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000152}
153
John McCallf312b1e2010-08-26 23:41:50 +0000154ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
155 SourceLocation EncodeLoc,
156 SourceLocation LParenLoc,
157 ParsedType ty,
158 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000159 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000160 TypeSourceInfo *TInfo;
161 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
162 if (!TInfo)
163 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
164 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000165
Douglas Gregor81d34662010-04-20 15:39:42 +0000166 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000167}
168
John McCallf312b1e2010-08-26 23:41:50 +0000169ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
170 SourceLocation AtLoc,
171 SourceLocation SelLoc,
172 SourceLocation LParenLoc,
173 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000174 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000175 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000176 if (!Method)
177 Method = LookupFactoryMethodInGlobalPool(Sel,
178 SourceRange(LParenLoc, RParenLoc));
179 if (!Method)
180 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
Fariborz Jahanian4c91d892011-07-13 19:05:43 +0000181
182 if (!Method ||
183 Method->getImplementationControl() != ObjCMethodDecl::Optional) {
184 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
185 = ReferencedSelectors.find(Sel);
186 if (Pos == ReferencedSelectors.end())
187 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
188 }
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000189
John McCallf85e1932011-06-15 23:02:42 +0000190 // In ARC, forbid the user from using @selector for
191 // retain/release/autorelease/dealloc/retainCount.
192 if (getLangOptions().ObjCAutoRefCount) {
193 switch (Sel.getMethodFamily()) {
194 case OMF_retain:
195 case OMF_release:
196 case OMF_autorelease:
197 case OMF_retainCount:
198 case OMF_dealloc:
199 Diag(AtLoc, diag::err_arc_illegal_selector) <<
200 Sel << SourceRange(LParenLoc, RParenLoc);
201 break;
202
203 case OMF_None:
204 case OMF_alloc:
205 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +0000206 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +0000207 case OMF_init:
208 case OMF_mutableCopy:
209 case OMF_new:
210 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +0000211 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +0000212 break;
213 }
214 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000215 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000216 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000217}
218
John McCallf312b1e2010-08-26 23:41:50 +0000219ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
220 SourceLocation AtLoc,
221 SourceLocation ProtoLoc,
222 SourceLocation LParenLoc,
223 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000224 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000225 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000226 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000227 return true;
228 }
Mike Stump1eb44332009-09-09 15:08:12 +0000229
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000230 QualType Ty = Context.getObjCProtoType();
231 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000232 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000233 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000234 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000235}
236
John McCall26743b22011-02-03 09:00:02 +0000237/// Try to capture an implicit reference to 'self'.
238ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
239 // Ignore block scopes: we can capture through them.
240 DeclContext *DC = CurContext;
241 while (true) {
242 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
243 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
244 else break;
245 }
246
247 // If we're not in an ObjC method, error out. Note that, unlike the
248 // C++ case, we don't require an instance method --- class methods
249 // still have a 'self', and we really do still need to capture it!
250 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
251 if (!method)
252 return 0;
253
254 ImplicitParamDecl *self = method->getSelfDecl();
255 assert(self && "capturing 'self' in non-definition?");
256
257 // Mark that we're closing on 'this' in all the block scopes, if applicable.
258 for (unsigned idx = FunctionScopes.size() - 1;
259 isa<BlockScopeInfo>(FunctionScopes[idx]);
John McCall6b5a61b2011-02-07 10:33:21 +0000260 --idx) {
261 BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
262 unsigned &captureIndex = blockScope->CaptureMap[self];
263 if (captureIndex) break;
264
265 bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
266 blockScope->Captures.push_back(
267 BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
268 captureIndex = blockScope->Captures.size(); // +1
269 }
John McCall26743b22011-02-03 09:00:02 +0000270
271 return method;
272}
273
Douglas Gregor926df6c2011-06-11 01:09:30 +0000274QualType Sema::getMessageSendResultType(QualType ReceiverType,
275 ObjCMethodDecl *Method,
276 bool isClassMessage, bool isSuperMessage) {
277 assert(Method && "Must have a method");
278 if (!Method->hasRelatedResultType())
279 return Method->getSendResultType();
280
281 // If a method has a related return type:
282 // - if the method found is an instance method, but the message send
283 // was a class message send, T is the declared return type of the method
284 // found
285 if (Method->isInstanceMethod() && isClassMessage)
286 return Method->getSendResultType();
287
288 // - if the receiver is super, T is a pointer to the class of the
289 // enclosing method definition
290 if (isSuperMessage) {
291 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
292 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
293 return Context.getObjCObjectPointerType(
294 Context.getObjCInterfaceType(Class));
295 }
296
297 // - if the receiver is the name of a class U, T is a pointer to U
298 if (ReceiverType->getAs<ObjCInterfaceType>() ||
299 ReceiverType->isObjCQualifiedInterfaceType())
300 return Context.getObjCObjectPointerType(ReceiverType);
301 // - if the receiver is of type Class or qualified Class type,
302 // T is the declared return type of the method.
303 if (ReceiverType->isObjCClassType() ||
304 ReceiverType->isObjCQualifiedClassType())
305 return Method->getSendResultType();
306
307 // - if the receiver is id, qualified id, Class, or qualified Class, T
308 // is the receiver type, otherwise
309 // - T is the type of the receiver expression.
310 return ReceiverType;
311}
John McCall26743b22011-02-03 09:00:02 +0000312
Douglas Gregor926df6c2011-06-11 01:09:30 +0000313void Sema::EmitRelatedResultTypeNote(const Expr *E) {
314 E = E->IgnoreParenImpCasts();
315 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
316 if (!MsgSend)
317 return;
318
319 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
320 if (!Method)
321 return;
322
323 if (!Method->hasRelatedResultType())
324 return;
325
326 if (Context.hasSameUnqualifiedType(Method->getResultType()
327 .getNonReferenceType(),
328 MsgSend->getType()))
329 return;
330
331 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
332 << Method->isInstanceMethod() << Method->getSelector()
333 << MsgSend->getType();
334}
335
336bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
337 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000338 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000339 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000340 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000341 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000342 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000343 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000344 for (unsigned i = 0; i != NumArgs; i++) {
345 if (Args[i]->isTypeDependent())
346 continue;
347
John Wiegley429bb272011-04-08 18:41:53 +0000348 ExprResult Result = DefaultArgumentPromotion(Args[i]);
349 if (Result.isInvalid())
350 return true;
351 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000352 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000353
John McCallf85e1932011-06-15 23:02:42 +0000354 unsigned DiagID;
355 if (getLangOptions().ObjCAutoRefCount)
356 DiagID = diag::err_arc_method_not_found;
357 else
358 DiagID = isClassMessage ? diag::warn_class_method_not_found
359 : diag::warn_inst_method_not_found;
John McCall819e7452011-08-31 20:57:36 +0000360 if (!getLangOptions().DebuggerSupport)
361 Diag(lbrac, DiagID)
362 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
John McCall48218c62011-07-13 17:56:40 +0000363
364 // In debuggers, we want to use __unknown_anytype for these
365 // results so that clients can cast them.
366 if (getLangOptions().DebuggerSupport) {
367 ReturnType = Context.UnknownAnyTy;
368 } else {
369 ReturnType = Context.getObjCIdType();
370 }
John McCallf89e55a2010-11-18 06:31:45 +0000371 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000372 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000373 }
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Douglas Gregor926df6c2011-06-11 01:09:30 +0000375 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
376 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000377 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000378
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000379 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000380 // Method might have more arguments than selector indicates. This is due
381 // to addition of c-style arguments in method.
382 if (Method->param_size() > Sel.getNumArgs())
383 NumNamedArgs = Method->param_size();
384 // FIXME. This need be cleaned up.
385 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000386 Diag(lbrac, diag::err_typecheck_call_too_few_args)
387 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000388 return false;
389 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000390
Chris Lattner312531a2009-04-12 08:11:20 +0000391 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000392 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000393 // We can't do any type-checking on a type-dependent argument.
394 if (Args[i]->isTypeDependent())
395 continue;
396
Chris Lattner85a932e2008-01-04 22:32:30 +0000397 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000398
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000399 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000400 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000401
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000402 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
403 Param->getType(),
404 PDiag(diag::err_call_incomplete_argument)
405 << argExpr->getSourceRange()))
406 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000407
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000408 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
409 Param);
John McCall3fa5cae2010-10-26 07:05:15 +0000410 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000411 if (ArgE.isInvalid())
412 IsError = true;
413 else
414 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000415 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000416
417 // Promote additional arguments to variadic methods.
418 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000419 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
420 if (Args[i]->isTypeDependent())
421 continue;
422
John Wiegley429bb272011-04-08 18:41:53 +0000423 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
424 IsError |= Arg.isInvalid();
425 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000426 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000427 } else {
428 // Check for extra arguments to non-variadic methods.
429 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000430 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000431 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000432 << 2 /*method*/ << NumNamedArgs << NumArgs
433 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000434 << SourceRange(Args[NumNamedArgs]->getLocStart(),
435 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000436 }
437 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000438 // diagnose nonnull arguments.
439 for (specific_attr_iterator<NonNullAttr>
440 i = Method->specific_attr_begin<NonNullAttr>(),
441 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
442 CheckNonNullArguments(*i, Args, lbrac);
443 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000444
Douglas Gregor2725ca82010-04-21 19:57:20 +0000445 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000446 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000447}
448
John McCallf85e1932011-06-15 23:02:42 +0000449bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000450 // 'self' is objc 'self' in an objc method only.
Fariborz Jahanianb4602102011-03-28 16:23:34 +0000451 DeclContext *DC = CurContext;
452 while (isa<BlockDecl>(DC))
453 DC = DC->getParent();
454 if (DC && !isa<ObjCMethodDecl>(DC))
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000455 return false;
John McCallf85e1932011-06-15 23:02:42 +0000456 receiver = receiver->IgnoreParenLValueCasts();
457 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000458 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
459 return true;
460 return false;
461}
462
Steve Narofff1afaf62009-02-26 15:55:06 +0000463// Helper method for ActOnClassMethod/ActOnInstanceMethod.
464// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000465// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000466// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000467ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000468 ObjCInterfaceDecl *ClassDecl) {
469 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000470 // lookup in class and all superclasses
471 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000472 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000473 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000474
Steve Naroff5609ec02009-03-08 18:56:13 +0000475 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000476 if (!Method)
477 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Steve Naroff5609ec02009-03-08 18:56:13 +0000479 // Before we give up, check if the selector is an instance method.
480 // But only in the root. This matches gcc's behaviour and what the
481 // runtime expects.
482 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000483 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000484 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000485 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000486 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000487 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
488 }
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Steve Naroff5609ec02009-03-08 18:56:13 +0000490 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000491 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000492 return Method;
493}
494
495ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
496 ObjCInterfaceDecl *ClassDecl) {
497 ObjCMethodDecl *Method = 0;
498 while (ClassDecl && !Method) {
499 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000500 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000501 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000502
Steve Naroff5609ec02009-03-08 18:56:13 +0000503 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000504 if (!Method)
505 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000506 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000507 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000508 return Method;
509}
510
Fariborz Jahanian61478062011-03-09 20:18:06 +0000511/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
512/// list of a qualified objective pointer type.
513ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
514 const ObjCObjectPointerType *OPT,
515 bool Instance)
516{
517 ObjCMethodDecl *MD = 0;
518 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
519 E = OPT->qual_end(); I != E; ++I) {
520 ObjCProtocolDecl *PROTO = (*I);
521 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
522 return MD;
523 }
524 }
525 return 0;
526}
527
Chris Lattner7f816522010-04-11 07:45:24 +0000528/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
529/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000530ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000531HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000532 Expr *BaseExpr, SourceLocation OpLoc,
533 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000534 SourceLocation MemberLoc,
535 SourceLocation SuperLoc, QualType SuperType,
536 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000537 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
538 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000539
540 if (MemberName.getNameKind() != DeclarationName::Identifier) {
541 Diag(MemberLoc, diag::err_invalid_property_name)
542 << MemberName << QualType(OPT, 0);
543 return ExprError();
544 }
545
Chris Lattner7f816522010-04-11 07:45:24 +0000546 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
547
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000548 if (IFace->isForwardDecl()) {
549 Diag(MemberLoc, diag::err_property_not_found_forward_class)
550 << MemberName << QualType(OPT, 0);
551 Diag(IFace->getLocation(), diag::note_forward_class);
552 return ExprError();
553 }
Chris Lattner7f816522010-04-11 07:45:24 +0000554 // Search for a declared property first.
555 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
556 // Check whether we can reference this property.
557 if (DiagnoseUseOfDecl(PD, MemberLoc))
558 return ExprError();
559 QualType ResTy = PD->getType();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000560 ResTy = ResTy.getNonLValueExprType(Context);
Chris Lattner7f816522010-04-11 07:45:24 +0000561 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
562 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000563 if (Getter &&
564 (Getter->hasRelatedResultType()
565 || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
566 ResTy = getMessageSendResultType(QualType(OPT, 0), Getter, false,
567 Super);
568
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000569 if (Super)
570 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000571 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000572 MemberLoc,
573 SuperLoc, SuperType));
574 else
575 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000576 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000577 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000578 }
579 // Check protocols on qualified interfaces.
580 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
581 E = OPT->qual_end(); I != E; ++I)
582 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
583 // Check whether we can reference this property.
584 if (DiagnoseUseOfDecl(PD, MemberLoc))
585 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000586
587 QualType T = PD->getType();
588 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
589 T = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000590 if (Super)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000591 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000592 VK_LValue,
593 OK_ObjCProperty,
594 MemberLoc,
595 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000596 else
Douglas Gregor926df6c2011-06-11 01:09:30 +0000597 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000598 VK_LValue,
599 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000600 MemberLoc,
601 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000602 }
603 // If that failed, look for an "implicit" property by seeing if the nullary
604 // selector is implemented.
605
606 // FIXME: The logic for looking up nullary and unary selectors should be
607 // shared with the code in ActOnInstanceMessage.
608
609 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
610 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000611
612 // May be founf in property's qualified list.
613 if (!Getter)
614 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000615
616 // If this reference is in an @implementation, check for 'private' methods.
617 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000618 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000619
620 // Look through local category implementations associated with the class.
621 if (!Getter)
622 Getter = IFace->getCategoryInstanceMethod(Sel);
623 if (Getter) {
624 // Check if we can reference this property.
625 if (DiagnoseUseOfDecl(Getter, MemberLoc))
626 return ExprError();
627 }
628 // If we found a getter then this may be a valid dot-reference, we
629 // will look for the matching setter, in case it is needed.
630 Selector SetterSel =
631 SelectorTable::constructSetterName(PP.getIdentifierTable(),
632 PP.getSelectorTable(), Member);
633 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000634
635 // May be founf in property's qualified list.
636 if (!Setter)
637 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
638
Chris Lattner7f816522010-04-11 07:45:24 +0000639 if (!Setter) {
640 // If this reference is in an @implementation, also check for 'private'
641 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000642 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000643 }
644 // Look through local category implementations associated with the class.
645 if (!Setter)
646 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000647
Chris Lattner7f816522010-04-11 07:45:24 +0000648 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
649 return ExprError();
650
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000651 if (Getter || Setter) {
652 QualType PType;
653 if (Getter)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000654 PType = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000655 else {
656 ParmVarDecl *ArgDecl = *Setter->param_begin();
657 PType = ArgDecl->getType();
658 }
659
John McCall09431682010-11-18 19:01:18 +0000660 ExprValueKind VK = VK_LValue;
661 ExprObjectKind OK = OK_ObjCProperty;
662 if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
663 PType->isVoidType())
664 VK = VK_RValue, OK = OK_Ordinary;
665
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000666 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000667 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
668 PType, VK, OK,
669 MemberLoc,
670 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000671 else
John McCall12f78a62010-12-02 01:19:52 +0000672 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
673 PType, VK, OK,
674 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000675
Chris Lattner7f816522010-04-11 07:45:24 +0000676 }
677
678 // Attempt to correct for typos in property names.
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000679 TypoCorrection Corrected = CorrectTypo(
680 DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL,
681 NULL, IFace, false, CTC_NoKeywords, OPT);
682 if (ObjCPropertyDecl *Property =
683 Corrected.getCorrectionDeclAs<ObjCPropertyDecl>()) {
684 DeclarationName TypoResult = Corrected.getCorrection();
Chris Lattner7f816522010-04-11 07:45:24 +0000685 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000686 << MemberName << QualType(OPT, 0) << TypoResult
687 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000688 Diag(Property->getLocation(), diag::note_previous_decl)
689 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000690 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
691 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000692 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000693 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000694 ObjCInterfaceDecl *ClassDeclared;
695 if (ObjCIvarDecl *Ivar =
696 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
697 QualType T = Ivar->getType();
698 if (const ObjCObjectPointerType * OBJPT =
699 T->getAsObjCInterfacePointerType()) {
700 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
701 if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
702 if (IFace->isForwardDecl()) {
703 Diag(MemberLoc, diag::err_property_not_as_forward_class)
Fariborz Jahanian2a96bf52011-02-17 17:30:05 +0000704 << MemberName << IFace;
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000705 Diag(IFace->getLocation(), diag::note_forward_class);
706 return ExprError();
707 }
708 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000709 Diag(MemberLoc,
710 diag::err_ivar_access_using_property_syntax_suggest)
711 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
712 << FixItHint::CreateReplacement(OpLoc, "->");
713 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000714 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000715
Chris Lattner7f816522010-04-11 07:45:24 +0000716 Diag(MemberLoc, diag::err_property_not_found)
717 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000718 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000719 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000720 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000721 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000722}
723
724
725
John McCall60d7b3a2010-08-24 06:29:42 +0000726ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000727ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
728 IdentifierInfo &propertyName,
729 SourceLocation receiverNameLoc,
730 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000732 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000733 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
734 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000735
736 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000737 if (IFace == 0) {
738 // If the "receiver" is 'super' in a method, handle it as an expression-like
739 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000740 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000741 IsSuper = true;
742
John McCall26743b22011-02-03 09:00:02 +0000743 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000744 if (CurMethod->isInstanceMethod()) {
745 QualType T =
746 Context.getObjCInterfaceType(CurMethod->getClassInterface());
747 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000748
749 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000750 /*BaseExpr*/0,
751 SourceLocation()/*OpLoc*/,
752 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000753 propertyNameLoc,
754 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000755 }
Mike Stump1eb44332009-09-09 15:08:12 +0000756
Chris Lattnereb483eb2010-04-11 08:28:14 +0000757 // Otherwise, if this is a class method, try dispatching to our
758 // superclass.
759 IFace = CurMethod->getClassInterface()->getSuperClass();
760 }
John McCall26743b22011-02-03 09:00:02 +0000761 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000762
763 if (IFace == 0) {
764 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
765 return ExprError();
766 }
767 }
768
769 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000770 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000771 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000772
773 // If this reference is in an @implementation, check for 'private' methods.
774 if (!Getter)
775 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
776 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000777 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000778 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000779
780 if (Getter) {
781 // FIXME: refactor/share with ActOnMemberReference().
782 // Check if we can reference this property.
783 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
784 return ExprError();
785 }
Mike Stump1eb44332009-09-09 15:08:12 +0000786
Steve Naroff61f72cb2009-03-09 21:12:44 +0000787 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000788 Selector SetterSel =
789 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000790 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000791
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000792 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000793 if (!Setter) {
794 // If this reference is in an @implementation, also check for 'private'
795 // methods.
796 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
797 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000798 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000799 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000800 }
801 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000802 if (!Setter)
803 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000804
805 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
806 return ExprError();
807
808 if (Getter || Setter) {
809 QualType PType;
810
John McCall09431682010-11-18 19:01:18 +0000811 ExprValueKind VK = VK_LValue;
812 if (Getter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000813 PType = getMessageSendResultType(Context.getObjCInterfaceType(IFace),
814 Getter, true,
815 receiverNamePtr->isStr("super"));
John McCall09431682010-11-18 19:01:18 +0000816 if (!getLangOptions().CPlusPlus &&
817 !PType.hasQualifiers() && PType->isVoidType())
818 VK = VK_RValue;
819 } else {
Steve Naroff61f72cb2009-03-09 21:12:44 +0000820 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
821 E = Setter->param_end(); PI != E; ++PI)
822 PType = (*PI)->getType();
John McCall09431682010-11-18 19:01:18 +0000823 VK = VK_LValue;
Steve Naroff61f72cb2009-03-09 21:12:44 +0000824 }
John McCall09431682010-11-18 19:01:18 +0000825
826 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
827
Douglas Gregor926df6c2011-06-11 01:09:30 +0000828 if (IsSuper)
829 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
830 PType, VK, OK,
831 propertyNameLoc,
832 receiverNameLoc,
833 Context.getObjCInterfaceType(IFace)));
834
John McCall12f78a62010-12-02 01:19:52 +0000835 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
836 PType, VK, OK,
837 propertyNameLoc,
838 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000839 }
840 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
841 << &propertyName << Context.getObjCInterfaceType(IFace));
842}
843
Douglas Gregor47bd5432010-04-14 02:46:37 +0000844Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000845 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000846 SourceLocation NameLoc,
847 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000848 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000849 ParsedType &ReceiverType) {
850 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000851
Douglas Gregor47bd5432010-04-14 02:46:37 +0000852 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000853 // messaging super. If the identifier is "super" and there is a
854 // trailing dot, it's an instance message.
855 if (IsSuper && S->isInObjcMethodScope())
856 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000857
858 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
859 LookupName(Result, S);
860
861 switch (Result.getResultKind()) {
862 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000863 // Normal name lookup didn't find anything. If we're in an
864 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000865 // FIXME: This is a hack. Ivar lookup should be part of normal
866 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000867 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
868 ObjCInterfaceDecl *ClassDeclared;
869 if (Method->getClassInterface()->lookupInstanceVariable(Name,
870 ClassDeclared))
871 return ObjCInstanceMessage;
872 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000873
Douglas Gregor47bd5432010-04-14 02:46:37 +0000874 // Break out; we'll perform typo correction below.
875 break;
876
877 case LookupResult::NotFoundInCurrentInstantiation:
878 case LookupResult::FoundOverloaded:
879 case LookupResult::FoundUnresolvedValue:
880 case LookupResult::Ambiguous:
881 Result.suppressDiagnostics();
882 return ObjCInstanceMessage;
883
884 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000885 // If the identifier is a class or not, and there is a trailing dot,
886 // it's an instance message.
887 if (HasTrailingDot)
888 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000889 // We found something. If it's a type, then we have a class
890 // message. Otherwise, it's an instance message.
891 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000892 QualType T;
893 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
894 T = Context.getObjCInterfaceType(Class);
895 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
896 T = Context.getTypeDeclType(Type);
897 else
898 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000899
Douglas Gregor1569f952010-04-21 20:38:13 +0000900 // We have a class message, and T is the type we're
901 // messaging. Build source-location information for it.
902 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000903 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000904 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000905 }
906 }
907
Douglas Gregoraaf87162010-04-14 20:04:41 +0000908 // Determine our typo-correction context.
909 CorrectTypoContext CTC = CTC_Expression;
910 if (ObjCMethodDecl *Method = getCurMethodDecl())
911 if (Method->getClassInterface() &&
912 Method->getClassInterface()->getSuperClass())
913 CTC = CTC_ObjCMessageReceiver;
914
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000915 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
916 Result.getLookupKind(), S, NULL,
917 NULL, false, CTC)) {
918 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000919 // If we found a declaration, correct when it refers to an Objective-C
920 // class.
Douglas Gregor1569f952010-04-21 20:38:13 +0000921 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000922 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000923 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000924 << FixItHint::CreateReplacement(SourceRange(NameLoc),
925 ND->getNameAsString());
926 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000927 << Corrected.getCorrection();
Douglas Gregor47bd5432010-04-14 02:46:37 +0000928
Douglas Gregor1569f952010-04-21 20:38:13 +0000929 QualType T = Context.getObjCInterfaceType(Class);
930 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000931 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000932 return ObjCClassMessage;
933 }
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000934 } else if (Corrected.isKeyword() &&
935 Corrected.getCorrectionAsIdentifierInfo()->isStr("super")) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000936 // If we've found the keyword "super", this is a send to super.
937 Diag(NameLoc, diag::err_unknown_receiver_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000938 << Name << Corrected.getCorrection()
Douglas Gregoraaf87162010-04-14 20:04:41 +0000939 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000940 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000941 }
942 }
943
944 // Fall back: let the parser try to parse it as an instance message.
945 return ObjCInstanceMessage;
946}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000947
John McCall60d7b3a2010-08-24 06:29:42 +0000948ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000949 SourceLocation SuperLoc,
950 Selector Sel,
951 SourceLocation LBracLoc,
952 SourceLocation SelectorLoc,
953 SourceLocation RBracLoc,
954 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000955 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000956 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000957 if (!Method) {
958 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
959 return ExprError();
960 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000961
Douglas Gregorf95861a2010-04-21 20:01:04 +0000962 ObjCInterfaceDecl *Class = Method->getClassInterface();
963 if (!Class) {
964 Diag(SuperLoc, diag::error_no_super_class_message)
965 << Method->getDeclName();
966 return ExprError();
967 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000968
Douglas Gregorf95861a2010-04-21 20:01:04 +0000969 ObjCInterfaceDecl *Super = Class->getSuperClass();
970 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000971 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000972 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
973 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000974 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000975 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000976
Douglas Gregorf95861a2010-04-21 20:01:04 +0000977 // We are in a method whose class has a superclass, so 'super'
978 // is acting as a keyword.
979 if (Method->isInstanceMethod()) {
Nico Weber9a1ecf02011-08-22 17:25:57 +0000980 if (Sel.getMethodFamily() == OMF_dealloc)
981 ObjCShouldCallSuperDealloc = false;
Nico Weber80cb6e62011-08-28 22:35:17 +0000982 if (Sel.getMethodFamily() == OMF_finalize)
983 ObjCShouldCallSuperFinalize = false;
Nico Weber9a1ecf02011-08-22 17:25:57 +0000984
Douglas Gregorf95861a2010-04-21 20:01:04 +0000985 // Since we are in an instance method, this is an instance
986 // message to the superclass instance.
987 QualType SuperTy = Context.getObjCInterfaceType(Super);
988 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +0000989 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000990 Sel, /*Method=*/0,
991 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000992 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000993
994 // Since we are in a class method, this is a class message to
995 // the superclass.
996 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
997 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000998 SuperLoc, Sel, /*Method=*/0,
999 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001000}
1001
1002/// \brief Build an Objective-C class message expression.
1003///
1004/// This routine takes care of both normal class messages and
1005/// class messages to the superclass.
1006///
1007/// \param ReceiverTypeInfo Type source information that describes the
1008/// receiver of this message. This may be NULL, in which case we are
1009/// sending to the superclass and \p SuperLoc must be a valid source
1010/// location.
1011
1012/// \param ReceiverType The type of the object receiving the
1013/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
1014/// type as that refers to. For a superclass send, this is the type of
1015/// the superclass.
1016///
1017/// \param SuperLoc The location of the "super" keyword in a
1018/// superclass message.
1019///
1020/// \param Sel The selector to which the message is being sent.
1021///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001022/// \param Method The method that this class message is invoking, if
1023/// already known.
1024///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001025/// \param LBracLoc The location of the opening square bracket ']'.
1026///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001027/// \param RBrac The location of the closing square bracket ']'.
1028///
1029/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001030ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001031 QualType ReceiverType,
1032 SourceLocation SuperLoc,
1033 Selector Sel,
1034 ObjCMethodDecl *Method,
1035 SourceLocation LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001036 SourceLocation SelectorLoc,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001037 SourceLocation RBracLoc,
1038 MultiExprArg ArgsIn) {
1039 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001040 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001041 if (LBracLoc.isInvalid()) {
1042 Diag(Loc, diag::err_missing_open_square_message_send)
1043 << FixItHint::CreateInsertion(Loc, "[");
1044 LBracLoc = Loc;
1045 }
1046
Douglas Gregor92e986e2010-04-22 16:44:27 +00001047 if (ReceiverType->isDependentType()) {
1048 // If the receiver type is dependent, we can't type-check anything
1049 // at this point. Build a dependent expression.
1050 unsigned NumArgs = ArgsIn.size();
1051 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1052 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001053 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1054 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001055 Sel, SelectorLoc, /*Method=*/0,
Douglas Gregor92e986e2010-04-22 16:44:27 +00001056 Args, NumArgs, RBracLoc));
1057 }
Chris Lattner15faee12010-04-12 05:38:43 +00001058
Douglas Gregor2725ca82010-04-21 19:57:20 +00001059 // Find the class to which we are sending this message.
1060 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001061 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1062 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001063 Diag(Loc, diag::err_invalid_receiver_class_message)
1064 << ReceiverType;
1065 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001066 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001067 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian02b0d652011-03-08 19:12:46 +00001068 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001069 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001070 if (!Method) {
1071 if (Class->isForwardDecl()) {
John McCallf85e1932011-06-15 23:02:42 +00001072 if (getLangOptions().ObjCAutoRefCount) {
1073 Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
1074 } else {
1075 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1076 }
1077
Douglas Gregorf49bb082010-04-22 17:01:48 +00001078 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001079 Method = LookupFactoryMethodInGlobalPool(Sel,
1080 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001081 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001082 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1083 << Method->getDeclName();
1084 }
1085 if (!Method)
1086 Method = Class->lookupClassMethod(Sel);
1087
1088 // If we have an implementation in scope, check "private" methods.
1089 if (!Method)
1090 Method = LookupPrivateClassMethod(Sel, Class);
1091
1092 if (Method && DiagnoseUseOfDecl(Method, Loc))
1093 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001094 }
Mike Stump1eb44332009-09-09 15:08:12 +00001095
Douglas Gregor2725ca82010-04-21 19:57:20 +00001096 // Check the argument types and determine the result type.
1097 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001098 ExprValueKind VK = VK_RValue;
1099
Douglas Gregor2725ca82010-04-21 19:57:20 +00001100 unsigned NumArgs = ArgsIn.size();
1101 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001102 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1103 SuperLoc.isValid(), LBracLoc, RBracLoc,
1104 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001105 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001106
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001107 if (Method && !Method->getResultType()->isVoidType() &&
1108 RequireCompleteType(LBracLoc, Method->getResultType(),
1109 diag::err_illegal_message_expr_incomplete_type))
1110 return ExprError();
1111
Douglas Gregor2725ca82010-04-21 19:57:20 +00001112 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001113 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001114 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001115 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001116 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001117 ReceiverType, Sel, SelectorLoc,
1118 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001119 else
John McCallf89e55a2010-11-18 06:31:45 +00001120 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001121 ReceiverTypeInfo, Sel, SelectorLoc,
1122 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001123 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001124}
1125
Douglas Gregor2725ca82010-04-21 19:57:20 +00001126// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001127// ArgExprs is optional - if it is present, the number of expressions
1128// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001129ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001130 ParsedType Receiver,
1131 Selector Sel,
1132 SourceLocation LBracLoc,
1133 SourceLocation SelectorLoc,
1134 SourceLocation RBracLoc,
1135 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001136 TypeSourceInfo *ReceiverTypeInfo;
1137 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1138 if (ReceiverType.isNull())
1139 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Mike Stump1eb44332009-09-09 15:08:12 +00001141
Douglas Gregor2725ca82010-04-21 19:57:20 +00001142 if (!ReceiverTypeInfo)
1143 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1144
1145 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001146 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001147 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001148}
1149
1150/// \brief Build an Objective-C instance message expression.
1151///
1152/// This routine takes care of both normal instance messages and
1153/// instance messages to the superclass instance.
1154///
1155/// \param Receiver The expression that computes the object that will
1156/// receive this message. This may be empty, in which case we are
1157/// sending to the superclass instance and \p SuperLoc must be a valid
1158/// source location.
1159///
1160/// \param ReceiverType The (static) type of the object receiving the
1161/// message. When a \p Receiver expression is provided, this is the
1162/// same type as that expression. For a superclass instance send, this
1163/// is a pointer to the type of the superclass.
1164///
1165/// \param SuperLoc The location of the "super" keyword in a
1166/// superclass instance message.
1167///
1168/// \param Sel The selector to which the message is being sent.
1169///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001170/// \param Method The method that this instance message is invoking, if
1171/// already known.
1172///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001173/// \param LBracLoc The location of the opening square bracket ']'.
1174///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001175/// \param RBrac The location of the closing square bracket ']'.
1176///
1177/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001178ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001179 QualType ReceiverType,
1180 SourceLocation SuperLoc,
1181 Selector Sel,
1182 ObjCMethodDecl *Method,
1183 SourceLocation LBracLoc,
1184 SourceLocation SelectorLoc,
1185 SourceLocation RBracLoc,
1186 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001187 // The location of the receiver.
1188 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1189
1190 if (LBracLoc.isInvalid()) {
1191 Diag(Loc, diag::err_missing_open_square_message_send)
1192 << FixItHint::CreateInsertion(Loc, "[");
1193 LBracLoc = Loc;
1194 }
1195
Douglas Gregor2725ca82010-04-21 19:57:20 +00001196 // If we have a receiver expression, perform appropriate promotions
1197 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001198 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001199 if (Receiver->isTypeDependent()) {
1200 // If the receiver is type-dependent, we can't type-check anything
1201 // at this point. Build a dependent expression.
1202 unsigned NumArgs = ArgsIn.size();
1203 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1204 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1205 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001206 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001207 SelectorLoc, /*Method=*/0,
1208 Args, NumArgs, RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001209 }
1210
Douglas Gregor2725ca82010-04-21 19:57:20 +00001211 // If necessary, apply function/array conversion to the receiver.
1212 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001213 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1214 if (Result.isInvalid())
1215 return ExprError();
1216 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001217 ReceiverType = Receiver->getType();
1218 }
1219
Douglas Gregorf49bb082010-04-22 17:01:48 +00001220 if (!Method) {
1221 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001222 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001223 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001224 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1225 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001226 SourceRange(LBracLoc, RBracLoc),
1227 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001228 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001229 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001230 SourceRange(LBracLoc, RBracLoc),
1231 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001232 } else if (ReceiverType->isObjCClassType() ||
1233 ReceiverType->isObjCQualifiedClassType()) {
1234 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001235 // We allow sending a message to a qualified Class ("Class<foo>"), which
1236 // is ok as long as one of the protocols implements the selector (if not, warn).
1237 if (const ObjCObjectPointerType *QClassTy
1238 = ReceiverType->getAsObjCQualifiedClassType()) {
1239 // Search protocols for class methods.
1240 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1241 if (!Method) {
1242 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1243 // warn if instance method found for a Class message.
1244 if (Method) {
1245 Diag(Loc, diag::warn_instance_method_on_class_found)
1246 << Method->getSelector() << Sel;
1247 Diag(Method->getLocation(), diag::note_method_declared_at);
1248 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001249 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001250 } else {
1251 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1252 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1253 // First check the public methods in the class interface.
1254 Method = ClassDecl->lookupClassMethod(Sel);
1255
1256 if (!Method)
1257 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1258 }
1259 if (Method && DiagnoseUseOfDecl(Method, Loc))
1260 return ExprError();
1261 }
1262 if (!Method) {
1263 // If not messaging 'self', look for any factory method named 'Sel'.
1264 if (!Receiver || !isSelfExpr(Receiver)) {
1265 Method = LookupFactoryMethodInGlobalPool(Sel,
1266 SourceRange(LBracLoc, RBracLoc),
1267 true);
1268 if (!Method) {
1269 // If no class (factory) method was found, check if an _instance_
1270 // method of the same name exists in the root class only.
1271 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001272 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001273 true);
1274 if (Method)
1275 if (const ObjCInterfaceDecl *ID =
1276 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1277 if (ID->getSuperClass())
1278 Diag(Loc, diag::warn_root_inst_method_not_found)
1279 << Sel << SourceRange(LBracLoc, RBracLoc);
1280 }
1281 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001282 }
1283 }
1284 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001285 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001286 ObjCInterfaceDecl* ClassDecl = 0;
1287
1288 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1289 // long as one of the protocols implements the selector (if not, warn).
1290 if (const ObjCObjectPointerType *QIdTy
1291 = ReceiverType->getAsObjCQualifiedIdType()) {
1292 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001293 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1294 if (!Method)
1295 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001296 } else if (const ObjCObjectPointerType *OCIType
1297 = ReceiverType->getAsObjCInterfacePointerType()) {
1298 // We allow sending a message to a pointer to an interface (an object).
1299 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001300
1301 if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCount) {
1302 Diag(Loc, diag::err_arc_receiver_forward_instance)
1303 << OCIType->getPointeeType()
1304 << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperLoc));
1305 return ExprError();
1306 }
1307
Douglas Gregorf49bb082010-04-22 17:01:48 +00001308 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1309 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +00001310 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001311 Method = ClassDecl->lookupInstanceMethod(Sel);
1312
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001313 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001314 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001315 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1316
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001317 const ObjCInterfaceDecl *forwardClass = 0;
Douglas Gregorf49bb082010-04-22 17:01:48 +00001318 if (!Method) {
1319 // If we have implementations in scope, check "private" methods.
1320 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1321
John McCallf85e1932011-06-15 23:02:42 +00001322 if (!Method && getLangOptions().ObjCAutoRefCount) {
1323 Diag(Loc, diag::err_arc_may_not_respond)
1324 << OCIType->getPointeeType() << Sel;
1325 return ExprError();
1326 }
1327
Douglas Gregorf49bb082010-04-22 17:01:48 +00001328 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1329 // If we still haven't found a method, look in the global pool. This
1330 // behavior isn't very desirable, however we need it for GCC
1331 // compatibility. FIXME: should we deviate??
1332 if (OCIType->qual_empty()) {
1333 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001334 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001335 if (OCIType->getInterfaceDecl()->isForwardDecl())
1336 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001337 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001338 Diag(Loc, diag::warn_maynot_respond)
1339 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1340 }
1341 }
1342 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001343 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001344 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001345 } else if (!getLangOptions().ObjCAutoRefCount &&
1346 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001347 (ReceiverType->isPointerType() ||
1348 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001349 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001350 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001351 Diag(Loc, diag::warn_bad_receiver_type)
1352 << ReceiverType
1353 << Receiver->getSourceRange();
1354 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001355 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1356 CK_BitCast).take();
John McCall404cd162010-11-13 01:35:44 +00001357 else {
1358 // TODO: specialized warning on null receivers?
1359 bool IsNull = Receiver->isNullPointerConstant(Context,
1360 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001361 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1362 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001363 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001364 ReceiverType = Receiver->getType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00001365 }
John Wiegley429bb272011-04-08 18:41:53 +00001366 else {
1367 ExprResult ReceiverRes;
1368 if (getLangOptions().CPlusPlus)
1369 ReceiverRes = PerformContextuallyConvertToObjCId(Receiver);
1370 if (ReceiverRes.isUsable()) {
1371 Receiver = ReceiverRes.take();
1372 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
1373 Receiver = ICE->getSubExpr();
1374 ReceiverType = Receiver->getType();
1375 }
1376 return BuildInstanceMessage(Receiver,
1377 ReceiverType,
1378 SuperLoc,
1379 Sel,
1380 Method,
1381 LBracLoc,
1382 SelectorLoc,
1383 RBracLoc,
1384 move(ArgsIn));
1385 } else {
1386 // Reject other random receiver types (e.g. structs).
1387 Diag(Loc, diag::err_bad_receiver_type)
1388 << ReceiverType << Receiver->getSourceRange();
1389 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001390 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001391 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001392 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001393 }
Mike Stump1eb44332009-09-09 15:08:12 +00001394
Douglas Gregor2725ca82010-04-21 19:57:20 +00001395 // Check the message arguments.
1396 unsigned NumArgs = ArgsIn.size();
1397 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1398 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001399 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001400 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1401 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001402 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1403 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001404 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001405 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001406
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001407 if (Method && !Method->getResultType()->isVoidType() &&
1408 RequireCompleteType(LBracLoc, Method->getResultType(),
1409 diag::err_illegal_message_expr_incomplete_type))
1410 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001411
John McCallf85e1932011-06-15 23:02:42 +00001412 // In ARC, forbid the user from sending messages to
1413 // retain/release/autorelease/dealloc/retainCount explicitly.
1414 if (getLangOptions().ObjCAutoRefCount) {
1415 ObjCMethodFamily family =
1416 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1417 switch (family) {
1418 case OMF_init:
1419 if (Method)
1420 checkInitMethod(Method, ReceiverType);
1421
1422 case OMF_None:
1423 case OMF_alloc:
1424 case OMF_copy:
Nico Weber80cb6e62011-08-28 22:35:17 +00001425 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00001426 case OMF_mutableCopy:
1427 case OMF_new:
1428 case OMF_self:
1429 break;
1430
1431 case OMF_dealloc:
1432 case OMF_retain:
1433 case OMF_release:
1434 case OMF_autorelease:
1435 case OMF_retainCount:
1436 Diag(Loc, diag::err_arc_illegal_explicit_message)
1437 << Sel << SelectorLoc;
1438 break;
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001439
1440 case OMF_performSelector:
1441 if (Method && NumArgs >= 1) {
1442 if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) {
1443 Selector ArgSel = SelExp->getSelector();
1444 ObjCMethodDecl *SelMethod =
1445 LookupInstanceMethodInGlobalPool(ArgSel,
1446 SelExp->getSourceRange());
1447 if (!SelMethod)
1448 SelMethod =
1449 LookupFactoryMethodInGlobalPool(ArgSel,
1450 SelExp->getSourceRange());
1451 if (SelMethod) {
1452 ObjCMethodFamily SelFamily = SelMethod->getMethodFamily();
1453 switch (SelFamily) {
1454 case OMF_alloc:
1455 case OMF_copy:
1456 case OMF_mutableCopy:
1457 case OMF_new:
1458 case OMF_self:
1459 case OMF_init:
1460 // Issue error, unless ns_returns_not_retained.
1461 if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1462 // selector names a +1 method
1463 Diag(SelectorLoc,
1464 diag::err_arc_perform_selector_retains);
1465 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1466 }
1467 break;
1468 default:
1469 // +0 call. OK. unless ns_returns_retained.
1470 if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) {
1471 // selector names a +1 method
1472 Diag(SelectorLoc,
1473 diag::err_arc_perform_selector_retains);
1474 Diag(SelMethod->getLocation(), diag::note_method_declared_at);
1475 }
1476 break;
1477 }
1478 }
1479 } else {
1480 // error (may leak).
1481 Diag(SelectorLoc, diag::warn_arc_perform_selector_leaks);
1482 Diag(Args[0]->getExprLoc(), diag::note_used_here);
1483 }
1484 }
1485 break;
John McCallf85e1932011-06-15 23:02:42 +00001486 }
1487 }
1488
Douglas Gregor2725ca82010-04-21 19:57:20 +00001489 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001490 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001491 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001492 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001493 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001494 ReceiverType, Sel, SelectorLoc, Method,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001495 Args, NumArgs, RBracLoc);
1496 else
John McCallf89e55a2010-11-18 06:31:45 +00001497 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001498 Receiver, Sel, SelectorLoc, Method,
1499 Args, NumArgs, RBracLoc);
John McCallf85e1932011-06-15 23:02:42 +00001500
1501 if (getLangOptions().ObjCAutoRefCount) {
1502 // In ARC, annotate delegate init calls.
1503 if (Result->getMethodFamily() == OMF_init &&
1504 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
1505 // Only consider init calls *directly* in init implementations,
1506 // not within blocks.
1507 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1508 if (method && method->getMethodFamily() == OMF_init) {
1509 // The implicit assignment to self means we also don't want to
1510 // consume the result.
1511 Result->setDelegateInitCall(true);
1512 return Owned(Result);
1513 }
1514 }
1515
1516 // In ARC, check for message sends which are likely to introduce
1517 // retain cycles.
1518 checkRetainCycles(Result);
1519 }
1520
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001521 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001522}
1523
1524// ActOnInstanceMessage - used for both unary and keyword messages.
1525// ArgExprs is optional - if it is present, the number of expressions
1526// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001527ExprResult Sema::ActOnInstanceMessage(Scope *S,
1528 Expr *Receiver,
1529 Selector Sel,
1530 SourceLocation LBracLoc,
1531 SourceLocation SelectorLoc,
1532 SourceLocation RBracLoc,
1533 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001534 if (!Receiver)
1535 return ExprError();
1536
John McCall9ae2f072010-08-23 23:25:46 +00001537 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001538 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001539 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001540}
Chris Lattnereca7be62008-04-07 05:30:13 +00001541
John McCallf85e1932011-06-15 23:02:42 +00001542enum ARCConversionTypeClass {
1543 ACTC_none,
1544 ACTC_retainable,
1545 ACTC_indirectRetainable
1546};
1547static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
1548 ARCConversionTypeClass ACTC = ACTC_retainable;
1549
1550 // Ignore an outermost reference type.
1551 if (const ReferenceType *ref = type->getAs<ReferenceType>())
1552 type = ref->getPointeeType();
1553
1554 // Drill through pointers and arrays recursively.
1555 while (true) {
1556 if (const PointerType *ptr = type->getAs<PointerType>()) {
1557 type = ptr->getPointeeType();
1558 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1559 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1560 } else {
1561 break;
1562 }
1563 ACTC = ACTC_indirectRetainable;
1564 }
1565
1566 if (!type->isObjCRetainableType()) return ACTC_none;
1567 return ACTC;
1568}
1569
1570namespace {
1571 /// Return true if the given expression can be reasonably converted
1572 /// between a retainable pointer type and a C pointer type.
1573 struct ARCCastChecker : StmtVisitor<ARCCastChecker, bool> {
1574 ASTContext &Context;
1575 ARCCastChecker(ASTContext &Context) : Context(Context) {}
1576 bool VisitStmt(Stmt *s) {
1577 return false;
1578 }
1579 bool VisitExpr(Expr *e) {
1580 return e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
1581 }
1582
1583 bool VisitParenExpr(ParenExpr *e) {
1584 return Visit(e->getSubExpr());
1585 }
1586 bool VisitCastExpr(CastExpr *e) {
1587 switch (e->getCastKind()) {
1588 case CK_NullToPointer:
1589 return true;
1590 case CK_NoOp:
1591 case CK_LValueToRValue:
1592 case CK_BitCast:
1593 case CK_AnyPointerToObjCPointerCast:
1594 case CK_AnyPointerToBlockPointerCast:
1595 return Visit(e->getSubExpr());
1596 default:
1597 return false;
1598 }
1599 }
1600 bool VisitUnaryExtension(UnaryOperator *e) {
1601 return Visit(e->getSubExpr());
1602 }
1603 bool VisitBinComma(BinaryOperator *e) {
1604 return Visit(e->getRHS());
1605 }
1606 bool VisitConditionalOperator(ConditionalOperator *e) {
1607 // Conditional operators are okay if both sides are okay.
1608 return Visit(e->getTrueExpr()) && Visit(e->getFalseExpr());
1609 }
1610 bool VisitObjCStringLiteral(ObjCStringLiteral *e) {
1611 // Always white-list Objective-C string literals.
1612 return true;
1613 }
1614 bool VisitStmtExpr(StmtExpr *e) {
1615 return Visit(e->getSubStmt()->body_back());
1616 }
1617 bool VisitDeclRefExpr(DeclRefExpr *e) {
1618 // White-list references to global extern strings from system
1619 // headers.
1620 if (VarDecl *var = dyn_cast<VarDecl>(e->getDecl()))
1621 if (var->getStorageClass() == SC_Extern &&
1622 var->getType().isConstQualified() &&
1623 Context.getSourceManager().isInSystemHeader(var->getLocation()))
1624 return true;
1625 return false;
1626 }
1627 };
1628}
1629
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001630bool
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001631Sema::ValidObjCARCNoBridgeCastExpr(Expr *&Exp, QualType castType) {
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001632 Expr *NewExp = Exp->IgnoreParenCasts();
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001633
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001634 if (!isa<ObjCMessageExpr>(NewExp) && !isa<ObjCPropertyRefExpr>(NewExp)
1635 && !isa<CallExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001636 return false;
1637 ObjCMethodDecl *method = 0;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001638 bool MethodReturnsPlusOne = false;
1639
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001640 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(NewExp)) {
1641 method = PRE->getExplicitProperty()->getGetterMethodDecl();
1642 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001643 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001644 method = ME->getMethodDecl();
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001645 else {
1646 CallExpr *CE = cast<CallExpr>(NewExp);
1647 Decl *CallDecl = CE->getCalleeDecl();
1648 if (!CallDecl)
1649 return false;
1650 if (CallDecl->hasAttr<CFReturnsNotRetainedAttr>())
1651 return true;
1652 MethodReturnsPlusOne = CallDecl->hasAttr<CFReturnsRetainedAttr>();
1653 if (!MethodReturnsPlusOne) {
1654 if (NamedDecl *ND = dyn_cast<NamedDecl>(CallDecl))
1655 if (const IdentifierInfo *Id = ND->getIdentifier())
1656 if (Id->isStr("__builtin___CFStringMakeConstantString"))
1657 return true;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001658 }
1659 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001660
1661 if (!MethodReturnsPlusOne) {
1662 if (!method)
1663 return false;
1664 if (method->hasAttr<CFReturnsNotRetainedAttr>())
1665 return true;
1666 MethodReturnsPlusOne = method->hasAttr<CFReturnsRetainedAttr>();
1667 if (!MethodReturnsPlusOne) {
1668 ObjCMethodFamily family = method->getSelector().getMethodFamily();
1669 switch (family) {
1670 case OMF_alloc:
1671 case OMF_copy:
1672 case OMF_mutableCopy:
1673 case OMF_new:
1674 MethodReturnsPlusOne = true;
1675 break;
1676 default:
1677 break;
1678 }
1679 }
1680 }
1681
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001682 if (MethodReturnsPlusOne) {
1683 TypeSourceInfo *TSInfo =
1684 Context.getTrivialTypeSourceInfo(castType, SourceLocation());
1685 ExprResult ExpRes = BuildObjCBridgedCast(SourceLocation(), OBC_BridgeTransfer,
1686 SourceLocation(), TSInfo, Exp);
1687 Exp = ExpRes.take();
1688 }
1689 return true;
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001690}
1691
John McCallf85e1932011-06-15 23:02:42 +00001692void
1693Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001694 Expr *&castExpr, CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00001695 QualType castExprType = castExpr->getType();
1696
1697 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1698 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
1699 if (exprACTC == castACTC) return;
Fariborz Jahanian8295b7b2011-06-22 16:36:45 +00001700 if (exprACTC && castType->isIntegralType(Context)) return;
John McCallf85e1932011-06-15 23:02:42 +00001701
1702 // Allow casts between pointers to lifetime types (e.g., __strong id*)
1703 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1704 // must be explicit.
1705 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
1706 if (const PointerType *CastExprPtr = castExprType->getAs<PointerType>()) {
1707 QualType CastPointee = CastPtr->getPointeeType();
1708 QualType CastExprPointee = CastExprPtr->getPointeeType();
1709 if ((CCK != CCK_ImplicitConversion &&
1710 CastPointee->isObjCIndirectLifetimeType() &&
1711 CastExprPointee->isVoidType()) ||
1712 (CastPointee->isVoidType() &&
1713 CastExprPointee->isObjCIndirectLifetimeType()))
1714 return;
1715 }
1716 }
1717
1718 if (ARCCastChecker(Context).Visit(castExpr))
1719 return;
1720
1721 SourceLocation loc =
1722 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
1723
1724 if (makeUnavailableInSystemHeader(loc,
1725 "converts between Objective-C and C pointers in -fobjc-arc"))
1726 return;
1727
John McCall71c482c2011-06-17 06:50:50 +00001728 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00001729 switch (exprACTC) {
1730 case ACTC_none:
1731 srcKind = (castExprType->isPointerType() ? 1 : 0);
1732 break;
1733 case ACTC_retainable:
1734 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1735 break;
1736 case ACTC_indirectRetainable:
1737 srcKind = 4;
1738 break;
1739 }
1740
1741 if (CCK == CCK_CStyleCast) {
1742 // Check whether this could be fixed with a bridge cast.
1743 SourceLocation AfterLParen = PP.getLocForEndOfToken(castRange.getBegin());
1744 SourceLocation NoteLoc = AfterLParen.isValid()? AfterLParen : loc;
1745
1746 if (castType->isObjCARCBridgableType() &&
1747 castExprType->isCARCBridgableType()) {
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001748 // explicit unbridged casts are allowed if the source of the cast is a
1749 // message sent to an objc method (or property access)
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001750 if (ValidObjCARCNoBridgeCastExpr(castExpr, castType))
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001751 return;
John McCallf85e1932011-06-15 23:02:42 +00001752 Diag(loc, diag::err_arc_cast_requires_bridge)
1753 << 2
1754 << castExprType
1755 << (castType->isBlockPointerType()? 1 : 0)
1756 << castType
1757 << castRange
1758 << castExpr->getSourceRange();
1759 Diag(NoteLoc, diag::note_arc_bridge)
1760 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1761 Diag(NoteLoc, diag::note_arc_bridge_transfer)
1762 << castExprType
1763 << FixItHint::CreateInsertion(AfterLParen, "__bridge_transfer ");
1764
1765 return;
1766 }
1767
1768 if (castType->isCARCBridgableType() &&
1769 castExprType->isObjCARCBridgableType()){
1770 Diag(loc, diag::err_arc_cast_requires_bridge)
1771 << (castExprType->isBlockPointerType()? 1 : 0)
1772 << castExprType
1773 << 2
1774 << castType
1775 << castRange
1776 << castExpr->getSourceRange();
1777
1778 Diag(NoteLoc, diag::note_arc_bridge)
1779 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1780 Diag(NoteLoc, diag::note_arc_bridge_retained)
1781 << castType
1782 << FixItHint::CreateInsertion(AfterLParen, "__bridge_retained ");
1783 return;
1784 }
1785 }
1786
1787 Diag(loc, diag::err_arc_mismatched_cast)
1788 << (CCK != CCK_ImplicitConversion) << srcKind << castExprType << castType
1789 << castRange << castExpr->getSourceRange();
1790}
1791
Fariborz Jahanian7a084ec2011-07-07 23:04:17 +00001792bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType,
1793 QualType exprType) {
1794 QualType canCastType =
1795 Context.getCanonicalType(castType).getUnqualifiedType();
1796 QualType canExprType =
1797 Context.getCanonicalType(exprType).getUnqualifiedType();
1798 if (isa<ObjCObjectPointerType>(canCastType) &&
1799 castType.getObjCLifetime() == Qualifiers::OCL_Weak &&
1800 canExprType->isObjCObjectPointerType()) {
1801 if (const ObjCObjectPointerType *ObjT =
1802 canExprType->getAs<ObjCObjectPointerType>())
1803 if (ObjT->getInterfaceDecl()->isArcWeakrefUnavailable())
1804 return false;
1805 }
1806 return true;
1807}
1808
John McCall7e5e5f42011-07-07 06:58:02 +00001809/// Look for an ObjCReclaimReturnedObject cast and destroy it.
1810static Expr *maybeUndoReclaimObject(Expr *e) {
1811 // For now, we just undo operands that are *immediately* reclaim
1812 // expressions, which prevents the vast majority of potential
1813 // problems here. To catch them all, we'd need to rebuild arbitrary
1814 // value-propagating subexpressions --- we can't reliably rebuild
1815 // in-place because of expression sharing.
1816 if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
1817 if (ice->getCastKind() == CK_ObjCReclaimReturnedObject)
1818 return ice->getSubExpr();
1819
1820 return e;
1821}
1822
John McCallf85e1932011-06-15 23:02:42 +00001823ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
1824 ObjCBridgeCastKind Kind,
1825 SourceLocation BridgeKeywordLoc,
1826 TypeSourceInfo *TSInfo,
1827 Expr *SubExpr) {
John McCall4906cf92011-08-26 00:48:42 +00001828 ExprResult SubResult = UsualUnaryConversions(SubExpr);
1829 if (SubResult.isInvalid()) return ExprError();
1830 SubExpr = SubResult.take();
1831
John McCallf85e1932011-06-15 23:02:42 +00001832 QualType T = TSInfo->getType();
1833 QualType FromType = SubExpr->getType();
1834
1835 bool MustConsume = false;
1836 if (T->isDependentType() || SubExpr->isTypeDependent()) {
1837 // Okay: we'll build a dependent expression type.
1838 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
1839 // Casting CF -> id
1840 switch (Kind) {
1841 case OBC_Bridge:
1842 break;
1843
1844 case OBC_BridgeRetained:
1845 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1846 << 2
1847 << FromType
1848 << (T->isBlockPointerType()? 1 : 0)
1849 << T
1850 << SubExpr->getSourceRange()
1851 << Kind;
1852 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1853 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
1854 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
1855 << FromType
1856 << FixItHint::CreateReplacement(BridgeKeywordLoc,
1857 "__bridge_transfer ");
1858
1859 Kind = OBC_Bridge;
1860 break;
1861
1862 case OBC_BridgeTransfer:
1863 // We must consume the Objective-C object produced by the cast.
1864 MustConsume = true;
1865 break;
1866 }
1867 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
1868 // Okay: id -> CF
1869 switch (Kind) {
1870 case OBC_Bridge:
John McCall7e5e5f42011-07-07 06:58:02 +00001871 // Reclaiming a value that's going to be __bridge-casted to CF
1872 // is very dangerous, so we don't do it.
1873 SubExpr = maybeUndoReclaimObject(SubExpr);
John McCallf85e1932011-06-15 23:02:42 +00001874 break;
1875
1876 case OBC_BridgeRetained:
1877 // Produce the object before casting it.
1878 SubExpr = ImplicitCastExpr::Create(Context, FromType,
1879 CK_ObjCProduceObject,
1880 SubExpr, 0, VK_RValue);
1881 break;
1882
1883 case OBC_BridgeTransfer:
1884 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1885 << (FromType->isBlockPointerType()? 1 : 0)
1886 << FromType
1887 << 2
1888 << T
1889 << SubExpr->getSourceRange()
1890 << Kind;
1891
1892 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1893 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
1894 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
1895 << T
1896 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
1897
1898 Kind = OBC_Bridge;
1899 break;
1900 }
1901 } else {
1902 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
1903 << FromType << T << Kind
1904 << SubExpr->getSourceRange()
1905 << TSInfo->getTypeLoc().getSourceRange();
1906 return ExprError();
1907 }
1908
1909 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind,
1910 BridgeKeywordLoc,
1911 TSInfo, SubExpr);
1912
1913 if (MustConsume) {
1914 ExprNeedsCleanups = true;
1915 Result = ImplicitCastExpr::Create(Context, T, CK_ObjCConsumeObject, Result,
1916 0, VK_RValue);
1917 }
1918
1919 return Result;
1920}
1921
1922ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
1923 SourceLocation LParenLoc,
1924 ObjCBridgeCastKind Kind,
1925 SourceLocation BridgeKeywordLoc,
1926 ParsedType Type,
1927 SourceLocation RParenLoc,
1928 Expr *SubExpr) {
1929 TypeSourceInfo *TSInfo = 0;
1930 QualType T = GetTypeFromParser(Type, &TSInfo);
1931 if (!TSInfo)
1932 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
1933 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
1934 SubExpr);
1935}