blob: 1d1f6aeb34880ad7e88ef1c5411dea4fad70695e [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.
Anders Carlsson3e2193c2011-04-14 00:40:03 +000066 S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(),
67 /*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 {
Argyrios Kyrtzidis3b5904b2011-05-14 20:32:39 +0000131 if (!EncodedType->getAsArrayTypeUnsafe()) // Incomplete array is handled.
132 if (RequireCompleteType(AtLoc, EncodedType,
133 PDiag(diag::err_incomplete_type_objc_at_encode)
134 << EncodedTypeInfo->getTypeLoc().getSourceRange()))
135 return ExprError();
136
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000137 std::string Str;
138 Context.getObjCEncodingForType(EncodedType, Str);
139
140 // The type of @encode is the same as the type of the corresponding string,
141 // which is an array type.
142 StrTy = Context.CharTy;
143 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000144 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000145 StrTy.addConst();
146 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
147 ArrayType::Normal, 0);
148 }
Mike Stump1eb44332009-09-09 15:08:12 +0000149
Douglas Gregor81d34662010-04-20 15:39:42 +0000150 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000151}
152
John McCallf312b1e2010-08-26 23:41:50 +0000153ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
154 SourceLocation EncodeLoc,
155 SourceLocation LParenLoc,
156 ParsedType ty,
157 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000158 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000159 TypeSourceInfo *TInfo;
160 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
161 if (!TInfo)
162 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
163 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000164
Douglas Gregor81d34662010-04-20 15:39:42 +0000165 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000166}
167
John McCallf312b1e2010-08-26 23:41:50 +0000168ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
169 SourceLocation AtLoc,
170 SourceLocation SelLoc,
171 SourceLocation LParenLoc,
172 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000173 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +0000174 SourceRange(LParenLoc, RParenLoc), false, false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000175 if (!Method)
176 Method = LookupFactoryMethodInGlobalPool(Sel,
177 SourceRange(LParenLoc, RParenLoc));
178 if (!Method)
179 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
180
Fariborz Jahanian3fe10412010-07-22 18:24:20 +0000181 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
182 = ReferencedSelectors.find(Sel);
183 if (Pos == ReferencedSelectors.end())
184 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
185
John McCallf85e1932011-06-15 23:02:42 +0000186 // In ARC, forbid the user from using @selector for
187 // retain/release/autorelease/dealloc/retainCount.
188 if (getLangOptions().ObjCAutoRefCount) {
189 switch (Sel.getMethodFamily()) {
190 case OMF_retain:
191 case OMF_release:
192 case OMF_autorelease:
193 case OMF_retainCount:
194 case OMF_dealloc:
195 Diag(AtLoc, diag::err_arc_illegal_selector) <<
196 Sel << SourceRange(LParenLoc, RParenLoc);
197 break;
198
199 case OMF_None:
200 case OMF_alloc:
201 case OMF_copy:
202 case OMF_init:
203 case OMF_mutableCopy:
204 case OMF_new:
205 case OMF_self:
206 break;
207 }
208 }
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000209 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000210 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000211}
212
John McCallf312b1e2010-08-26 23:41:50 +0000213ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
214 SourceLocation AtLoc,
215 SourceLocation ProtoLoc,
216 SourceLocation LParenLoc,
217 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000218 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000219 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000220 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000221 return true;
222 }
Mike Stump1eb44332009-09-09 15:08:12 +0000223
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000224 QualType Ty = Context.getObjCProtoType();
225 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000226 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000227 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000228 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000229}
230
John McCall26743b22011-02-03 09:00:02 +0000231/// Try to capture an implicit reference to 'self'.
232ObjCMethodDecl *Sema::tryCaptureObjCSelf() {
233 // Ignore block scopes: we can capture through them.
234 DeclContext *DC = CurContext;
235 while (true) {
236 if (isa<BlockDecl>(DC)) DC = cast<BlockDecl>(DC)->getDeclContext();
237 else if (isa<EnumDecl>(DC)) DC = cast<EnumDecl>(DC)->getDeclContext();
238 else break;
239 }
240
241 // If we're not in an ObjC method, error out. Note that, unlike the
242 // C++ case, we don't require an instance method --- class methods
243 // still have a 'self', and we really do still need to capture it!
244 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC);
245 if (!method)
246 return 0;
247
248 ImplicitParamDecl *self = method->getSelfDecl();
249 assert(self && "capturing 'self' in non-definition?");
250
251 // Mark that we're closing on 'this' in all the block scopes, if applicable.
252 for (unsigned idx = FunctionScopes.size() - 1;
253 isa<BlockScopeInfo>(FunctionScopes[idx]);
John McCall6b5a61b2011-02-07 10:33:21 +0000254 --idx) {
255 BlockScopeInfo *blockScope = cast<BlockScopeInfo>(FunctionScopes[idx]);
256 unsigned &captureIndex = blockScope->CaptureMap[self];
257 if (captureIndex) break;
258
259 bool nested = isa<BlockScopeInfo>(FunctionScopes[idx-1]);
260 blockScope->Captures.push_back(
261 BlockDecl::Capture(self, /*byref*/ false, nested, /*copy*/ 0));
262 captureIndex = blockScope->Captures.size(); // +1
263 }
John McCall26743b22011-02-03 09:00:02 +0000264
265 return method;
266}
267
Douglas Gregor926df6c2011-06-11 01:09:30 +0000268QualType Sema::getMessageSendResultType(QualType ReceiverType,
269 ObjCMethodDecl *Method,
270 bool isClassMessage, bool isSuperMessage) {
271 assert(Method && "Must have a method");
272 if (!Method->hasRelatedResultType())
273 return Method->getSendResultType();
274
275 // If a method has a related return type:
276 // - if the method found is an instance method, but the message send
277 // was a class message send, T is the declared return type of the method
278 // found
279 if (Method->isInstanceMethod() && isClassMessage)
280 return Method->getSendResultType();
281
282 // - if the receiver is super, T is a pointer to the class of the
283 // enclosing method definition
284 if (isSuperMessage) {
285 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
286 if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface())
287 return Context.getObjCObjectPointerType(
288 Context.getObjCInterfaceType(Class));
289 }
290
291 // - if the receiver is the name of a class U, T is a pointer to U
292 if (ReceiverType->getAs<ObjCInterfaceType>() ||
293 ReceiverType->isObjCQualifiedInterfaceType())
294 return Context.getObjCObjectPointerType(ReceiverType);
295 // - if the receiver is of type Class or qualified Class type,
296 // T is the declared return type of the method.
297 if (ReceiverType->isObjCClassType() ||
298 ReceiverType->isObjCQualifiedClassType())
299 return Method->getSendResultType();
300
301 // - if the receiver is id, qualified id, Class, or qualified Class, T
302 // is the receiver type, otherwise
303 // - T is the type of the receiver expression.
304 return ReceiverType;
305}
John McCall26743b22011-02-03 09:00:02 +0000306
Douglas Gregor926df6c2011-06-11 01:09:30 +0000307void Sema::EmitRelatedResultTypeNote(const Expr *E) {
308 E = E->IgnoreParenImpCasts();
309 const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E);
310 if (!MsgSend)
311 return;
312
313 const ObjCMethodDecl *Method = MsgSend->getMethodDecl();
314 if (!Method)
315 return;
316
317 if (!Method->hasRelatedResultType())
318 return;
319
320 if (Context.hasSameUnqualifiedType(Method->getResultType()
321 .getNonReferenceType(),
322 MsgSend->getType()))
323 return;
324
325 Diag(Method->getLocation(), diag::note_related_result_type_inferred)
326 << Method->isInstanceMethod() << Method->getSelector()
327 << MsgSend->getType();
328}
329
330bool Sema::CheckMessageArgumentTypes(QualType ReceiverType,
331 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +0000332 Selector Sel, ObjCMethodDecl *Method,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000333 bool isClassMessage, bool isSuperMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000334 SourceLocation lbrac, SourceLocation rbrac,
John McCallf89e55a2010-11-18 06:31:45 +0000335 QualType &ReturnType, ExprValueKind &VK) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000336 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000337 // Apply default argument promotion as for (C99 6.5.2.2p6).
Douglas Gregor92e986e2010-04-22 16:44:27 +0000338 for (unsigned i = 0; i != NumArgs; i++) {
339 if (Args[i]->isTypeDependent())
340 continue;
341
John Wiegley429bb272011-04-08 18:41:53 +0000342 ExprResult Result = DefaultArgumentPromotion(Args[i]);
343 if (Result.isInvalid())
344 return true;
345 Args[i] = Result.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000346 }
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000347
John McCallf85e1932011-06-15 23:02:42 +0000348 unsigned DiagID;
349 if (getLangOptions().ObjCAutoRefCount)
350 DiagID = diag::err_arc_method_not_found;
351 else
352 DiagID = isClassMessage ? diag::warn_class_method_not_found
353 : diag::warn_inst_method_not_found;
Chris Lattner077bf5e2008-11-24 03:33:13 +0000354 Diag(lbrac, DiagID)
355 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000356 ReturnType = Context.getObjCIdType();
John McCallf89e55a2010-11-18 06:31:45 +0000357 VK = VK_RValue;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000358 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000359 }
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Douglas Gregor926df6c2011-06-11 01:09:30 +0000361 ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage,
362 isSuperMessage);
John McCallf89e55a2010-11-18 06:31:45 +0000363 VK = Expr::getValueKindForType(Method->getResultType());
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000365 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000366 // Method might have more arguments than selector indicates. This is due
367 // to addition of c-style arguments in method.
368 if (Method->param_size() > Sel.getNumArgs())
369 NumNamedArgs = Method->param_size();
370 // FIXME. This need be cleaned up.
371 if (NumArgs < NumNamedArgs) {
John McCallf89e55a2010-11-18 06:31:45 +0000372 Diag(lbrac, diag::err_typecheck_call_too_few_args)
373 << 2 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000374 return false;
375 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000376
Chris Lattner312531a2009-04-12 08:11:20 +0000377 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000378 for (unsigned i = 0; i < NumNamedArgs; i++) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000379 // We can't do any type-checking on a type-dependent argument.
380 if (Args[i]->isTypeDependent())
381 continue;
382
Chris Lattner85a932e2008-01-04 22:32:30 +0000383 Expr *argExpr = Args[i];
Douglas Gregor92e986e2010-04-22 16:44:27 +0000384
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000385 ParmVarDecl *Param = Method->param_begin()[i];
Chris Lattner85a932e2008-01-04 22:32:30 +0000386 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000388 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
389 Param->getType(),
390 PDiag(diag::err_call_incomplete_argument)
391 << argExpr->getSourceRange()))
392 return true;
Chris Lattner85a932e2008-01-04 22:32:30 +0000393
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000394 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
395 Param);
John McCall3fa5cae2010-10-26 07:05:15 +0000396 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
Douglas Gregor688fc9b2010-04-21 23:24:10 +0000397 if (ArgE.isInvalid())
398 IsError = true;
399 else
400 Args[i] = ArgE.takeAs<Expr>();
Chris Lattner85a932e2008-01-04 22:32:30 +0000401 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000402
403 // Promote additional arguments to variadic methods.
404 if (Method->isVariadic()) {
Douglas Gregor92e986e2010-04-22 16:44:27 +0000405 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
406 if (Args[i]->isTypeDependent())
407 continue;
408
John Wiegley429bb272011-04-08 18:41:53 +0000409 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
410 IsError |= Arg.isInvalid();
411 Args[i] = Arg.take();
Douglas Gregor92e986e2010-04-22 16:44:27 +0000412 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000413 } else {
414 // Check for extra arguments to non-variadic methods.
415 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000416 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000417 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000418 << 2 /*method*/ << NumNamedArgs << NumArgs
419 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000420 << SourceRange(Args[NumNamedArgs]->getLocStart(),
421 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000422 }
423 }
Fariborz Jahanian5272adf2011-04-15 22:06:22 +0000424 // diagnose nonnull arguments.
425 for (specific_attr_iterator<NonNullAttr>
426 i = Method->specific_attr_begin<NonNullAttr>(),
427 e = Method->specific_attr_end<NonNullAttr>(); i != e; ++i) {
428 CheckNonNullArguments(*i, Args, lbrac);
429 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000430
Douglas Gregor2725ca82010-04-21 19:57:20 +0000431 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000432 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000433}
434
John McCallf85e1932011-06-15 23:02:42 +0000435bool Sema::isSelfExpr(Expr *receiver) {
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000436 // 'self' is objc 'self' in an objc method only.
Fariborz Jahanianb4602102011-03-28 16:23:34 +0000437 DeclContext *DC = CurContext;
438 while (isa<BlockDecl>(DC))
439 DC = DC->getParent();
440 if (DC && !isa<ObjCMethodDecl>(DC))
Fariborz Jahanianf2d74cc2011-03-27 19:53:47 +0000441 return false;
John McCallf85e1932011-06-15 23:02:42 +0000442 receiver = receiver->IgnoreParenLValueCasts();
443 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver))
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000444 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
445 return true;
446 return false;
447}
448
Steve Narofff1afaf62009-02-26 15:55:06 +0000449// Helper method for ActOnClassMethod/ActOnInstanceMethod.
450// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000451// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000452// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000453ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000454 ObjCInterfaceDecl *ClassDecl) {
455 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000456 // lookup in class and all superclasses
457 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000458 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000459 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Steve Naroff5609ec02009-03-08 18:56:13 +0000461 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000462 if (!Method)
463 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Steve Naroff5609ec02009-03-08 18:56:13 +0000465 // Before we give up, check if the selector is an instance method.
466 // But only in the root. This matches gcc's behaviour and what the
467 // runtime expects.
468 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000469 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000470 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000471 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000472 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000473 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
474 }
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Steve Naroff5609ec02009-03-08 18:56:13 +0000476 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000477 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000478 return Method;
479}
480
481ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
482 ObjCInterfaceDecl *ClassDecl) {
483 ObjCMethodDecl *Method = 0;
484 while (ClassDecl && !Method) {
485 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000486 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000487 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000488
Steve Naroff5609ec02009-03-08 18:56:13 +0000489 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000490 if (!Method)
491 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000492 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000493 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000494 return Method;
495}
496
Fariborz Jahanian61478062011-03-09 20:18:06 +0000497/// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier
498/// list of a qualified objective pointer type.
499ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel,
500 const ObjCObjectPointerType *OPT,
501 bool Instance)
502{
503 ObjCMethodDecl *MD = 0;
504 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
505 E = OPT->qual_end(); I != E; ++I) {
506 ObjCProtocolDecl *PROTO = (*I);
507 if ((MD = PROTO->lookupMethod(Sel, Instance))) {
508 return MD;
509 }
510 }
511 return 0;
512}
513
Chris Lattner7f816522010-04-11 07:45:24 +0000514/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
515/// objective C interface. This is a property reference expression.
John McCall60d7b3a2010-08-24 06:29:42 +0000516ExprResult Sema::
Chris Lattner7f816522010-04-11 07:45:24 +0000517HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000518 Expr *BaseExpr, DeclarationName MemberName,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000519 SourceLocation MemberLoc,
520 SourceLocation SuperLoc, QualType SuperType,
521 bool Super) {
Chris Lattner7f816522010-04-11 07:45:24 +0000522 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
523 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
Douglas Gregor109ec1b2011-04-20 18:19:55 +0000524
525 if (MemberName.getNameKind() != DeclarationName::Identifier) {
526 Diag(MemberLoc, diag::err_invalid_property_name)
527 << MemberName << QualType(OPT, 0);
528 return ExprError();
529 }
530
Chris Lattner7f816522010-04-11 07:45:24 +0000531 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
532
Fariborz Jahanian8b1aba42010-12-16 00:56:28 +0000533 if (IFace->isForwardDecl()) {
534 Diag(MemberLoc, diag::err_property_not_found_forward_class)
535 << MemberName << QualType(OPT, 0);
536 Diag(IFace->getLocation(), diag::note_forward_class);
537 return ExprError();
538 }
Chris Lattner7f816522010-04-11 07:45:24 +0000539 // Search for a declared property first.
540 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
541 // Check whether we can reference this property.
542 if (DiagnoseUseOfDecl(PD, MemberLoc))
543 return ExprError();
544 QualType ResTy = PD->getType();
Fariborz Jahanian14086762011-03-28 23:47:18 +0000545 ResTy = ResTy.getNonLValueExprType(Context);
Chris Lattner7f816522010-04-11 07:45:24 +0000546 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
547 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000548 if (Getter &&
549 (Getter->hasRelatedResultType()
550 || DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)))
551 ResTy = getMessageSendResultType(QualType(OPT, 0), Getter, false,
552 Super);
553
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000554 if (Super)
555 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000556 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000557 MemberLoc,
558 SuperLoc, SuperType));
559 else
560 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
John McCallf89e55a2010-11-18 06:31:45 +0000561 VK_LValue, OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000562 MemberLoc, BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000563 }
564 // Check protocols on qualified interfaces.
565 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
566 E = OPT->qual_end(); I != E; ++I)
567 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
568 // Check whether we can reference this property.
569 if (DiagnoseUseOfDecl(PD, MemberLoc))
570 return ExprError();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000571
572 QualType T = PD->getType();
573 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
574 T = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000575 if (Super)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000576 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000577 VK_LValue,
578 OK_ObjCProperty,
579 MemberLoc,
580 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000581 else
Douglas Gregor926df6c2011-06-11 01:09:30 +0000582 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
John McCallf89e55a2010-11-18 06:31:45 +0000583 VK_LValue,
584 OK_ObjCProperty,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000585 MemberLoc,
586 BaseExpr));
Chris Lattner7f816522010-04-11 07:45:24 +0000587 }
588 // If that failed, look for an "implicit" property by seeing if the nullary
589 // selector is implemented.
590
591 // FIXME: The logic for looking up nullary and unary selectors should be
592 // shared with the code in ActOnInstanceMessage.
593
594 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
595 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000596
597 // May be founf in property's qualified list.
598 if (!Getter)
599 Getter = LookupMethodInQualifiedType(Sel, OPT, true);
Chris Lattner7f816522010-04-11 07:45:24 +0000600
601 // If this reference is in an @implementation, check for 'private' methods.
602 if (!Getter)
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000603 Getter = IFace->lookupPrivateMethod(Sel);
Chris Lattner7f816522010-04-11 07:45:24 +0000604
605 // Look through local category implementations associated with the class.
606 if (!Getter)
607 Getter = IFace->getCategoryInstanceMethod(Sel);
608 if (Getter) {
609 // Check if we can reference this property.
610 if (DiagnoseUseOfDecl(Getter, MemberLoc))
611 return ExprError();
612 }
613 // If we found a getter then this may be a valid dot-reference, we
614 // will look for the matching setter, in case it is needed.
615 Selector SetterSel =
616 SelectorTable::constructSetterName(PP.getIdentifierTable(),
617 PP.getSelectorTable(), Member);
618 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000619
620 // May be founf in property's qualified list.
621 if (!Setter)
622 Setter = LookupMethodInQualifiedType(SetterSel, OPT, true);
623
Chris Lattner7f816522010-04-11 07:45:24 +0000624 if (!Setter) {
625 // If this reference is in an @implementation, also check for 'private'
626 // methods.
Fariborz Jahanian74b27562010-12-03 23:37:08 +0000627 Setter = IFace->lookupPrivateMethod(SetterSel);
Chris Lattner7f816522010-04-11 07:45:24 +0000628 }
629 // Look through local category implementations associated with the class.
630 if (!Setter)
631 Setter = IFace->getCategoryInstanceMethod(SetterSel);
Fariborz Jahanian27569b02011-03-09 22:17:12 +0000632
Chris Lattner7f816522010-04-11 07:45:24 +0000633 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
634 return ExprError();
635
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000636 if (Getter || Setter) {
637 QualType PType;
638 if (Getter)
Douglas Gregor926df6c2011-06-11 01:09:30 +0000639 PType = getMessageSendResultType(QualType(OPT, 0), Getter, false, Super);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000640 else {
641 ParmVarDecl *ArgDecl = *Setter->param_begin();
642 PType = ArgDecl->getType();
643 }
644
John McCall09431682010-11-18 19:01:18 +0000645 ExprValueKind VK = VK_LValue;
646 ExprObjectKind OK = OK_ObjCProperty;
647 if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
648 PType->isVoidType())
649 VK = VK_RValue, OK = OK_Ordinary;
650
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000651 if (Super)
John McCall12f78a62010-12-02 01:19:52 +0000652 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
653 PType, VK, OK,
654 MemberLoc,
655 SuperLoc, SuperType));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000656 else
John McCall12f78a62010-12-02 01:19:52 +0000657 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
658 PType, VK, OK,
659 MemberLoc, BaseExpr));
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000660
Chris Lattner7f816522010-04-11 07:45:24 +0000661 }
662
663 // Attempt to correct for typos in property names.
664 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000665 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
Chris Lattner7f816522010-04-11 07:45:24 +0000666 Res.getAsSingle<ObjCPropertyDecl>()) {
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000667 DeclarationName TypoResult = Res.getLookupName();
Chris Lattner7f816522010-04-11 07:45:24 +0000668 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000669 << MemberName << QualType(OPT, 0) << TypoResult
670 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000671 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
672 Diag(Property->getLocation(), diag::note_previous_decl)
673 << Property->getDeclName();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000674 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc,
675 SuperLoc, SuperType, Super);
Chris Lattner7f816522010-04-11 07:45:24 +0000676 }
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000677 ObjCInterfaceDecl *ClassDeclared;
678 if (ObjCIvarDecl *Ivar =
679 IFace->lookupInstanceVariable(Member, ClassDeclared)) {
680 QualType T = Ivar->getType();
681 if (const ObjCObjectPointerType * OBJPT =
682 T->getAsObjCInterfacePointerType()) {
683 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
684 if (ObjCInterfaceDecl *IFace = IFaceT->getDecl())
685 if (IFace->isForwardDecl()) {
686 Diag(MemberLoc, diag::err_property_not_as_forward_class)
Fariborz Jahanian2a96bf52011-02-17 17:30:05 +0000687 << MemberName << IFace;
Fariborz Jahanian41aadbc2011-02-17 01:26:14 +0000688 Diag(IFace->getLocation(), diag::note_forward_class);
689 return ExprError();
690 }
691 }
692 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000693
Chris Lattner7f816522010-04-11 07:45:24 +0000694 Diag(MemberLoc, diag::err_property_not_found)
695 << MemberName << QualType(OPT, 0);
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000696 if (Setter)
Chris Lattner7f816522010-04-11 07:45:24 +0000697 Diag(Setter->getLocation(), diag::note_getter_unavailable)
Fariborz Jahanian99130e52010-12-22 19:46:35 +0000698 << MemberName << BaseExpr->getSourceRange();
Chris Lattner7f816522010-04-11 07:45:24 +0000699 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000700}
701
702
703
John McCall60d7b3a2010-08-24 06:29:42 +0000704ExprResult Sema::
Chris Lattnereb483eb2010-04-11 08:28:14 +0000705ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
706 IdentifierInfo &propertyName,
707 SourceLocation receiverNameLoc,
708 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000709
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000710 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000711 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
712 receiverNameLoc);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000713
714 bool IsSuper = false;
Chris Lattnereb483eb2010-04-11 08:28:14 +0000715 if (IFace == 0) {
716 // If the "receiver" is 'super' in a method, handle it as an expression-like
717 // property reference.
John McCall26743b22011-02-03 09:00:02 +0000718 if (receiverNamePtr->isStr("super")) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000719 IsSuper = true;
720
John McCall26743b22011-02-03 09:00:02 +0000721 if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf()) {
Chris Lattnereb483eb2010-04-11 08:28:14 +0000722 if (CurMethod->isInstanceMethod()) {
723 QualType T =
724 Context.getObjCInterfaceType(CurMethod->getClassInterface());
725 T = Context.getObjCObjectPointerType(T);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000726
727 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +0000728 /*BaseExpr*/0, &propertyName,
729 propertyNameLoc,
730 receiverNameLoc, T, true);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000731 }
Mike Stump1eb44332009-09-09 15:08:12 +0000732
Chris Lattnereb483eb2010-04-11 08:28:14 +0000733 // Otherwise, if this is a class method, try dispatching to our
734 // superclass.
735 IFace = CurMethod->getClassInterface()->getSuperClass();
736 }
John McCall26743b22011-02-03 09:00:02 +0000737 }
Chris Lattnereb483eb2010-04-11 08:28:14 +0000738
739 if (IFace == 0) {
740 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
741 return ExprError();
742 }
743 }
744
745 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000746 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000747 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000748
749 // If this reference is in an @implementation, check for 'private' methods.
750 if (!Getter)
751 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
752 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000753 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000754 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000755
756 if (Getter) {
757 // FIXME: refactor/share with ActOnMemberReference().
758 // Check if we can reference this property.
759 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
760 return ExprError();
761 }
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Steve Naroff61f72cb2009-03-09 21:12:44 +0000763 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000764 Selector SetterSel =
765 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000766 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000767
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000768 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000769 if (!Setter) {
770 // If this reference is in an @implementation, also check for 'private'
771 // methods.
772 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
773 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000774 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000775 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000776 }
777 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000778 if (!Setter)
779 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000780
781 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
782 return ExprError();
783
784 if (Getter || Setter) {
785 QualType PType;
786
John McCall09431682010-11-18 19:01:18 +0000787 ExprValueKind VK = VK_LValue;
788 if (Getter) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000789 PType = getMessageSendResultType(Context.getObjCInterfaceType(IFace),
790 Getter, true,
791 receiverNamePtr->isStr("super"));
John McCall09431682010-11-18 19:01:18 +0000792 if (!getLangOptions().CPlusPlus &&
793 !PType.hasQualifiers() && PType->isVoidType())
794 VK = VK_RValue;
795 } else {
Steve Naroff61f72cb2009-03-09 21:12:44 +0000796 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
797 E = Setter->param_end(); PI != E; ++PI)
798 PType = (*PI)->getType();
John McCall09431682010-11-18 19:01:18 +0000799 VK = VK_LValue;
Steve Naroff61f72cb2009-03-09 21:12:44 +0000800 }
John McCall09431682010-11-18 19:01:18 +0000801
802 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
803
Douglas Gregor926df6c2011-06-11 01:09:30 +0000804 if (IsSuper)
805 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
806 PType, VK, OK,
807 propertyNameLoc,
808 receiverNameLoc,
809 Context.getObjCInterfaceType(IFace)));
810
John McCall12f78a62010-12-02 01:19:52 +0000811 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
812 PType, VK, OK,
813 propertyNameLoc,
814 receiverNameLoc, IFace));
Steve Naroff61f72cb2009-03-09 21:12:44 +0000815 }
816 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
817 << &propertyName << Context.getObjCInterfaceType(IFace));
818}
819
Douglas Gregor47bd5432010-04-14 02:46:37 +0000820Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
Douglas Gregor1569f952010-04-21 20:38:13 +0000821 IdentifierInfo *Name,
Douglas Gregor47bd5432010-04-14 02:46:37 +0000822 SourceLocation NameLoc,
823 bool IsSuper,
Douglas Gregor1569f952010-04-21 20:38:13 +0000824 bool HasTrailingDot,
John McCallb3d87482010-08-24 05:47:05 +0000825 ParsedType &ReceiverType) {
826 ReceiverType = ParsedType();
Douglas Gregor1569f952010-04-21 20:38:13 +0000827
Douglas Gregor47bd5432010-04-14 02:46:37 +0000828 // If the identifier is "super" and there is no trailing dot, we're
Douglas Gregor95f42922010-10-14 22:11:03 +0000829 // messaging super. If the identifier is "super" and there is a
830 // trailing dot, it's an instance message.
831 if (IsSuper && S->isInObjcMethodScope())
832 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000833
834 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
835 LookupName(Result, S);
836
837 switch (Result.getResultKind()) {
838 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000839 // Normal name lookup didn't find anything. If we're in an
840 // Objective-C method, look for ivars. If we find one, we're done!
Douglas Gregor95f42922010-10-14 22:11:03 +0000841 // FIXME: This is a hack. Ivar lookup should be part of normal
842 // lookup.
Douglas Gregored464422010-04-19 20:09:36 +0000843 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
844 ObjCInterfaceDecl *ClassDeclared;
845 if (Method->getClassInterface()->lookupInstanceVariable(Name,
846 ClassDeclared))
847 return ObjCInstanceMessage;
848 }
Douglas Gregor95f42922010-10-14 22:11:03 +0000849
Douglas Gregor47bd5432010-04-14 02:46:37 +0000850 // Break out; we'll perform typo correction below.
851 break;
852
853 case LookupResult::NotFoundInCurrentInstantiation:
854 case LookupResult::FoundOverloaded:
855 case LookupResult::FoundUnresolvedValue:
856 case LookupResult::Ambiguous:
857 Result.suppressDiagnostics();
858 return ObjCInstanceMessage;
859
860 case LookupResult::Found: {
Fariborz Jahanian8348de32011-02-08 00:23:07 +0000861 // If the identifier is a class or not, and there is a trailing dot,
862 // it's an instance message.
863 if (HasTrailingDot)
864 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000865 // We found something. If it's a type, then we have a class
866 // message. Otherwise, it's an instance message.
867 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000868 QualType T;
869 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
870 T = Context.getObjCInterfaceType(Class);
871 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
872 T = Context.getTypeDeclType(Type);
873 else
874 return ObjCInstanceMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000875
Douglas Gregor1569f952010-04-21 20:38:13 +0000876 // We have a class message, and T is the type we're
877 // messaging. Build source-location information for it.
878 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000879 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregor1569f952010-04-21 20:38:13 +0000880 return ObjCClassMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000881 }
882 }
883
Douglas Gregoraaf87162010-04-14 20:04:41 +0000884 // Determine our typo-correction context.
885 CorrectTypoContext CTC = CTC_Expression;
886 if (ObjCMethodDecl *Method = getCurMethodDecl())
887 if (Method->getClassInterface() &&
888 Method->getClassInterface()->getSuperClass())
889 CTC = CTC_ObjCMessageReceiver;
890
891 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
892 if (Result.isSingleResult()) {
893 // If we found a declaration, correct when it refers to an Objective-C
894 // class.
895 NamedDecl *ND = Result.getFoundDecl();
Douglas Gregor1569f952010-04-21 20:38:13 +0000896 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
Douglas Gregoraaf87162010-04-14 20:04:41 +0000897 Diag(NameLoc, diag::err_unknown_receiver_suggest)
898 << Name << Result.getLookupName()
899 << FixItHint::CreateReplacement(SourceRange(NameLoc),
900 ND->getNameAsString());
901 Diag(ND->getLocation(), diag::note_previous_decl)
902 << Corrected;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000903
Douglas Gregor1569f952010-04-21 20:38:13 +0000904 QualType T = Context.getObjCInterfaceType(Class);
905 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
John McCallb3d87482010-08-24 05:47:05 +0000906 ReceiverType = CreateParsedType(T, TSInfo);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000907 return ObjCClassMessage;
908 }
909 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
910 Corrected.getAsIdentifierInfo()->isStr("super")) {
911 // If we've found the keyword "super", this is a send to super.
912 Diag(NameLoc, diag::err_unknown_receiver_suggest)
913 << Name << Corrected
914 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
Douglas Gregoraaf87162010-04-14 20:04:41 +0000915 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000916 }
917 }
918
919 // Fall back: let the parser try to parse it as an instance message.
920 return ObjCInstanceMessage;
921}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000922
John McCall60d7b3a2010-08-24 06:29:42 +0000923ExprResult Sema::ActOnSuperMessage(Scope *S,
Douglas Gregor0fbda682010-09-15 14:51:05 +0000924 SourceLocation SuperLoc,
925 Selector Sel,
926 SourceLocation LBracLoc,
927 SourceLocation SelectorLoc,
928 SourceLocation RBracLoc,
929 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000930 // Determine whether we are inside a method or not.
John McCall26743b22011-02-03 09:00:02 +0000931 ObjCMethodDecl *Method = tryCaptureObjCSelf();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000932 if (!Method) {
933 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
934 return ExprError();
935 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000936
Douglas Gregorf95861a2010-04-21 20:01:04 +0000937 ObjCInterfaceDecl *Class = Method->getClassInterface();
938 if (!Class) {
939 Diag(SuperLoc, diag::error_no_super_class_message)
940 << Method->getDeclName();
941 return ExprError();
942 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000943
Douglas Gregorf95861a2010-04-21 20:01:04 +0000944 ObjCInterfaceDecl *Super = Class->getSuperClass();
945 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000946 // The current class does not have a superclass.
Ted Kremeneke00909a2011-01-23 17:21:34 +0000947 Diag(SuperLoc, diag::error_root_class_cannot_use_super)
948 << Class->getIdentifier();
Douglas Gregor2725ca82010-04-21 19:57:20 +0000949 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000950 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000951
Douglas Gregorf95861a2010-04-21 20:01:04 +0000952 // We are in a method whose class has a superclass, so 'super'
953 // is acting as a keyword.
954 if (Method->isInstanceMethod()) {
955 // Since we are in an instance method, this is an instance
956 // message to the superclass instance.
957 QualType SuperTy = Context.getObjCInterfaceType(Super);
958 SuperTy = Context.getObjCObjectPointerType(SuperTy);
John McCall9ae2f072010-08-23 23:25:46 +0000959 return BuildInstanceMessage(0, SuperTy, SuperLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000960 Sel, /*Method=*/0,
961 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000962 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000963
964 // Since we are in a class method, this is a class message to
965 // the superclass.
966 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
967 Context.getObjCInterfaceType(Super),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +0000968 SuperLoc, Sel, /*Method=*/0,
969 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000970}
971
972/// \brief Build an Objective-C class message expression.
973///
974/// This routine takes care of both normal class messages and
975/// class messages to the superclass.
976///
977/// \param ReceiverTypeInfo Type source information that describes the
978/// receiver of this message. This may be NULL, in which case we are
979/// sending to the superclass and \p SuperLoc must be a valid source
980/// location.
981
982/// \param ReceiverType The type of the object receiving the
983/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
984/// type as that refers to. For a superclass send, this is the type of
985/// the superclass.
986///
987/// \param SuperLoc The location of the "super" keyword in a
988/// superclass message.
989///
990/// \param Sel The selector to which the message is being sent.
991///
Douglas Gregorf49bb082010-04-22 17:01:48 +0000992/// \param Method The method that this class message is invoking, if
993/// already known.
994///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000995/// \param LBracLoc The location of the opening square bracket ']'.
996///
Douglas Gregor2725ca82010-04-21 19:57:20 +0000997/// \param RBrac The location of the closing square bracket ']'.
998///
999/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001000ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001001 QualType ReceiverType,
1002 SourceLocation SuperLoc,
1003 Selector Sel,
1004 ObjCMethodDecl *Method,
1005 SourceLocation LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001006 SourceLocation SelectorLoc,
Douglas Gregor0fbda682010-09-15 14:51:05 +00001007 SourceLocation RBracLoc,
1008 MultiExprArg ArgsIn) {
1009 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
Douglas Gregor9497a732010-09-16 01:51:54 +00001010 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Douglas Gregor0fbda682010-09-15 14:51:05 +00001011 if (LBracLoc.isInvalid()) {
1012 Diag(Loc, diag::err_missing_open_square_message_send)
1013 << FixItHint::CreateInsertion(Loc, "[");
1014 LBracLoc = Loc;
1015 }
1016
Douglas Gregor92e986e2010-04-22 16:44:27 +00001017 if (ReceiverType->isDependentType()) {
1018 // If the receiver type is dependent, we can't type-check anything
1019 // at this point. Build a dependent expression.
1020 unsigned NumArgs = ArgsIn.size();
1021 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1022 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
John McCallf89e55a2010-11-18 06:31:45 +00001023 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
1024 VK_RValue, LBracLoc, ReceiverTypeInfo,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001025 Sel, SelectorLoc, /*Method=*/0,
Douglas Gregor92e986e2010-04-22 16:44:27 +00001026 Args, NumArgs, RBracLoc));
1027 }
Chris Lattner15faee12010-04-12 05:38:43 +00001028
Douglas Gregor2725ca82010-04-21 19:57:20 +00001029 // Find the class to which we are sending this message.
1030 ObjCInterfaceDecl *Class = 0;
John McCallc12c5bb2010-05-15 11:32:37 +00001031 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
1032 if (!ClassType || !(Class = ClassType->getInterface())) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001033 Diag(Loc, diag::err_invalid_receiver_class_message)
1034 << ReceiverType;
1035 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +00001036 }
Douglas Gregor2725ca82010-04-21 19:57:20 +00001037 assert(Class && "We don't know which class we're messaging?");
Fariborz Jahanian02b0d652011-03-08 19:12:46 +00001038 (void)DiagnoseUseOfDecl(Class, Loc);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001039 // Find the method we are messaging.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001040 if (!Method) {
1041 if (Class->isForwardDecl()) {
John McCallf85e1932011-06-15 23:02:42 +00001042 if (getLangOptions().ObjCAutoRefCount) {
1043 Diag(Loc, diag::err_arc_receiver_forward_class) << ReceiverType;
1044 } else {
1045 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
1046 }
1047
Douglas Gregorf49bb082010-04-22 17:01:48 +00001048 // A forward class used in messaging is treated as a 'Class'
Douglas Gregorf49bb082010-04-22 17:01:48 +00001049 Method = LookupFactoryMethodInGlobalPool(Sel,
1050 SourceRange(LBracLoc, RBracLoc));
John McCallf85e1932011-06-15 23:02:42 +00001051 if (Method && !getLangOptions().ObjCAutoRefCount)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001052 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
1053 << Method->getDeclName();
1054 }
1055 if (!Method)
1056 Method = Class->lookupClassMethod(Sel);
1057
1058 // If we have an implementation in scope, check "private" methods.
1059 if (!Method)
1060 Method = LookupPrivateClassMethod(Sel, Class);
1061
1062 if (Method && DiagnoseUseOfDecl(Method, Loc))
1063 return ExprError();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +00001064 }
Mike Stump1eb44332009-09-09 15:08:12 +00001065
Douglas Gregor2725ca82010-04-21 19:57:20 +00001066 // Check the argument types and determine the result type.
1067 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001068 ExprValueKind VK = VK_RValue;
1069
Douglas Gregor2725ca82010-04-21 19:57:20 +00001070 unsigned NumArgs = ArgsIn.size();
1071 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001072 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method, true,
1073 SuperLoc.isValid(), LBracLoc, RBracLoc,
1074 ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001075 return ExprError();
Ted Kremenek4df728e2008-06-24 15:50:53 +00001076
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001077 if (Method && !Method->getResultType()->isVoidType() &&
1078 RequireCompleteType(LBracLoc, Method->getResultType(),
1079 diag::err_illegal_message_expr_incomplete_type))
1080 return ExprError();
1081
Douglas Gregor2725ca82010-04-21 19:57:20 +00001082 // Construct the appropriate ObjCMessageExpr.
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001083 Expr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001084 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001085 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001086 SuperLoc, /*IsInstanceSuper=*/false,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001087 ReceiverType, Sel, SelectorLoc,
1088 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001089 else
John McCallf89e55a2010-11-18 06:31:45 +00001090 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001091 ReceiverTypeInfo, Sel, SelectorLoc,
1092 Method, Args, NumArgs, RBracLoc);
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001093 return MaybeBindToTemporary(Result);
Chris Lattner85a932e2008-01-04 22:32:30 +00001094}
1095
Douglas Gregor2725ca82010-04-21 19:57:20 +00001096// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +00001097// ArgExprs is optional - if it is present, the number of expressions
1098// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001099ExprResult Sema::ActOnClassMessage(Scope *S,
Douglas Gregor77328d12010-09-15 23:19:31 +00001100 ParsedType Receiver,
1101 Selector Sel,
1102 SourceLocation LBracLoc,
1103 SourceLocation SelectorLoc,
1104 SourceLocation RBracLoc,
1105 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001106 TypeSourceInfo *ReceiverTypeInfo;
1107 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
1108 if (ReceiverType.isNull())
1109 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Douglas Gregor2725ca82010-04-21 19:57:20 +00001112 if (!ReceiverTypeInfo)
1113 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
1114
1115 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
Douglas Gregorf49bb082010-04-22 17:01:48 +00001116 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001117 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +00001118}
1119
1120/// \brief Build an Objective-C instance message expression.
1121///
1122/// This routine takes care of both normal instance messages and
1123/// instance messages to the superclass instance.
1124///
1125/// \param Receiver The expression that computes the object that will
1126/// receive this message. This may be empty, in which case we are
1127/// sending to the superclass instance and \p SuperLoc must be a valid
1128/// source location.
1129///
1130/// \param ReceiverType The (static) type of the object receiving the
1131/// message. When a \p Receiver expression is provided, this is the
1132/// same type as that expression. For a superclass instance send, this
1133/// is a pointer to the type of the superclass.
1134///
1135/// \param SuperLoc The location of the "super" keyword in a
1136/// superclass instance message.
1137///
1138/// \param Sel The selector to which the message is being sent.
1139///
Douglas Gregorf49bb082010-04-22 17:01:48 +00001140/// \param Method The method that this instance message is invoking, if
1141/// already known.
1142///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001143/// \param LBracLoc The location of the opening square bracket ']'.
1144///
Douglas Gregor2725ca82010-04-21 19:57:20 +00001145/// \param RBrac The location of the closing square bracket ']'.
1146///
1147/// \param Args The message arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00001148ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001149 QualType ReceiverType,
1150 SourceLocation SuperLoc,
1151 Selector Sel,
1152 ObjCMethodDecl *Method,
1153 SourceLocation LBracLoc,
1154 SourceLocation SelectorLoc,
1155 SourceLocation RBracLoc,
1156 MultiExprArg ArgsIn) {
Douglas Gregor0fbda682010-09-15 14:51:05 +00001157 // The location of the receiver.
1158 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
1159
1160 if (LBracLoc.isInvalid()) {
1161 Diag(Loc, diag::err_missing_open_square_message_send)
1162 << FixItHint::CreateInsertion(Loc, "[");
1163 LBracLoc = Loc;
1164 }
1165
Douglas Gregor2725ca82010-04-21 19:57:20 +00001166 // If we have a receiver expression, perform appropriate promotions
1167 // and determine receiver type.
Douglas Gregor2725ca82010-04-21 19:57:20 +00001168 if (Receiver) {
Douglas Gregor92e986e2010-04-22 16:44:27 +00001169 if (Receiver->isTypeDependent()) {
1170 // If the receiver is type-dependent, we can't type-check anything
1171 // at this point. Build a dependent expression.
1172 unsigned NumArgs = ArgsIn.size();
1173 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1174 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
1175 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00001176 VK_RValue, LBracLoc, Receiver, Sel,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001177 SelectorLoc, /*Method=*/0,
1178 Args, NumArgs, RBracLoc));
Douglas Gregor92e986e2010-04-22 16:44:27 +00001179 }
1180
Douglas Gregor2725ca82010-04-21 19:57:20 +00001181 // If necessary, apply function/array conversion to the receiver.
1182 // C99 6.7.5.3p[7,8].
John Wiegley429bb272011-04-08 18:41:53 +00001183 ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver);
1184 if (Result.isInvalid())
1185 return ExprError();
1186 Receiver = Result.take();
Douglas Gregor2725ca82010-04-21 19:57:20 +00001187 ReceiverType = Receiver->getType();
1188 }
1189
Douglas Gregorf49bb082010-04-22 17:01:48 +00001190 if (!Method) {
1191 // Handle messages to id.
Fariborz Jahanianba551982010-08-10 18:10:50 +00001192 bool receiverIsId = ReceiverType->isObjCIdType();
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001193 if (receiverIsId || ReceiverType->isBlockPointerType() ||
Douglas Gregorf49bb082010-04-22 17:01:48 +00001194 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
1195 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001196 SourceRange(LBracLoc, RBracLoc),
1197 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001198 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +00001199 Method = LookupFactoryMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001200 SourceRange(LBracLoc, RBracLoc),
1201 receiverIsId);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001202 } else if (ReceiverType->isObjCClassType() ||
1203 ReceiverType->isObjCQualifiedClassType()) {
1204 // Handle messages to Class.
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001205 // We allow sending a message to a qualified Class ("Class<foo>"), which
1206 // is ok as long as one of the protocols implements the selector (if not, warn).
1207 if (const ObjCObjectPointerType *QClassTy
1208 = ReceiverType->getAsObjCQualifiedClassType()) {
1209 // Search protocols for class methods.
1210 Method = LookupMethodInQualifiedType(Sel, QClassTy, false);
1211 if (!Method) {
1212 Method = LookupMethodInQualifiedType(Sel, QClassTy, true);
1213 // warn if instance method found for a Class message.
1214 if (Method) {
1215 Diag(Loc, diag::warn_instance_method_on_class_found)
1216 << Method->getSelector() << Sel;
1217 Diag(Method->getLocation(), diag::note_method_declared_at);
1218 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +00001219 }
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001220 } else {
1221 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
1222 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
1223 // First check the public methods in the class interface.
1224 Method = ClassDecl->lookupClassMethod(Sel);
1225
1226 if (!Method)
1227 Method = LookupPrivateClassMethod(Sel, ClassDecl);
1228 }
1229 if (Method && DiagnoseUseOfDecl(Method, Loc))
1230 return ExprError();
1231 }
1232 if (!Method) {
1233 // If not messaging 'self', look for any factory method named 'Sel'.
1234 if (!Receiver || !isSelfExpr(Receiver)) {
1235 Method = LookupFactoryMethodInGlobalPool(Sel,
1236 SourceRange(LBracLoc, RBracLoc),
1237 true);
1238 if (!Method) {
1239 // If no class (factory) method was found, check if an _instance_
1240 // method of the same name exists in the root class only.
1241 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00001242 SourceRange(LBracLoc, RBracLoc),
Fariborz Jahanian759abb42011-04-06 18:40:08 +00001243 true);
1244 if (Method)
1245 if (const ObjCInterfaceDecl *ID =
1246 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
1247 if (ID->getSuperClass())
1248 Diag(Loc, diag::warn_root_inst_method_not_found)
1249 << Sel << SourceRange(LBracLoc, RBracLoc);
1250 }
1251 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001252 }
1253 }
1254 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001255 } else {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001256 ObjCInterfaceDecl* ClassDecl = 0;
1257
1258 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1259 // long as one of the protocols implements the selector (if not, warn).
1260 if (const ObjCObjectPointerType *QIdTy
1261 = ReceiverType->getAsObjCQualifiedIdType()) {
1262 // Search protocols for instance methods.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001263 Method = LookupMethodInQualifiedType(Sel, QIdTy, true);
1264 if (!Method)
1265 Method = LookupMethodInQualifiedType(Sel, QIdTy, false);
Douglas Gregorf49bb082010-04-22 17:01:48 +00001266 } else if (const ObjCObjectPointerType *OCIType
1267 = ReceiverType->getAsObjCInterfacePointerType()) {
1268 // We allow sending a message to a pointer to an interface (an object).
1269 ClassDecl = OCIType->getInterfaceDecl();
John McCallf85e1932011-06-15 23:02:42 +00001270
1271 if (ClassDecl->isForwardDecl() && getLangOptions().ObjCAutoRefCount) {
1272 Diag(Loc, diag::err_arc_receiver_forward_instance)
1273 << OCIType->getPointeeType()
1274 << (Receiver ? Receiver->getSourceRange() : SourceRange(SuperLoc));
1275 return ExprError();
1276 }
1277
Douglas Gregorf49bb082010-04-22 17:01:48 +00001278 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1279 // faster than the following method (which can do *many* linear searches).
Sebastian Redldb9d2142010-08-02 23:18:59 +00001280 // The idea is to add class info to MethodPool.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001281 Method = ClassDecl->lookupInstanceMethod(Sel);
1282
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001283 if (!Method)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001284 // Search protocol qualifiers.
Fariborz Jahanian27569b02011-03-09 22:17:12 +00001285 Method = LookupMethodInQualifiedType(Sel, OCIType, true);
1286
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001287 const ObjCInterfaceDecl *forwardClass = 0;
Douglas Gregorf49bb082010-04-22 17:01:48 +00001288 if (!Method) {
1289 // If we have implementations in scope, check "private" methods.
1290 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1291
John McCallf85e1932011-06-15 23:02:42 +00001292 if (!Method && getLangOptions().ObjCAutoRefCount) {
1293 Diag(Loc, diag::err_arc_may_not_respond)
1294 << OCIType->getPointeeType() << Sel;
1295 return ExprError();
1296 }
1297
Douglas Gregorf49bb082010-04-22 17:01:48 +00001298 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1299 // If we still haven't found a method, look in the global pool. This
1300 // behavior isn't very desirable, however we need it for GCC
1301 // compatibility. FIXME: should we deviate??
1302 if (OCIType->qual_empty()) {
1303 Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001304 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89ebaed2011-04-23 17:27:19 +00001305 if (OCIType->getInterfaceDecl()->isForwardDecl())
1306 forwardClass = OCIType->getInterfaceDecl();
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001307 if (Method && !forwardClass)
Douglas Gregorf49bb082010-04-22 17:01:48 +00001308 Diag(Loc, diag::warn_maynot_respond)
1309 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1310 }
1311 }
1312 }
Fariborz Jahanian8e5fc9b2010-12-21 00:44:01 +00001313 if (Method && DiagnoseUseOfDecl(Method, Loc, forwardClass))
Douglas Gregorf49bb082010-04-22 17:01:48 +00001314 return ExprError();
John McCallf85e1932011-06-15 23:02:42 +00001315 } else if (!getLangOptions().ObjCAutoRefCount &&
1316 !Context.getObjCIdType().isNull() &&
Douglas Gregorf6094622010-07-23 15:58:24 +00001317 (ReceiverType->isPointerType() ||
1318 ReceiverType->isIntegerType())) {
Douglas Gregorf49bb082010-04-22 17:01:48 +00001319 // Implicitly convert integers and pointers to 'id' but emit a warning.
John McCallf85e1932011-06-15 23:02:42 +00001320 // But not in ARC.
Douglas Gregorf49bb082010-04-22 17:01:48 +00001321 Diag(Loc, diag::warn_bad_receiver_type)
1322 << ReceiverType
1323 << Receiver->getSourceRange();
1324 if (ReceiverType->isPointerType())
John Wiegley429bb272011-04-08 18:41:53 +00001325 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1326 CK_BitCast).take();
John McCall404cd162010-11-13 01:35:44 +00001327 else {
1328 // TODO: specialized warning on null receivers?
1329 bool IsNull = Receiver->isNullPointerConstant(Context,
1330 Expr::NPC_ValueDependentIsNull);
John Wiegley429bb272011-04-08 18:41:53 +00001331 Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(),
1332 IsNull ? CK_NullToPointer : CK_IntegralToPointer).take();
John McCall404cd162010-11-13 01:35:44 +00001333 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001334 ReceiverType = Receiver->getType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00001335 }
John Wiegley429bb272011-04-08 18:41:53 +00001336 else {
1337 ExprResult ReceiverRes;
1338 if (getLangOptions().CPlusPlus)
1339 ReceiverRes = PerformContextuallyConvertToObjCId(Receiver);
1340 if (ReceiverRes.isUsable()) {
1341 Receiver = ReceiverRes.take();
1342 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
1343 Receiver = ICE->getSubExpr();
1344 ReceiverType = Receiver->getType();
1345 }
1346 return BuildInstanceMessage(Receiver,
1347 ReceiverType,
1348 SuperLoc,
1349 Sel,
1350 Method,
1351 LBracLoc,
1352 SelectorLoc,
1353 RBracLoc,
1354 move(ArgsIn));
1355 } else {
1356 // Reject other random receiver types (e.g. structs).
1357 Diag(Loc, diag::err_bad_receiver_type)
1358 << ReceiverType << Receiver->getSourceRange();
1359 return ExprError();
Fariborz Jahanian3ba60612010-05-13 17:19:25 +00001360 }
Douglas Gregorf49bb082010-04-22 17:01:48 +00001361 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00001362 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +00001363 }
Mike Stump1eb44332009-09-09 15:08:12 +00001364
Douglas Gregor2725ca82010-04-21 19:57:20 +00001365 // Check the message arguments.
1366 unsigned NumArgs = ArgsIn.size();
1367 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1368 QualType ReturnType;
John McCallf89e55a2010-11-18 06:31:45 +00001369 ExprValueKind VK = VK_RValue;
Fariborz Jahanian26005032010-12-01 01:07:24 +00001370 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1371 ReceiverType->isObjCQualifiedClassType());
Douglas Gregor926df6c2011-06-11 01:09:30 +00001372 if (CheckMessageArgumentTypes(ReceiverType, Args, NumArgs, Sel, Method,
1373 ClassMessage, SuperLoc.isValid(),
John McCallf89e55a2010-11-18 06:31:45 +00001374 LBracLoc, RBracLoc, ReturnType, VK))
Douglas Gregor2725ca82010-04-21 19:57:20 +00001375 return ExprError();
Fariborz Jahanianda59e092010-06-16 19:56:08 +00001376
Douglas Gregor483dd2f2011-01-11 03:23:19 +00001377 if (Method && !Method->getResultType()->isVoidType() &&
1378 RequireCompleteType(LBracLoc, Method->getResultType(),
1379 diag::err_illegal_message_expr_incomplete_type))
1380 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +00001381
John McCallf85e1932011-06-15 23:02:42 +00001382 // In ARC, forbid the user from sending messages to
1383 // retain/release/autorelease/dealloc/retainCount explicitly.
1384 if (getLangOptions().ObjCAutoRefCount) {
1385 ObjCMethodFamily family =
1386 (Method ? Method->getMethodFamily() : Sel.getMethodFamily());
1387 switch (family) {
1388 case OMF_init:
1389 if (Method)
1390 checkInitMethod(Method, ReceiverType);
1391
1392 case OMF_None:
1393 case OMF_alloc:
1394 case OMF_copy:
1395 case OMF_mutableCopy:
1396 case OMF_new:
1397 case OMF_self:
1398 break;
1399
1400 case OMF_dealloc:
1401 case OMF_retain:
1402 case OMF_release:
1403 case OMF_autorelease:
1404 case OMF_retainCount:
1405 Diag(Loc, diag::err_arc_illegal_explicit_message)
1406 << Sel << SelectorLoc;
1407 break;
1408 }
1409 }
1410
Douglas Gregor2725ca82010-04-21 19:57:20 +00001411 // Construct the appropriate ObjCMessageExpr instance.
John McCallf85e1932011-06-15 23:02:42 +00001412 ObjCMessageExpr *Result;
Douglas Gregor2725ca82010-04-21 19:57:20 +00001413 if (SuperLoc.isValid())
John McCallf89e55a2010-11-18 06:31:45 +00001414 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001415 SuperLoc, /*IsInstanceSuper=*/true,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001416 ReceiverType, Sel, SelectorLoc, Method,
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001417 Args, NumArgs, RBracLoc);
1418 else
John McCallf89e55a2010-11-18 06:31:45 +00001419 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001420 Receiver, Sel, SelectorLoc, Method,
1421 Args, NumArgs, RBracLoc);
John McCallf85e1932011-06-15 23:02:42 +00001422
1423 if (getLangOptions().ObjCAutoRefCount) {
1424 // In ARC, annotate delegate init calls.
1425 if (Result->getMethodFamily() == OMF_init &&
1426 (SuperLoc.isValid() || isSelfExpr(Receiver))) {
1427 // Only consider init calls *directly* in init implementations,
1428 // not within blocks.
1429 ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext);
1430 if (method && method->getMethodFamily() == OMF_init) {
1431 // The implicit assignment to self means we also don't want to
1432 // consume the result.
1433 Result->setDelegateInitCall(true);
1434 return Owned(Result);
1435 }
1436 }
1437
1438 // In ARC, check for message sends which are likely to introduce
1439 // retain cycles.
1440 checkRetainCycles(Result);
1441 }
1442
Douglas Gregor2d6b0e92010-05-22 05:17:18 +00001443 return MaybeBindToTemporary(Result);
Douglas Gregor2725ca82010-04-21 19:57:20 +00001444}
1445
1446// ActOnInstanceMessage - used for both unary and keyword messages.
1447// ArgExprs is optional - if it is present, the number of expressions
1448// is obtained from Sel.getNumArgs().
John McCall60d7b3a2010-08-24 06:29:42 +00001449ExprResult Sema::ActOnInstanceMessage(Scope *S,
1450 Expr *Receiver,
1451 Selector Sel,
1452 SourceLocation LBracLoc,
1453 SourceLocation SelectorLoc,
1454 SourceLocation RBracLoc,
1455 MultiExprArg Args) {
Douglas Gregor2725ca82010-04-21 19:57:20 +00001456 if (!Receiver)
1457 return ExprError();
1458
John McCall9ae2f072010-08-23 23:25:46 +00001459 return BuildInstanceMessage(Receiver, Receiver->getType(),
Douglas Gregorf49bb082010-04-22 17:01:48 +00001460 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001461 LBracLoc, SelectorLoc, RBracLoc, move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +00001462}
Chris Lattnereca7be62008-04-07 05:30:13 +00001463
John McCallf85e1932011-06-15 23:02:42 +00001464enum ARCConversionTypeClass {
1465 ACTC_none,
1466 ACTC_retainable,
1467 ACTC_indirectRetainable
1468};
1469static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) {
1470 ARCConversionTypeClass ACTC = ACTC_retainable;
1471
1472 // Ignore an outermost reference type.
1473 if (const ReferenceType *ref = type->getAs<ReferenceType>())
1474 type = ref->getPointeeType();
1475
1476 // Drill through pointers and arrays recursively.
1477 while (true) {
1478 if (const PointerType *ptr = type->getAs<PointerType>()) {
1479 type = ptr->getPointeeType();
1480 } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) {
1481 type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0);
1482 } else {
1483 break;
1484 }
1485 ACTC = ACTC_indirectRetainable;
1486 }
1487
1488 if (!type->isObjCRetainableType()) return ACTC_none;
1489 return ACTC;
1490}
1491
1492namespace {
1493 /// Return true if the given expression can be reasonably converted
1494 /// between a retainable pointer type and a C pointer type.
1495 struct ARCCastChecker : StmtVisitor<ARCCastChecker, bool> {
1496 ASTContext &Context;
1497 ARCCastChecker(ASTContext &Context) : Context(Context) {}
1498 bool VisitStmt(Stmt *s) {
1499 return false;
1500 }
1501 bool VisitExpr(Expr *e) {
1502 return e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
1503 }
1504
1505 bool VisitParenExpr(ParenExpr *e) {
1506 return Visit(e->getSubExpr());
1507 }
1508 bool VisitCastExpr(CastExpr *e) {
1509 switch (e->getCastKind()) {
1510 case CK_NullToPointer:
1511 return true;
1512 case CK_NoOp:
1513 case CK_LValueToRValue:
1514 case CK_BitCast:
1515 case CK_AnyPointerToObjCPointerCast:
1516 case CK_AnyPointerToBlockPointerCast:
1517 return Visit(e->getSubExpr());
1518 default:
1519 return false;
1520 }
1521 }
1522 bool VisitUnaryExtension(UnaryOperator *e) {
1523 return Visit(e->getSubExpr());
1524 }
1525 bool VisitBinComma(BinaryOperator *e) {
1526 return Visit(e->getRHS());
1527 }
1528 bool VisitConditionalOperator(ConditionalOperator *e) {
1529 // Conditional operators are okay if both sides are okay.
1530 return Visit(e->getTrueExpr()) && Visit(e->getFalseExpr());
1531 }
1532 bool VisitObjCStringLiteral(ObjCStringLiteral *e) {
1533 // Always white-list Objective-C string literals.
1534 return true;
1535 }
1536 bool VisitStmtExpr(StmtExpr *e) {
1537 return Visit(e->getSubStmt()->body_back());
1538 }
1539 bool VisitDeclRefExpr(DeclRefExpr *e) {
1540 // White-list references to global extern strings from system
1541 // headers.
1542 if (VarDecl *var = dyn_cast<VarDecl>(e->getDecl()))
1543 if (var->getStorageClass() == SC_Extern &&
1544 var->getType().isConstQualified() &&
1545 Context.getSourceManager().isInSystemHeader(var->getLocation()))
1546 return true;
1547 return false;
1548 }
1549 };
1550}
1551
1552void
1553Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType,
1554 Expr *castExpr, CheckedConversionKind CCK) {
1555 QualType castExprType = castExpr->getType();
1556
1557 ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType);
1558 ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType);
1559 if (exprACTC == castACTC) return;
1560 if (exprACTC && castType->isBooleanType()) return;
1561
1562 // Allow casts between pointers to lifetime types (e.g., __strong id*)
1563 // and pointers to void (e.g., cv void *). Casting from void* to lifetime*
1564 // must be explicit.
1565 if (const PointerType *CastPtr = castType->getAs<PointerType>()) {
1566 if (const PointerType *CastExprPtr = castExprType->getAs<PointerType>()) {
1567 QualType CastPointee = CastPtr->getPointeeType();
1568 QualType CastExprPointee = CastExprPtr->getPointeeType();
1569 if ((CCK != CCK_ImplicitConversion &&
1570 CastPointee->isObjCIndirectLifetimeType() &&
1571 CastExprPointee->isVoidType()) ||
1572 (CastPointee->isVoidType() &&
1573 CastExprPointee->isObjCIndirectLifetimeType()))
1574 return;
1575 }
1576 }
1577
1578 if (ARCCastChecker(Context).Visit(castExpr))
1579 return;
1580
1581 SourceLocation loc =
1582 (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc());
1583
1584 if (makeUnavailableInSystemHeader(loc,
1585 "converts between Objective-C and C pointers in -fobjc-arc"))
1586 return;
1587
1588 unsigned srcKind;
1589 switch (exprACTC) {
1590 case ACTC_none:
1591 srcKind = (castExprType->isPointerType() ? 1 : 0);
1592 break;
1593 case ACTC_retainable:
1594 srcKind = (castExprType->isBlockPointerType() ? 2 : 3);
1595 break;
1596 case ACTC_indirectRetainable:
1597 srcKind = 4;
1598 break;
1599 }
1600
1601 if (CCK == CCK_CStyleCast) {
1602 // Check whether this could be fixed with a bridge cast.
1603 SourceLocation AfterLParen = PP.getLocForEndOfToken(castRange.getBegin());
1604 SourceLocation NoteLoc = AfterLParen.isValid()? AfterLParen : loc;
1605
1606 if (castType->isObjCARCBridgableType() &&
1607 castExprType->isCARCBridgableType()) {
1608 Diag(loc, diag::err_arc_cast_requires_bridge)
1609 << 2
1610 << castExprType
1611 << (castType->isBlockPointerType()? 1 : 0)
1612 << castType
1613 << castRange
1614 << castExpr->getSourceRange();
1615 Diag(NoteLoc, diag::note_arc_bridge)
1616 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1617 Diag(NoteLoc, diag::note_arc_bridge_transfer)
1618 << castExprType
1619 << FixItHint::CreateInsertion(AfterLParen, "__bridge_transfer ");
1620
1621 return;
1622 }
1623
1624 if (castType->isCARCBridgableType() &&
1625 castExprType->isObjCARCBridgableType()){
1626 Diag(loc, diag::err_arc_cast_requires_bridge)
1627 << (castExprType->isBlockPointerType()? 1 : 0)
1628 << castExprType
1629 << 2
1630 << castType
1631 << castRange
1632 << castExpr->getSourceRange();
1633
1634 Diag(NoteLoc, diag::note_arc_bridge)
1635 << FixItHint::CreateInsertion(AfterLParen, "__bridge ");
1636 Diag(NoteLoc, diag::note_arc_bridge_retained)
1637 << castType
1638 << FixItHint::CreateInsertion(AfterLParen, "__bridge_retained ");
1639 return;
1640 }
1641 }
1642
1643 Diag(loc, diag::err_arc_mismatched_cast)
1644 << (CCK != CCK_ImplicitConversion) << srcKind << castExprType << castType
1645 << castRange << castExpr->getSourceRange();
1646}
1647
1648ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc,
1649 ObjCBridgeCastKind Kind,
1650 SourceLocation BridgeKeywordLoc,
1651 TypeSourceInfo *TSInfo,
1652 Expr *SubExpr) {
1653 QualType T = TSInfo->getType();
1654 QualType FromType = SubExpr->getType();
1655
1656 bool MustConsume = false;
1657 if (T->isDependentType() || SubExpr->isTypeDependent()) {
1658 // Okay: we'll build a dependent expression type.
1659 } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) {
1660 // Casting CF -> id
1661 switch (Kind) {
1662 case OBC_Bridge:
1663 break;
1664
1665 case OBC_BridgeRetained:
1666 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1667 << 2
1668 << FromType
1669 << (T->isBlockPointerType()? 1 : 0)
1670 << T
1671 << SubExpr->getSourceRange()
1672 << Kind;
1673 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1674 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge");
1675 Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer)
1676 << FromType
1677 << FixItHint::CreateReplacement(BridgeKeywordLoc,
1678 "__bridge_transfer ");
1679
1680 Kind = OBC_Bridge;
1681 break;
1682
1683 case OBC_BridgeTransfer:
1684 // We must consume the Objective-C object produced by the cast.
1685 MustConsume = true;
1686 break;
1687 }
1688 } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) {
1689 // Okay: id -> CF
1690 switch (Kind) {
1691 case OBC_Bridge:
1692 break;
1693
1694 case OBC_BridgeRetained:
1695 // Produce the object before casting it.
1696 SubExpr = ImplicitCastExpr::Create(Context, FromType,
1697 CK_ObjCProduceObject,
1698 SubExpr, 0, VK_RValue);
1699 break;
1700
1701 case OBC_BridgeTransfer:
1702 Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind)
1703 << (FromType->isBlockPointerType()? 1 : 0)
1704 << FromType
1705 << 2
1706 << T
1707 << SubExpr->getSourceRange()
1708 << Kind;
1709
1710 Diag(BridgeKeywordLoc, diag::note_arc_bridge)
1711 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge ");
1712 Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained)
1713 << T
1714 << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge_retained ");
1715
1716 Kind = OBC_Bridge;
1717 break;
1718 }
1719 } else {
1720 Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible)
1721 << FromType << T << Kind
1722 << SubExpr->getSourceRange()
1723 << TSInfo->getTypeLoc().getSourceRange();
1724 return ExprError();
1725 }
1726
1727 Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind,
1728 BridgeKeywordLoc,
1729 TSInfo, SubExpr);
1730
1731 if (MustConsume) {
1732 ExprNeedsCleanups = true;
1733 Result = ImplicitCastExpr::Create(Context, T, CK_ObjCConsumeObject, Result,
1734 0, VK_RValue);
1735 }
1736
1737 return Result;
1738}
1739
1740ExprResult Sema::ActOnObjCBridgedCast(Scope *S,
1741 SourceLocation LParenLoc,
1742 ObjCBridgeCastKind Kind,
1743 SourceLocation BridgeKeywordLoc,
1744 ParsedType Type,
1745 SourceLocation RParenLoc,
1746 Expr *SubExpr) {
1747 TypeSourceInfo *TSInfo = 0;
1748 QualType T = GetTypeFromParser(Type, &TSInfo);
1749 if (!TSInfo)
1750 TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc);
1751 return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo,
1752 SubExpr);
1753}