blob: 80d3a7451de8d4d90f2162513b2bf87cf734ec1d [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;
45 llvm::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
Chris Lattner39c28bb2009-02-18 06:48:40 +000050 // ObjC strings can't be wide.
Chris Lattnerf4b136f2009-02-18 06:13:04 +000051 if (S->isWide()) {
52 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,
Anders Carlsson3e2193c2011-04-14 00:40:03 +000067 /*Wide=*/false, /*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;
181
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000182 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
183 = ReferencedSelectors.find(Sel);
184 if (Pos == ReferencedSelectors.end())
185 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
186
John McCallf85e1932011-06-15 23:02:42 +0000187 // In ARC, forbid the user from using @selector for
188 // retain/release/autorelease/dealloc/retainCount.
189 if (getLangOptions().ObjCAutoRefCount) {
190 switch (Sel.getMethodFamily()) {
191 case OMF_retain:
192 case OMF_release:
193 case OMF_autorelease:
194 case OMF_retainCount:
195 case OMF_dealloc:
196 Diag(AtLoc, diag::err_arc_illegal_selector) <<
197 Sel << SourceRange(LParenLoc, RParenLoc);
198 break;
199
200 case OMF_None:
201 case OMF_alloc:
202 case OMF_copy:
203 case OMF_init:
204 case OMF_mutableCopy:
205 case OMF_new:
206 case OMF_self:
207 break;
208 }
209 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000210 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000211 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000212}
213
John McCallf312b1e2010-08-26 23:41:50 +0000214ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
215 SourceLocation AtLoc,
216 SourceLocation ProtoLoc,
217 SourceLocation LParenLoc,
218 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000219 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000220 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000221 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000222 return true;
223 }
Mike Stump1eb44332009-09-09 15:08:12 +0000224
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000225 QualType Ty = Context.getObjCProtoType();
226 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000227 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000228 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000229 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000230}
231
John McCall26743b22011-02-03 09:00:02 +0000232/// Try to capture an implicit reference to 'self'.
233ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
234 // Ignore block scopes: we can capture through them.
235 DeclContext *DC = CurContext;
236 while (true) {
237 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
238 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
239 else break;
240 }
241
242 // If we're not in an ObjC method, error out. Note that, unlike the
243 // C++ case, we don't require an instance method --- class methods
244 // still have a 'self', and we really do still need to capture it!
245 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
246 if (!method)
247 return 0;
248
249 ImplicitParamDecl *self = method->getSelfDecl();
250 assert(self && "capturing 'self' in non-definition?");
251
252 // Mark that we're closing on 'this' in all the block scopes, if applicable.
253 for (unsigned idx = FunctionScopes.size() - 1;
254 isa<BlockScopeInfo>(FunctionScopes[idx]);
John McCall6b5a61b2011-02-07 10:33:21 +0000255 --idx) {
256 BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
257 unsigned &captureIndex = blockScope->CaptureMap[self];
258 if (captureIndex) break;
259
260 bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
261 blockScope->Captures.push_back(
262 BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
263 captureIndex = blockScope->Captures.size(); // +1
264 }
John McCall26743b22011-02-03 09:00:02 +0000265
266 return method;
267}
268
Douglas Gregor926df6c2011-06-11 01:09:30 +0000269QualType Sema::getMessageSendResultType(QualType ReceiverType,
270 ObjCMethodDecl *Method,
271 bool isClassMessage, bool isSuperMessage) {
272 assert(Method && "Must have a method");
273 if (!Method->hasRelatedResultType())
274 return Method->getSendResultType();
275
276 // If a method has a related return type:
277 // - if the method found is an instance method, but the message send
278 // was a class message send, T is the declared return type of the method
279 // found
280 if (Method->isInstanceMethod() && isClassMessage)
281 return Method->getSendResultType();
282
283 // - if the receiver is super, T is a pointer to the class of the
284 // enclosing method definition
285 if (isSuperMessage) {
286 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
287 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
288 return Context.getObjCObjectPointerType(
289 Context.getObjCInterfaceType(Class));
290 }
291
292 // - if the receiver is the name of a class U, T is a pointer to U
293 if (ReceiverType->getAs<ObjCInterfaceType>() ||
294 ReceiverType->isObjCQualifiedInterfaceType())
295 return Context.getObjCObjectPointerType(ReceiverType);
296 // - if the receiver is of type Class or qualified Class type,
297 // T is the declared return type of the method.
298 if (ReceiverType->isObjCClassType() ||
299 ReceiverType->isObjCQualifiedClassType())
300 return Method->getSendResultType();
301
302 // - if the receiver is id, qualified id, Class, or qualified Class, T
303 // is the receiver type, otherwise
304 // - T is the type of the receiver expression.
305 return ReceiverType;
306}
John McCall26743b22011-02-03 09:00:02 +0000307
Douglas Gregor926df6c2011-06-11 01:09:30 +0000308void Sema::EmitRelatedResultTypeNote(const Expr *E) {
309 E = E->IgnoreParenImpCasts();
310 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
311 if (!MsgSend)
312 return;
313
314 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
315 if (!Method)
316 return;
317
318 if (!Method->hasRelatedResultType())
319 return;
320
321 if (Context.hasSameUnqualifiedType(Method->getResultType()
322 .getNonReferenceType(),
323 MsgSend->getType()))
324 return;
325
326 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
327 << Method->isInstanceMethod() << Method->getSelector()
328 << MsgSend->getType();
329}
330
331bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
332 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000333 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000334 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000335 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000336 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000337 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000338 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000339 for (unsigned i = 0; i != NumArgs; i++) {
340 if (Args[i]->isTypeDependent())
341 continue;
342
John Wiegley429bb272011-04-08 18:41:53 +0000343 ExprResult Result = DefaultArgumentPromotion(Args[i]);
344 if (Result.isInvalid())
345 return true;
346 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000347 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000348
John McCallf85e1932011-06-15 23:02:42 +0000349 unsigned DiagID;
350 if (getLangOptions().ObjCAutoRefCount)
351 DiagID = diag::err_arc_method_not_found;
352 else
353 DiagID = isClassMessage ? diag::warn_class_method_not_found
354 : diag::warn_inst_method_not_found;
Chris Lattner077bf5e2008-11-24 03:33:13 +0000355 Diag(lbrac, DiagID)
356 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000357 ReturnType = Context.getObjCIdType();
John McCallf89e55a2010-11-18 06:31:45 +0000358 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000359 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000360 }
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Douglas Gregor926df6c2011-06-11 01:09:30 +0000362 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
363 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000364 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000365
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000366 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000367 // Method might have more arguments than selector indicates. This is due
368 // to addition of c-style arguments in method.
369 if (Method->param_size() > Sel.getNumArgs())
370 NumNamedArgs = Method->param_size();
371 // FIXME. This need be cleaned up.
372 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000373 Diag(lbrac, diag::err_typecheck_call_too_few_args)
374 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000375 return false;
376 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000377
Chris Lattner312531a2009-04-12 08:11:20 +0000378 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000379 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000380 // We can't do any type-checking on a type-dependent argument.
381 if (Args[i]->isTypeDependent())
382 continue;
383
Chris Lattner85a932e2008-01-04 22:32:30 +0000384 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000385
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000386 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000387 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000388
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000389 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
390 Param->getType(),
391 PDiag(diag::err_call_incomplete_argument)
392 << argExpr->getSourceRange()))
393 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000394
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000395 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
396 Param);
John McCall3fa5cae2010-10-26 07:05:15 +0000397 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000398 if (ArgE.isInvalid())
399 IsError = true;
400 else
401 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000402 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000403
404 // Promote additional arguments to variadic methods.
405 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000406 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
407 if (Args[i]->isTypeDependent())
408 continue;
409
John Wiegley429bb272011-04-08 18:41:53 +0000410 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
411 IsError |= Arg.isInvalid();
412 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000413 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000414 } else {
415 // Check for extra arguments to non-variadic methods.
416 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000417 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000418 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000419 << 2 /*method*/ << NumNamedArgs << NumArgs
420 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000421 << SourceRange(Args[NumNamedArgs]->getLocStart(),
422 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000423 }
424 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000425 // diagnose nonnull arguments.
426 for (specific_attr_iterator<NonNullAttr>
427 i = Method->specific_attr_begin<NonNullAttr>(),
428 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
429 CheckNonNullArguments(*i, Args, lbrac);
430 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000431
Douglas Gregor2725ca82010-04-21 19:57:20 +0000432 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000433 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000434}
435
John McCallf85e1932011-06-15 23:02:42 +0000436bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000437 // 'self' is objc 'self' in an objc method only.
Fariborz Jahanianb4602102011-03-28 16:23:34 +0000438 DeclContext *DC = CurContext;
439 while (isa<BlockDecl>(DC))
440 DC = DC->getParent();
441 if (DC && !isa<ObjCMethodDecl>(DC))
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000442 return false;
John McCallf85e1932011-06-15 23:02:42 +0000443 receiver = receiver->IgnoreParenLValueCasts();
444 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000445 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
446 return true;
447 return false;
448}
449
Steve Narofff1afaf62009-02-26 15:55:06 +0000450// Helper method for ActOnClassMethod/ActOnInstanceMethod.
451// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000452// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000453// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000454ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000455 ObjCInterfaceDecl *ClassDecl) {
456 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000457 // lookup in class and all superclasses
458 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000459 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000460 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Steve Naroff5609ec02009-03-08 18:56:13 +0000462 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000463 if (!Method)
464 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Steve Naroff5609ec02009-03-08 18:56:13 +0000466 // Before we give up, check if the selector is an instance method.
467 // But only in the root. This matches gcc's behaviour and what the
468 // runtime expects.
469 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000470 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000471 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000472 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000473 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000474 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
475 }
Mike Stump1eb44332009-09-09 15:08:12 +0000476
Steve Naroff5609ec02009-03-08 18:56:13 +0000477 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000478 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000479 return Method;
480}
481
482ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
483 ObjCInterfaceDecl *ClassDecl) {
484 ObjCMethodDecl *Method = 0;
485 while (ClassDecl && !Method) {
486 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000487 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000488 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Steve Naroff5609ec02009-03-08 18:56:13 +0000490 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000491 if (!Method)
492 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000493 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000494 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000495 return Method;
496}
497
Fariborz Jahanian61478062011-03-09 20:18:06 +0000498/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
499/// list of a qualified objective pointer type.
500ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
501 const ObjCObjectPointerType *OPT,
502 bool Instance)
503{
504 ObjCMethodDecl *MD = 0;
505 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
506 E = OPT->qual_end(); I != E; ++I) {
507 ObjCProtocolDecl *PROTO = (*I);
508 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
509 return MD;
510 }
511 }
512 return 0;
513}
514
Chris Lattner7f816522010-04-11 07:45:24 +0000515/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
516/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000517ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000518HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000519 Expr *BaseExpr, SourceLocation OpLoc,
520 DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000521 SourceLocation MemberLoc,
522 SourceLocation SuperLoc, QualType SuperType,
523 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000524 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
525 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000526
527 if (MemberName.getNameKind() != DeclarationName::Identifier) {
528 Diag(MemberLoc, diag::err_invalid_property_name)
529 << MemberName << QualType(OPT, 0);
530 return ExprError();
531 }
532
Chris Lattner7f816522010-04-11 07:45:24 +0000533 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
534
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000535 if (IFace->isForwardDecl()) {
536 Diag(MemberLoc, diag::err_property_not_found_forward_class)
537 << MemberName << QualType(OPT, 0);
538 Diag(IFace->getLocation(), diag::note_forward_class);
539 return ExprError();
540 }
Chris Lattner7f816522010-04-11 07:45:24 +0000541 // Search for a declared property first.
542 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
543 // Check whether we can reference this property.
544 if (DiagnoseUseOfDecl(PD, MemberLoc))
545 return ExprError();
546 QualType ResTy = PD->getType();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000547 ResTy = ResTy.getNonLValueExprType(Context);
Chris Lattner7f816522010-04-11 07:45:24 +0000548 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
549 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000550 if (Getter &&
551 (Getter->hasRelatedResultType()
552 || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
553 ResTy = getMessageSendResultType(QualType(OPT, 0), Getter, false,
554 Super);
555
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000556 if (Super)
557 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000558 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000559 MemberLoc,
560 SuperLoc, SuperType));
561 else
562 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000563 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000564 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000565 }
566 // Check protocols on qualified interfaces.
567 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
568 E = OPT->qual_end(); I != E; ++I)
569 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
570 // Check whether we can reference this property.
571 if (DiagnoseUseOfDecl(PD, MemberLoc))
572 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000573
574 QualType T = PD->getType();
575 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
576 T = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000577 if (Super)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000578 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000579 VK_LValue,
580 OK_ObjCProperty,
581 MemberLoc,
582 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000583 else
Douglas Gregor926df6c2011-06-11 01:09:30 +0000584 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000585 VK_LValue,
586 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000587 MemberLoc,
588 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000589 }
590 // If that failed, look for an "implicit" property by seeing if the nullary
591 // selector is implemented.
592
593 // FIXME: The logic for looking up nullary and unary selectors should be
594 // shared with the code in ActOnInstanceMessage.
595
596 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
597 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000598
599 // May be founf in property's qualified list.
600 if (!Getter)
601 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000602
603 // If this reference is in an @implementation, check for 'private' methods.
604 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000605 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000606
607 // Look through local category implementations associated with the class.
608 if (!Getter)
609 Getter = IFace->getCategoryInstanceMethod(Sel);
610 if (Getter) {
611 // Check if we can reference this property.
612 if (DiagnoseUseOfDecl(Getter, MemberLoc))
613 return ExprError();
614 }
615 // If we found a getter then this may be a valid dot-reference, we
616 // will look for the matching setter, in case it is needed.
617 Selector SetterSel =
618 SelectorTable::constructSetterName(PP.getIdentifierTable(),
619 PP.getSelectorTable(), Member);
620 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000621
622 // May be founf in property's qualified list.
623 if (!Setter)
624 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
625
Chris Lattner7f816522010-04-11 07:45:24 +0000626 if (!Setter) {
627 // If this reference is in an @implementation, also check for 'private'
628 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000629 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000630 }
631 // Look through local category implementations associated with the class.
632 if (!Setter)
633 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000634
Chris Lattner7f816522010-04-11 07:45:24 +0000635 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
636 return ExprError();
637
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000638 if (Getter || Setter) {
639 QualType PType;
640 if (Getter)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000641 PType = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000642 else {
643 ParmVarDecl *ArgDecl = *Setter->param_begin();
644 PType = ArgDecl->getType();
645 }
646
John McCall09431682010-11-18 19:01:18 +0000647 ExprValueKind VK = VK_LValue;
648 ExprObjectKind OK = OK_ObjCProperty;
649 if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
650 PType->isVoidType())
651 VK = VK_RValue, OK = OK_Ordinary;
652
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000653 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000654 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
655 PType, VK, OK,
656 MemberLoc,
657 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000658 else
John McCall12f78a62010-12-02 01:19:52 +0000659 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
660 PType, VK, OK,
661 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000662
Chris Lattner7f816522010-04-11 07:45:24 +0000663 }
664
665 // Attempt to correct for typos in property names.
666 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000667 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
Chris Lattner7f816522010-04-11 07:45:24 +0000668 Res.getAsSingle<ObjCPropertyDecl>()) {
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000669 DeclarationName TypoResult = Res.getLookupName();
Chris Lattner7f816522010-04-11 07:45:24 +0000670 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000671 << MemberName << QualType(OPT, 0) << TypoResult
672 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000673 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
674 Diag(Property->getLocation(), diag::note_previous_decl)
675 << Property->getDeclName();
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000676 return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc,
677 TypoResult, MemberLoc,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000678 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000679 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000680 ObjCInterfaceDecl *ClassDeclared;
681 if (ObjCIvarDecl *Ivar =
682 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
683 QualType T = Ivar->getType();
684 if (const ObjCObjectPointerType * OBJPT =
685 T->getAsObjCInterfacePointerType()) {
686 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
687 if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
688 if (IFace->isForwardDecl()) {
689 Diag(MemberLoc, diag::err_property_not_as_forward_class)
Fariborz Jahanian2a96bf52011-02-17 17:30:05 +0000690 << MemberName << IFace;
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000691 Diag(IFace->getLocation(), diag::note_forward_class);
692 return ExprError();
693 }
694 }
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000695 Diag(MemberLoc,
696 diag::err_ivar_access_using_property_syntax_suggest)
697 << MemberName << QualType(OPT, 0) << Ivar->getDeclName()
698 << FixItHint::CreateReplacement(OpLoc, "->");
699 return ExprError();
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000700 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000701
Chris Lattner7f816522010-04-11 07:45:24 +0000702 Diag(MemberLoc, diag::err_property_not_found)
703 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000704 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000705 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000706 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000707 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000708}
709
710
711
John McCall60d7b3a2010-08-24 06:29:42 +0000712ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000713ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
714 IdentifierInfo &propertyName,
715 SourceLocation receiverNameLoc,
716 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000718 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000719 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
720 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000721
722 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000723 if (IFace == 0) {
724 // If the "receiver" is 'super' in a method, handle it as an expression-like
725 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000726 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000727 IsSuper = true;
728
John McCall26743b22011-02-03 09:00:02 +0000729 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000730 if (CurMethod->isInstanceMethod()) {
731 QualType T =
732 Context.getObjCInterfaceType(CurMethod->getClassInterface());
733 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000734
735 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian6326e052011-06-28 00:00:52 +0000736 /*BaseExpr*/0,
737 SourceLocation()/*OpLoc*/,
738 &propertyName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000739 propertyNameLoc,
740 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000741 }
Mike Stump1eb44332009-09-09 15:08:12 +0000742
Chris Lattnereb483eb2010-04-11 08:28:14 +0000743 // Otherwise, if this is a class method, try dispatching to our
744 // superclass.
745 IFace = CurMethod->getClassInterface()->getSuperClass();
746 }
John McCall26743b22011-02-03 09:00:02 +0000747 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000748
749 if (IFace == 0) {
750 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
751 return ExprError();
752 }
753 }
754
755 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000756 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000757 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000758
759 // If this reference is in an @implementation, check for 'private' methods.
760 if (!Getter)
761 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
762 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000763 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000764 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000765
766 if (Getter) {
767 // FIXME: refactor/share with ActOnMemberReference().
768 // Check if we can reference this property.
769 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
770 return ExprError();
771 }
Mike Stump1eb44332009-09-09 15:08:12 +0000772
Steve Naroff61f72cb2009-03-09 21:12:44 +0000773 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000774 Selector SetterSel =
775 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000776 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000777
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000778 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000779 if (!Setter) {
780 // If this reference is in an @implementation, also check for 'private'
781 // methods.
782 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
783 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000784 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000785 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000786 }
787 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000788 if (!Setter)
789 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000790
791 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
792 return ExprError();
793
794 if (Getter || Setter) {
795 QualType PType;
796
John McCall09431682010-11-18 19:01:18 +0000797 ExprValueKind VK = VK_LValue;
798 if (Getter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000799 PType = getMessageSendResultType(Context.getObjCInterfaceType(IFace),
800 Getter, true,
801 receiverNamePtr->isStr("super"));
John McCall09431682010-11-18 19:01:18 +0000802 if (!getLangOptions().CPlusPlus &&
803 !PType.hasQualifiers() && PType->isVoidType())
804 VK = VK_RValue;
805 } else {
Steve Naroff61f72cb2009-03-09 21:12:44 +0000806 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
807 E = Setter->param_end(); PI != E; ++PI)
808 PType = (*PI)->getType();
John McCall09431682010-11-18 19:01:18 +0000809 VK = VK_LValue;
Steve Naroff61f72cb2009-03-09 21:12:44 +0000810 }
John McCall09431682010-11-18 19:01:18 +0000811
812 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
813
Douglas Gregor926df6c2011-06-11 01:09:30 +0000814 if (IsSuper)
815 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
816 PType, VK, OK,
817 propertyNameLoc,
818 receiverNameLoc,
819 Context.getObjCInterfaceType(IFace)));
820
John McCall12f78a62010-12-02 01:19:52 +0000821 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
822 PType, VK, OK,
823 propertyNameLoc,
824 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000825 }
826 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
827 << &propertyName << Context.getObjCInterfaceType(IFace));
828}
829
Douglas Gregor47bd5432010-04-14 02:46:37 +0000830Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000831 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000832 SourceLocation NameLoc,
833 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000834 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000835 ParsedType &ReceiverType) {
836 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000837
Douglas Gregor47bd5432010-04-14 02:46:37 +0000838 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000839 // messaging super. If the identifier is "super" and there is a
840 // trailing dot, it's an instance message.
841 if (IsSuper && S->isInObjcMethodScope())
842 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000843
844 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
845 LookupName(Result, S);
846
847 switch (Result.getResultKind()) {
848 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000849 // Normal name lookup didn't find anything. If we're in an
850 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000851 // FIXME: This is a hack. Ivar lookup should be part of normal
852 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000853 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
854 ObjCInterfaceDecl *ClassDeclared;
855 if (Method->getClassInterface()->lookupInstanceVariable(Name,
856 ClassDeclared))
857 return ObjCInstanceMessage;
858 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000859
Douglas Gregor47bd5432010-04-14 02:46:37 +0000860 // Break out; we'll perform typo correction below.
861 break;
862
863 case LookupResult::NotFoundInCurrentInstantiation:
864 case LookupResult::FoundOverloaded:
865 case LookupResult::FoundUnresolvedValue:
866 case LookupResult::Ambiguous:
867 Result.suppressDiagnostics();
868 return ObjCInstanceMessage;
869
870 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000871 // If the identifier is a class or not, and there is a trailing dot,
872 // it's an instance message.
873 if (HasTrailingDot)
874 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000875 // We found something. If it's a type, then we have a class
876 // message. Otherwise, it's an instance message.
877 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000878 QualType T;
879 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
880 T = Context.getObjCInterfaceType(Class);
881 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
882 T = Context.getTypeDeclType(Type);
883 else
884 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000885
Douglas Gregor1569f952010-04-21 20:38:13 +0000886 // We have a class message, and T is the type we're
887 // messaging. Build source-location information for it.
888 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000889 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000890 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000891 }
892 }
893
Douglas Gregoraaf87162010-04-14 20:04:41 +0000894 // Determine our typo-correction context.
895 CorrectTypoContext CTC = CTC_Expression;
896 if (ObjCMethodDecl *Method = getCurMethodDecl())
897 if (Method->getClassInterface() &&
898 Method->getClassInterface()->getSuperClass())
899 CTC = CTC_ObjCMessageReceiver;
900
901 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
902 if (Result.isSingleResult()) {
903 // If we found a declaration, correct when it refers to an Objective-C
904 // class.
905 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000906 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000907 Diag(NameLoc, diag::err_unknown_receiver_suggest)
908 << Name << Result.getLookupName()
909 << FixItHint::CreateReplacement(SourceRange(NameLoc),
910 ND->getNameAsString());
911 Diag(ND->getLocation(), diag::note_previous_decl)
912 << Corrected;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000913
Douglas Gregor1569f952010-04-21 20:38:13 +0000914 QualType T = Context.getObjCInterfaceType(Class);
915 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000916 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000917 return ObjCClassMessage;
918 }
919 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
920 Corrected.getAsIdentifierInfo()->isStr("super")) {
921 // If we've found the keyword "super", this is a send to super.
922 Diag(NameLoc, diag::err_unknown_receiver_suggest)
923 << Name << Corrected
924 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000925 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000926 }
927 }
928
929 // Fall back: let the parser try to parse it as an instance message.
930 return ObjCInstanceMessage;
931}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000932
John McCall60d7b3a2010-08-24 06:29:42 +0000933ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000934 SourceLocation SuperLoc,
935 Selector Sel,
936 SourceLocation LBracLoc,
937 SourceLocation SelectorLoc,
938 SourceLocation RBracLoc,
939 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000940 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000941 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000942 if (!Method) {
943 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
944 return ExprError();
945 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000946
Douglas Gregorf95861a2010-04-21 20:01:04 +0000947 ObjCInterfaceDecl *Class = Method->getClassInterface();
948 if (!Class) {
949 Diag(SuperLoc, diag::error_no_super_class_message)
950 << Method->getDeclName();
951 return ExprError();
952 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000953
Douglas Gregorf95861a2010-04-21 20:01:04 +0000954 ObjCInterfaceDecl *Super = Class->getSuperClass();
955 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000956 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000957 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
958 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000959 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000960 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000961
Douglas Gregorf95861a2010-04-21 20:01:04 +0000962 // We are in a method whose class has a superclass, so 'super'
963 // is acting as a keyword.
964 if (Method->isInstanceMethod()) {
965 // Since we are in an instance method, this is an instance
966 // message to the superclass instance.
967 QualType SuperTy = Context.getObjCInterfaceType(Super);
968 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +0000969 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000970 Sel, /*Method=*/0,
971 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000972 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000973
974 // Since we are in a class method, this is a class message to
975 // the superclass.
976 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
977 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000978 SuperLoc, Sel, /*Method=*/0,
979 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000980}
981
982/// \brief Build an Objective-C class message expression.
983///
984/// This routine takes care of both normal class messages and
985/// class messages to the superclass.
986///
987/// \param ReceiverTypeInfo Type source information that describes the
988/// receiver of this message. This may be NULL, in which case we are
989/// sending to the superclass and \p SuperLoc must be a valid source
990/// location.
991
992/// \param ReceiverType The type of the object receiving the
993/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
994/// type as that refers to. For a superclass send, this is the type of
995/// the superclass.
996///
997/// \param SuperLoc The location of the "super" keyword in a
998/// superclass message.
999///
1000/// \param Sel The selector to which the message is being sent.
1001///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001002/// \param Method The method that this class message is invoking, if
1003/// already known.
1004///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001005/// \param LBracLoc The location of the opening square bracket ']'.
1006///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001007/// \param RBrac The location of the closing square bracket ']'.
1008///
1009/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001010ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001011 QualType ReceiverType,
1012 SourceLocation SuperLoc,
1013 Selector Sel,
1014 ObjCMethodDecl *Method,
1015 SourceLocation LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001016 SourceLocation SelectorLoc,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001017 SourceLocation RBracLoc,
1018 MultiExprArg ArgsIn) {
1019 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001020 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001021 if (LBracLoc.isInvalid()) {
1022 Diag(Loc, diag::err_missing_open_square_message_send)
1023 << FixItHint::CreateInsertion(Loc, "[");
1024 LBracLoc = Loc;
1025 }
1026
Douglas Gregor92e986e2010-04-22 16:44:27 +00001027 if (ReceiverType->isDependentType()) {
1028 // If the receiver type is dependent, we can't type-check anything
1029 // at this point. Build a dependent expression.
1030 unsigned NumArgs = ArgsIn.size();
1031 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1032 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001033 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1034 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001035 Sel, SelectorLoc, /*Method=*/0,
Douglas Gregor92e986e2010-04-22 16:44:27 +00001036 Args, NumArgs, RBracLoc));
1037 }
Chris Lattner15faee12010-04-12 05:38:43 +00001038
Douglas Gregor2725ca82010-04-21 19:57:20 +00001039 // Find the class to which we are sending this message.
1040 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001041 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1042 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001043 Diag(Loc, diag::err_invalid_receiver_class_message)
1044 << ReceiverType;
1045 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001046 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001047 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian02b0d652011-03-08 19:12:46 +00001048 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001049 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001050 if (!Method) {
1051 if (Class->isForwardDecl()) {
John McCallf85e1932011-06-15 23:02:42 +00001052 if (getLangOptions().ObjCAutoRefCount) {
1053 Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
1054 } else {
1055 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1056 }
1057
Douglas Gregorf49bb082010-04-22 17:01:48 +00001058 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001059 Method = LookupFactoryMethodInGlobalPool(Sel,
1060 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001061 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001062 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1063 << Method->getDeclName();
1064 }
1065 if (!Method)
1066 Method = Class->lookupClassMethod(Sel);
1067
1068 // If we have an implementation in scope, check "private" methods.
1069 if (!Method)
1070 Method = LookupPrivateClassMethod(Sel, Class);
1071
1072 if (Method && DiagnoseUseOfDecl(Method, Loc))
1073 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001074 }
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Douglas Gregor2725ca82010-04-21 19:57:20 +00001076 // Check the argument types and determine the result type.
1077 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001078 ExprValueKind VK = VK_RValue;
1079
Douglas Gregor2725ca82010-04-21 19:57:20 +00001080 unsigned NumArgs = ArgsIn.size();
1081 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001082 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1083 SuperLoc.isValid(), LBracLoc, RBracLoc,
1084 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001085 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001086
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001087 if (Method && !Method->getResultType()->isVoidType() &&
1088 RequireCompleteType(LBracLoc, Method->getResultType(),
1089 diag::err_illegal_message_expr_incomplete_type))
1090 return ExprError();
1091
Douglas Gregor2725ca82010-04-21 19:57:20 +00001092 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001093 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001094 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001095 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001096 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001097 ReceiverType, Sel, SelectorLoc,
1098 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001099 else
John McCallf89e55a2010-11-18 06:31:45 +00001100 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001101 ReceiverTypeInfo, Sel, SelectorLoc,
1102 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001103 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001104}
1105
Douglas Gregor2725ca82010-04-21 19:57:20 +00001106// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001107// ArgExprs is optional - if it is present, the number of expressions
1108// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001109ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001110 ParsedType Receiver,
1111 Selector Sel,
1112 SourceLocation LBracLoc,
1113 SourceLocation SelectorLoc,
1114 SourceLocation RBracLoc,
1115 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001116 TypeSourceInfo *ReceiverTypeInfo;
1117 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1118 if (ReceiverType.isNull())
1119 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001120
Mike Stump1eb44332009-09-09 15:08:12 +00001121
Douglas Gregor2725ca82010-04-21 19:57:20 +00001122 if (!ReceiverTypeInfo)
1123 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1124
1125 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001126 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001127 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001128}
1129
1130/// \brief Build an Objective-C instance message expression.
1131///
1132/// This routine takes care of both normal instance messages and
1133/// instance messages to the superclass instance.
1134///
1135/// \param Receiver The expression that computes the object that will
1136/// receive this message. This may be empty, in which case we are
1137/// sending to the superclass instance and \p SuperLoc must be a valid
1138/// source location.
1139///
1140/// \param ReceiverType The (static) type of the object receiving the
1141/// message. When a \p Receiver expression is provided, this is the
1142/// same type as that expression. For a superclass instance send, this
1143/// is a pointer to the type of the superclass.
1144///
1145/// \param SuperLoc The location of the "super" keyword in a
1146/// superclass instance message.
1147///
1148/// \param Sel The selector to which the message is being sent.
1149///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001150/// \param Method The method that this instance message is invoking, if
1151/// already known.
1152///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001153/// \param LBracLoc The location of the opening square bracket ']'.
1154///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001155/// \param RBrac The location of the closing square bracket ']'.
1156///
1157/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001158ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001159 QualType ReceiverType,
1160 SourceLocation SuperLoc,
1161 Selector Sel,
1162 ObjCMethodDecl *Method,
1163 SourceLocation LBracLoc,
1164 SourceLocation SelectorLoc,
1165 SourceLocation RBracLoc,
1166 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001167 // The location of the receiver.
1168 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1169
1170 if (LBracLoc.isInvalid()) {
1171 Diag(Loc, diag::err_missing_open_square_message_send)
1172 << FixItHint::CreateInsertion(Loc, "[");
1173 LBracLoc = Loc;
1174 }
1175
Douglas Gregor2725ca82010-04-21 19:57:20 +00001176 // If we have a receiver expression, perform appropriate promotions
1177 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001178 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001179 if (Receiver->isTypeDependent()) {
1180 // If the receiver is type-dependent, we can't type-check anything
1181 // at this point. Build a dependent expression.
1182 unsigned NumArgs = ArgsIn.size();
1183 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1184 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1185 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001186 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001187 SelectorLoc, /*Method=*/0,
1188 Args, NumArgs, RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001189 }
1190
Douglas Gregor2725ca82010-04-21 19:57:20 +00001191 // If necessary, apply function/array conversion to the receiver.
1192 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001193 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1194 if (Result.isInvalid())
1195 return ExprError();
1196 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001197 ReceiverType = Receiver->getType();
1198 }
1199
Douglas Gregorf49bb082010-04-22 17:01:48 +00001200 if (!Method) {
1201 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001202 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001203 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001204 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1205 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001206 SourceRange(LBracLoc, RBracLoc),
1207 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001208 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001209 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001210 SourceRange(LBracLoc, RBracLoc),
1211 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001212 } else if (ReceiverType->isObjCClassType() ||
1213 ReceiverType->isObjCQualifiedClassType()) {
1214 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001215 // We allow sending a message to a qualified Class ("Class<foo>"), which
1216 // is ok as long as one of the protocols implements the selector (if not, warn).
1217 if (const ObjCObjectPointerType *QClassTy
1218 = ReceiverType->getAsObjCQualifiedClassType()) {
1219 // Search protocols for class methods.
1220 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1221 if (!Method) {
1222 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1223 // warn if instance method found for a Class message.
1224 if (Method) {
1225 Diag(Loc, diag::warn_instance_method_on_class_found)
1226 << Method->getSelector() << Sel;
1227 Diag(Method->getLocation(), diag::note_method_declared_at);
1228 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001229 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001230 } else {
1231 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1232 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1233 // First check the public methods in the class interface.
1234 Method = ClassDecl->lookupClassMethod(Sel);
1235
1236 if (!Method)
1237 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1238 }
1239 if (Method && DiagnoseUseOfDecl(Method, Loc))
1240 return ExprError();
1241 }
1242 if (!Method) {
1243 // If not messaging 'self', look for any factory method named 'Sel'.
1244 if (!Receiver || !isSelfExpr(Receiver)) {
1245 Method = LookupFactoryMethodInGlobalPool(Sel,
1246 SourceRange(LBracLoc, RBracLoc),
1247 true);
1248 if (!Method) {
1249 // If no class (factory) method was found, check if an _instance_
1250 // method of the same name exists in the root class only.
1251 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001252 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001253 true);
1254 if (Method)
1255 if (const ObjCInterfaceDecl *ID =
1256 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1257 if (ID->getSuperClass())
1258 Diag(Loc, diag::warn_root_inst_method_not_found)
1259 << Sel << SourceRange(LBracLoc, RBracLoc);
1260 }
1261 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001262 }
1263 }
1264 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001265 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001266 ObjCInterfaceDecl* ClassDecl = 0;
1267
1268 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1269 // long as one of the protocols implements the selector (if not, warn).
1270 if (const ObjCObjectPointerType *QIdTy
1271 = ReceiverType->getAsObjCQualifiedIdType()) {
1272 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001273 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1274 if (!Method)
1275 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001276 } else if (const ObjCObjectPointerType *OCIType
1277 = ReceiverType->getAsObjCInterfacePointerType()) {
1278 // We allow sending a message to a pointer to an interface (an object).
1279 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001280
1281 if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCount) {
1282 Diag(Loc, diag::err_arc_receiver_forward_instance)
1283 << OCIType->getPointeeType()
1284 << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperLoc));
1285 return ExprError();
1286 }
1287
Douglas Gregorf49bb082010-04-22 17:01:48 +00001288 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1289 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +00001290 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001291 Method = ClassDecl->lookupInstanceMethod(Sel);
1292
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001293 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001294 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001295 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1296
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001297 const ObjCInterfaceDecl *forwardClass = 0;
Douglas Gregorf49bb082010-04-22 17:01:48 +00001298 if (!Method) {
1299 // If we have implementations in scope, check "private" methods.
1300 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1301
John McCallf85e1932011-06-15 23:02:42 +00001302 if (!Method && getLangOptions().ObjCAutoRefCount) {
1303 Diag(Loc, diag::err_arc_may_not_respond)
1304 << OCIType->getPointeeType() << Sel;
1305 return ExprError();
1306 }
1307
Douglas Gregorf49bb082010-04-22 17:01:48 +00001308 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1309 // If we still haven't found a method, look in the global pool. This
1310 // behavior isn't very desirable, however we need it for GCC
1311 // compatibility. FIXME: should we deviate??
1312 if (OCIType->qual_empty()) {
1313 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001314 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001315 if (OCIType->getInterfaceDecl()->isForwardDecl())
1316 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001317 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001318 Diag(Loc, diag::warn_maynot_respond)
1319 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1320 }
1321 }
1322 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001323 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001324 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001325 } else if (!getLangOptions().ObjCAutoRefCount &&
1326 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001327 (ReceiverType->isPointerType() ||
1328 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001329 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001330 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001331 Diag(Loc, diag::warn_bad_receiver_type)
1332 << ReceiverType
1333 << Receiver->getSourceRange();
1334 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001335 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1336 CK_BitCast).take();
John McCall404cd162010-11-13 01:35:44 +00001337 else {
1338 // TODO: specialized warning on null receivers?
1339 bool IsNull = Receiver->isNullPointerConstant(Context,
1340 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001341 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1342 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001343 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001344 ReceiverType = Receiver->getType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00001345 }
John Wiegley429bb272011-04-08 18:41:53 +00001346 else {
1347 ExprResult ReceiverRes;
1348 if (getLangOptions().CPlusPlus)
1349 ReceiverRes = PerformContextuallyConvertToObjCId(Receiver);
1350 if (ReceiverRes.isUsable()) {
1351 Receiver = ReceiverRes.take();
1352 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
1353 Receiver = ICE->getSubExpr();
1354 ReceiverType = Receiver->getType();
1355 }
1356 return BuildInstanceMessage(Receiver,
1357 ReceiverType,
1358 SuperLoc,
1359 Sel,
1360 Method,
1361 LBracLoc,
1362 SelectorLoc,
1363 RBracLoc,
1364 move(ArgsIn));
1365 } else {
1366 // Reject other random receiver types (e.g. structs).
1367 Diag(Loc, diag::err_bad_receiver_type)
1368 << ReceiverType << Receiver->getSourceRange();
1369 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001370 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001371 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001372 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001373 }
Mike Stump1eb44332009-09-09 15:08:12 +00001374
Douglas Gregor2725ca82010-04-21 19:57:20 +00001375 // Check the message arguments.
1376 unsigned NumArgs = ArgsIn.size();
1377 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1378 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001379 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001380 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1381 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001382 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1383 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001384 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001385 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001386
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001387 if (Method && !Method->getResultType()->isVoidType() &&
1388 RequireCompleteType(LBracLoc, Method->getResultType(),
1389 diag::err_illegal_message_expr_incomplete_type))
1390 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001391
John McCallf85e1932011-06-15 23:02:42 +00001392 // In ARC, forbid the user from sending messages to
1393 // retain/release/autorelease/dealloc/retainCount explicitly.
1394 if (getLangOptions().ObjCAutoRefCount) {
1395 ObjCMethodFamily family =
1396 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1397 switch (family) {
1398 case OMF_init:
1399 if (Method)
1400 checkInitMethod(Method, ReceiverType);
1401
1402 case OMF_None:
1403 case OMF_alloc:
1404 case OMF_copy:
1405 case OMF_mutableCopy:
1406 case OMF_new:
1407 case OMF_self:
1408 break;
1409
1410 case OMF_dealloc:
1411 case OMF_retain:
1412 case OMF_release:
1413 case OMF_autorelease:
1414 case OMF_retainCount:
1415 Diag(Loc, diag::err_arc_illegal_explicit_message)
1416 << Sel << SelectorLoc;
1417 break;
1418 }
1419 }
1420
Douglas Gregor2725ca82010-04-21 19:57:20 +00001421 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001422 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001423 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001424 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001425 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001426 ReceiverType, Sel, SelectorLoc, Method,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001427 Args, NumArgs, RBracLoc);
1428 else
John McCallf89e55a2010-11-18 06:31:45 +00001429 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001430 Receiver, Sel, SelectorLoc, Method,
1431 Args, NumArgs, RBracLoc);
John McCallf85e1932011-06-15 23:02:42 +00001432
1433 if (getLangOptions().ObjCAutoRefCount) {
1434 // In ARC, annotate delegate init calls.
1435 if (Result->getMethodFamily() == OMF_init &&
1436 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
1437 // Only consider init calls *directly* in init implementations,
1438 // not within blocks.
1439 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1440 if (method && method->getMethodFamily() == OMF_init) {
1441 // The implicit assignment to self means we also don't want to
1442 // consume the result.
1443 Result->setDelegateInitCall(true);
1444 return Owned(Result);
1445 }
1446 }
1447
1448 // In ARC, check for message sends which are likely to introduce
1449 // retain cycles.
1450 checkRetainCycles(Result);
1451 }
1452
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001453 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001454}
1455
1456// ActOnInstanceMessage - used for both unary and keyword messages.
1457// ArgExprs is optional - if it is present, the number of expressions
1458// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001459ExprResult Sema::ActOnInstanceMessage(Scope *S,
1460 Expr *Receiver,
1461 Selector Sel,
1462 SourceLocation LBracLoc,
1463 SourceLocation SelectorLoc,
1464 SourceLocation RBracLoc,
1465 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001466 if (!Receiver)
1467 return ExprError();
1468
John McCall9ae2f072010-08-23 23:25:46 +00001469 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001470 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001471 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001472}
Chris Lattnereca7be62008-04-07 05:30:13 +00001473
John McCallf85e1932011-06-15 23:02:42 +00001474enum ARCConversionTypeClass {
1475 ACTC_none,
1476 ACTC_retainable,
1477 ACTC_indirectRetainable
1478};
1479static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
1480 ARCConversionTypeClass ACTC = ACTC_retainable;
1481
1482 // Ignore an outermost reference type.
1483 if (const ReferenceType *ref = type->getAs<ReferenceType>())
1484 type = ref->getPointeeType();
1485
1486 // Drill through pointers and arrays recursively.
1487 while (true) {
1488 if (const PointerType *ptr = type->getAs<PointerType>()) {
1489 type = ptr->getPointeeType();
1490 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1491 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1492 } else {
1493 break;
1494 }
1495 ACTC = ACTC_indirectRetainable;
1496 }
1497
1498 if (!type->isObjCRetainableType()) return ACTC_none;
1499 return ACTC;
1500}
1501
1502namespace {
1503 /// Return true if the given expression can be reasonably converted
1504 /// between a retainable pointer type and a C pointer type.
1505 struct ARCCastChecker : StmtVisitor<ARCCastChecker, bool> {
1506 ASTContext &Context;
1507 ARCCastChecker(ASTContext &Context) : Context(Context) {}
1508 bool VisitStmt(Stmt *s) {
1509 return false;
1510 }
1511 bool VisitExpr(Expr *e) {
1512 return e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
1513 }
1514
1515 bool VisitParenExpr(ParenExpr *e) {
1516 return Visit(e->getSubExpr());
1517 }
1518 bool VisitCastExpr(CastExpr *e) {
1519 switch (e->getCastKind()) {
1520 case CK_NullToPointer:
1521 return true;
1522 case CK_NoOp:
1523 case CK_LValueToRValue:
1524 case CK_BitCast:
1525 case CK_AnyPointerToObjCPointerCast:
1526 case CK_AnyPointerToBlockPointerCast:
1527 return Visit(e->getSubExpr());
1528 default:
1529 return false;
1530 }
1531 }
1532 bool VisitUnaryExtension(UnaryOperator *e) {
1533 return Visit(e->getSubExpr());
1534 }
1535 bool VisitBinComma(BinaryOperator *e) {
1536 return Visit(e->getRHS());
1537 }
1538 bool VisitConditionalOperator(ConditionalOperator *e) {
1539 // Conditional operators are okay if both sides are okay.
1540 return Visit(e->getTrueExpr()) && Visit(e->getFalseExpr());
1541 }
1542 bool VisitObjCStringLiteral(ObjCStringLiteral *e) {
1543 // Always white-list Objective-C string literals.
1544 return true;
1545 }
1546 bool VisitStmtExpr(StmtExpr *e) {
1547 return Visit(e->getSubStmt()->body_back());
1548 }
1549 bool VisitDeclRefExpr(DeclRefExpr *e) {
1550 // White-list references to global extern strings from system
1551 // headers.
1552 if (VarDecl *var = dyn_cast<VarDecl>(e->getDecl()))
1553 if (var->getStorageClass() == SC_Extern &&
1554 var->getType().isConstQualified() &&
1555 Context.getSourceManager().isInSystemHeader(var->getLocation()))
1556 return true;
1557 return false;
1558 }
1559 };
1560}
1561
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001562bool
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001563Sema::ValidObjCARCNoBridgeCastExpr(Expr *&Exp, QualType castType) {
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001564 Expr *NewExp = Exp->IgnoreParenCasts();
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001565
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001566 if (!isa<ObjCMessageExpr>(NewExp) && !isa<ObjCPropertyRefExpr>(NewExp)
1567 && !isa<CallExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001568 return false;
1569 ObjCMethodDecl *method = 0;
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001570 bool MethodReturnsPlusOne = false;
1571
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001572 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(NewExp)) {
1573 method = PRE->getExplicitProperty()->getGetterMethodDecl();
1574 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001575 else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(NewExp))
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001576 method = ME->getMethodDecl();
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001577 else {
1578 CallExpr *CE = cast<CallExpr>(NewExp);
1579 Decl *CallDecl = CE->getCalleeDecl();
1580 if (!CallDecl)
1581 return false;
1582 if (CallDecl->hasAttr<CFReturnsNotRetainedAttr>())
1583 return true;
1584 MethodReturnsPlusOne = CallDecl->hasAttr<CFReturnsRetainedAttr>();
1585 if (!MethodReturnsPlusOne) {
1586 if (NamedDecl *ND = dyn_cast<NamedDecl>(CallDecl))
1587 if (const IdentifierInfo *Id = ND->getIdentifier())
1588 if (Id->isStr("__builtin___CFStringMakeConstantString"))
1589 return true;
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001590 }
1591 }
Fariborz Jahanianc8505ad2011-06-21 19:42:38 +00001592
1593 if (!MethodReturnsPlusOne) {
1594 if (!method)
1595 return false;
1596 if (method->hasAttr<CFReturnsNotRetainedAttr>())
1597 return true;
1598 MethodReturnsPlusOne = method->hasAttr<CFReturnsRetainedAttr>();
1599 if (!MethodReturnsPlusOne) {
1600 ObjCMethodFamily family = method->getSelector().getMethodFamily();
1601 switch (family) {
1602 case OMF_alloc:
1603 case OMF_copy:
1604 case OMF_mutableCopy:
1605 case OMF_new:
1606 MethodReturnsPlusOne = true;
1607 break;
1608 default:
1609 break;
1610 }
1611 }
1612 }
1613
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001614 if (MethodReturnsPlusOne) {
1615 TypeSourceInfo *TSInfo =
1616 Context.getTrivialTypeSourceInfo(castType, SourceLocation());
1617 ExprResult ExpRes = BuildObjCBridgedCast(SourceLocation(), OBC_BridgeTransfer,
1618 SourceLocation(), TSInfo, Exp);
1619 Exp = ExpRes.take();
1620 }
1621 return true;
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001622}
1623
John McCallf85e1932011-06-15 23:02:42 +00001624void
1625Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001626 Expr *&castExpr, CheckedConversionKind CCK) {
John McCallf85e1932011-06-15 23:02:42 +00001627 QualType castExprType = castExpr->getType();
1628
1629 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1630 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
1631 if (exprACTC == castACTC) return;
Fariborz Jahanian8295b7b2011-06-22 16:36:45 +00001632 if (exprACTC && castType->isIntegralType(Context)) return;
John McCallf85e1932011-06-15 23:02:42 +00001633
1634 // Allow casts between pointers to lifetime types (e.g., __strong id*)
1635 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1636 // must be explicit.
1637 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
1638 if (const PointerType *CastExprPtr = castExprType->getAs<PointerType>()) {
1639 QualType CastPointee = CastPtr->getPointeeType();
1640 QualType CastExprPointee = CastExprPtr->getPointeeType();
1641 if ((CCK != CCK_ImplicitConversion &&
1642 CastPointee->isObjCIndirectLifetimeType() &&
1643 CastExprPointee->isVoidType()) ||
1644 (CastPointee->isVoidType() &&
1645 CastExprPointee->isObjCIndirectLifetimeType()))
1646 return;
1647 }
1648 }
1649
1650 if (ARCCastChecker(Context).Visit(castExpr))
1651 return;
1652
1653 SourceLocation loc =
1654 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
1655
1656 if (makeUnavailableInSystemHeader(loc,
1657 "converts between Objective-C and C pointers in -fobjc-arc"))
1658 return;
1659
John McCall71c482c2011-06-17 06:50:50 +00001660 unsigned srcKind = 0;
John McCallf85e1932011-06-15 23:02:42 +00001661 switch (exprACTC) {
1662 case ACTC_none:
1663 srcKind = (castExprType->isPointerType() ? 1 : 0);
1664 break;
1665 case ACTC_retainable:
1666 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1667 break;
1668 case ACTC_indirectRetainable:
1669 srcKind = 4;
1670 break;
1671 }
1672
1673 if (CCK == CCK_CStyleCast) {
1674 // Check whether this could be fixed with a bridge cast.
1675 SourceLocation AfterLParen = PP.getLocForEndOfToken(castRange.getBegin());
1676 SourceLocation NoteLoc = AfterLParen.isValid()? AfterLParen : loc;
1677
1678 if (castType->isObjCARCBridgableType() &&
1679 castExprType->isCARCBridgableType()) {
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001680 // explicit unbridged casts are allowed if the source of the cast is a
1681 // message sent to an objc method (or property access)
Fariborz Jahanianaf975172011-06-21 17:38:29 +00001682 if (ValidObjCARCNoBridgeCastExpr(castExpr, castType))
Fariborz Jahanian1522a7c2011-06-20 20:54:42 +00001683 return;
John McCallf85e1932011-06-15 23:02:42 +00001684 Diag(loc, diag::err_arc_cast_requires_bridge)
1685 << 2
1686 << castExprType
1687 << (castType->isBlockPointerType()? 1 : 0)
1688 << castType
1689 << castRange
1690 << castExpr->getSourceRange();
1691 Diag(NoteLoc, diag::note_arc_bridge)
1692 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1693 Diag(NoteLoc, diag::note_arc_bridge_transfer)
1694 << castExprType
1695 << FixItHint::CreateInsertion(AfterLParen, "__bridge_transfer ");
1696
1697 return;
1698 }
1699
1700 if (castType->isCARCBridgableType() &&
1701 castExprType->isObjCARCBridgableType()){
1702 Diag(loc, diag::err_arc_cast_requires_bridge)
1703 << (castExprType->isBlockPointerType()? 1 : 0)
1704 << castExprType
1705 << 2
1706 << castType
1707 << castRange
1708 << castExpr->getSourceRange();
1709
1710 Diag(NoteLoc, diag::note_arc_bridge)
1711 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1712 Diag(NoteLoc, diag::note_arc_bridge_retained)
1713 << castType
1714 << FixItHint::CreateInsertion(AfterLParen, "__bridge_retained ");
1715 return;
1716 }
1717 }
1718
1719 Diag(loc, diag::err_arc_mismatched_cast)
1720 << (CCK != CCK_ImplicitConversion) << srcKind << castExprType << castType
1721 << castRange << castExpr->getSourceRange();
1722}
1723
1724ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
1725 ObjCBridgeCastKind Kind,
1726 SourceLocation BridgeKeywordLoc,
1727 TypeSourceInfo *TSInfo,
1728 Expr *SubExpr) {
1729 QualType T = TSInfo->getType();
1730 QualType FromType = SubExpr->getType();
1731
1732 bool MustConsume = false;
1733 if (T->isDependentType() || SubExpr->isTypeDependent()) {
1734 // Okay: we'll build a dependent expression type.
1735 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
1736 // Casting CF -> id
1737 switch (Kind) {
1738 case OBC_Bridge:
1739 break;
1740
1741 case OBC_BridgeRetained:
1742 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1743 << 2
1744 << FromType
1745 << (T->isBlockPointerType()? 1 : 0)
1746 << T
1747 << SubExpr->getSourceRange()
1748 << Kind;
1749 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1750 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
1751 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
1752 << FromType
1753 << FixItHint::CreateReplacement(BridgeKeywordLoc,
1754 "__bridge_transfer ");
1755
1756 Kind = OBC_Bridge;
1757 break;
1758
1759 case OBC_BridgeTransfer:
1760 // We must consume the Objective-C object produced by the cast.
1761 MustConsume = true;
1762 break;
1763 }
1764 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
1765 // Okay: id -> CF
1766 switch (Kind) {
1767 case OBC_Bridge:
1768 break;
1769
1770 case OBC_BridgeRetained:
1771 // Produce the object before casting it.
1772 SubExpr = ImplicitCastExpr::Create(Context, FromType,
1773 CK_ObjCProduceObject,
1774 SubExpr, 0, VK_RValue);
1775 break;
1776
1777 case OBC_BridgeTransfer:
1778 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1779 << (FromType->isBlockPointerType()? 1 : 0)
1780 << FromType
1781 << 2
1782 << T
1783 << SubExpr->getSourceRange()
1784 << Kind;
1785
1786 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1787 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
1788 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
1789 << T
1790 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
1791
1792 Kind = OBC_Bridge;
1793 break;
1794 }
1795 } else {
1796 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
1797 << FromType << T << Kind
1798 << SubExpr->getSourceRange()
1799 << TSInfo->getTypeLoc().getSourceRange();
1800 return ExprError();
1801 }
1802
1803 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind,
1804 BridgeKeywordLoc,
1805 TSInfo, SubExpr);
1806
1807 if (MustConsume) {
1808 ExprNeedsCleanups = true;
1809 Result = ImplicitCastExpr::Create(Context, T, CK_ObjCConsumeObject, Result,
1810 0, VK_RValue);
1811 }
1812
1813 return Result;
1814}
1815
1816ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
1817 SourceLocation LParenLoc,
1818 ObjCBridgeCastKind Kind,
1819 SourceLocation BridgeKeywordLoc,
1820 ParsedType Type,
1821 SourceLocation RParenLoc,
1822 Expr *SubExpr) {
1823 TypeSourceInfo *TSInfo = 0;
1824 QualType T = GetTypeFromParser(Type, &TSInfo);
1825 if (!TSInfo)
1826 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
1827 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
1828 SubExpr);
1829}