blob: e9c391c3e9b01b1e102be684aa8bb1dc5e23ad13 [file] [log] [blame]
Chris Lattner85a932e2008-01-04 22:32:30 +00001//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective-C expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Chris Lattner7f816522010-04-11 07:45:24 +000015#include "Lookup.h"
Chris Lattner85a932e2008-01-04 22:32:30 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/DeclObjC.h"
Steve Narofff494b572008-05-29 21:12:08 +000018#include "clang/AST/ExprObjC.h"
Douglas Gregor2725ca82010-04-21 19:57:20 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner39c28bb2009-02-18 06:48:40 +000020#include "llvm/ADT/SmallString.h"
Steve Naroff61f72cb2009-03-09 21:12:44 +000021#include "clang/Lex/Preprocessor.h"
22
Chris Lattner85a932e2008-01-04 22:32:30 +000023using namespace clang;
24
Mike Stump1eb44332009-09-09 15:08:12 +000025Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
Chris Lattner39c28bb2009-02-18 06:48:40 +000026 ExprTy **strings,
Chris Lattner85a932e2008-01-04 22:32:30 +000027 unsigned NumStrings) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000028 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
29
Chris Lattnerf4b136f2009-02-18 06:13:04 +000030 // Most ObjC strings are formed out of a single piece. However, we *can*
31 // have strings formed out of multiple @ strings with multiple pptokens in
32 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
33 // StringLiteral for ObjCStringLiteral to hold onto.
Chris Lattner39c28bb2009-02-18 06:48:40 +000034 StringLiteral *S = Strings[0];
Mike Stump1eb44332009-09-09 15:08:12 +000035
Chris Lattnerf4b136f2009-02-18 06:13:04 +000036 // If we have a multi-part string, merge it all together.
37 if (NumStrings != 1) {
Chris Lattner85a932e2008-01-04 22:32:30 +000038 // Concatenate objc strings.
Chris Lattner39c28bb2009-02-18 06:48:40 +000039 llvm::SmallString<128> StrBuf;
40 llvm::SmallVector<SourceLocation, 8> StrLocs;
Mike Stump1eb44332009-09-09 15:08:12 +000041
Chris Lattner726e1682009-02-18 05:49:11 +000042 for (unsigned i = 0; i != NumStrings; ++i) {
Chris Lattner39c28bb2009-02-18 06:48:40 +000043 S = Strings[i];
Mike Stump1eb44332009-09-09 15:08:12 +000044
Chris Lattner39c28bb2009-02-18 06:48:40 +000045 // ObjC strings can't be wide.
Chris Lattnerf4b136f2009-02-18 06:13:04 +000046 if (S->isWide()) {
47 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
48 << S->getSourceRange();
49 return true;
50 }
Mike Stump1eb44332009-09-09 15:08:12 +000051
Chris Lattner39c28bb2009-02-18 06:48:40 +000052 // Get the string data.
53 StrBuf.append(S->getStrData(), S->getStrData()+S->getByteLength());
Mike Stump1eb44332009-09-09 15:08:12 +000054
Chris Lattner39c28bb2009-02-18 06:48:40 +000055 // Get the locations of the string tokens.
56 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
Mike Stump1eb44332009-09-09 15:08:12 +000057
Chris Lattner39c28bb2009-02-18 06:48:40 +000058 // Free the temporary string.
Ted Kremenek8189cde2009-02-07 01:47:29 +000059 S->Destroy(Context);
Chris Lattner85a932e2008-01-04 22:32:30 +000060 }
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattner39c28bb2009-02-18 06:48:40 +000062 // Create the aggregate string with the appropriate content and location
63 // information.
64 S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(), false,
Chris Lattner2085fd62009-02-18 06:40:38 +000065 Context.getPointerType(Context.CharTy),
Chris Lattner39c28bb2009-02-18 06:48:40 +000066 &StrLocs[0], StrLocs.size());
Chris Lattner85a932e2008-01-04 22:32:30 +000067 }
Mike Stump1eb44332009-09-09 15:08:12 +000068
Chris Lattner69039812009-02-18 06:01:06 +000069 // Verify that this composite string is acceptable for ObjC strings.
70 if (CheckObjCString(S))
Chris Lattner85a932e2008-01-04 22:32:30 +000071 return true;
Chris Lattnera0af1fe2009-02-18 06:06:56 +000072
73 // Initialize the constant string interface lazily. This assumes
Steve Naroffd9fd7642009-04-07 14:18:33 +000074 // the NSString interface is seen in this translation unit. Note: We
75 // don't use NSConstantString, since the runtime team considers this
76 // interface private (even though it appears in the header files).
Chris Lattnera0af1fe2009-02-18 06:06:56 +000077 QualType Ty = Context.getObjCConstantStringInterface();
78 if (!Ty.isNull()) {
Steve Naroff14108da2009-07-10 23:34:53 +000079 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattner13fd7e52008-06-21 21:44:18 +000080 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +000081 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
Douglas Gregorc83c6872010-04-15 22:33:43 +000082 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
83 LookupOrdinaryName);
Chris Lattnera0af1fe2009-02-18 06:06:56 +000084 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
85 Context.setObjCConstantStringInterface(StrIF);
86 Ty = Context.getObjCConstantStringInterface();
Steve Naroff14108da2009-07-10 23:34:53 +000087 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +000088 } else {
Steve Naroffd9fd7642009-04-07 14:18:33 +000089 // If there is no NSString interface defined then treat constant
Chris Lattnera0af1fe2009-02-18 06:06:56 +000090 // strings as untyped objects and let the runtime figure it out later.
91 Ty = Context.getObjCIdType();
92 }
Chris Lattner13fd7e52008-06-21 21:44:18 +000093 }
Mike Stump1eb44332009-09-09 15:08:12 +000094
Chris Lattnerf4b136f2009-02-18 06:13:04 +000095 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
Chris Lattner85a932e2008-01-04 22:32:30 +000096}
97
Mike Stump1eb44332009-09-09 15:08:12 +000098Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
Douglas Gregor81d34662010-04-20 15:39:42 +000099 TypeSourceInfo *EncodedTypeInfo,
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000100 SourceLocation RParenLoc) {
Douglas Gregor81d34662010-04-20 15:39:42 +0000101 QualType EncodedType = EncodedTypeInfo->getType();
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000102 QualType StrTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000103 if (EncodedType->isDependentType())
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000104 StrTy = Context.DependentTy;
105 else {
106 std::string Str;
107 Context.getObjCEncodingForType(EncodedType, Str);
108
109 // The type of @encode is the same as the type of the corresponding string,
110 // which is an array type.
111 StrTy = Context.CharTy;
112 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
John McCall4b7a8342010-03-15 10:54:44 +0000113 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000114 StrTy.addConst();
115 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
116 ArrayType::Normal, 0);
117 }
Mike Stump1eb44332009-09-09 15:08:12 +0000118
Douglas Gregor81d34662010-04-20 15:39:42 +0000119 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
Anders Carlssonfc0f0212009-06-07 18:45:35 +0000120}
121
Chris Lattner85a932e2008-01-04 22:32:30 +0000122Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
123 SourceLocation EncodeLoc,
124 SourceLocation LParenLoc,
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000125 TypeTy *ty,
Chris Lattner85a932e2008-01-04 22:32:30 +0000126 SourceLocation RParenLoc) {
Argyrios Kyrtzidise8661902009-08-19 01:28:28 +0000127 // FIXME: Preserve type source info ?
Douglas Gregor81d34662010-04-20 15:39:42 +0000128 TypeSourceInfo *TInfo;
129 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
130 if (!TInfo)
131 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
132 PP.getLocForEndOfToken(LParenLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000133
Douglas Gregor81d34662010-04-20 15:39:42 +0000134 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000135}
136
137Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
138 SourceLocation AtLoc,
139 SourceLocation SelLoc,
140 SourceLocation LParenLoc,
141 SourceLocation RParenLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000142 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
Fariborz Jahanian835ed7f2009-08-22 21:13:55 +0000143 SourceRange(LParenLoc, RParenLoc), false);
Fariborz Jahanian7ff22de2009-06-16 16:25:00 +0000144 if (!Method)
145 Method = LookupFactoryMethodInGlobalPool(Sel,
146 SourceRange(LParenLoc, RParenLoc));
147 if (!Method)
148 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
149
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000150 QualType Ty = Context.getObjCSelType();
Daniel Dunbar6d5a1c22010-02-03 20:11:42 +0000151 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000152}
153
154Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
155 SourceLocation AtLoc,
156 SourceLocation ProtoLoc,
157 SourceLocation LParenLoc,
158 SourceLocation RParenLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000159 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000160 if (!PDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000161 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
Chris Lattner85a932e2008-01-04 22:32:30 +0000162 return true;
163 }
Mike Stump1eb44332009-09-09 15:08:12 +0000164
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000165 QualType Ty = Context.getObjCProtoType();
166 if (Ty.isNull())
Chris Lattner85a932e2008-01-04 22:32:30 +0000167 return true;
Steve Naroff14108da2009-07-10 23:34:53 +0000168 Ty = Context.getObjCObjectPointerType(Ty);
Chris Lattnera0af1fe2009-02-18 06:06:56 +0000169 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
Chris Lattner85a932e2008-01-04 22:32:30 +0000170}
171
Mike Stump1eb44332009-09-09 15:08:12 +0000172bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
173 Selector Sel, ObjCMethodDecl *Method,
Chris Lattner077bf5e2008-11-24 03:33:13 +0000174 bool isClassMessage,
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000175 SourceLocation lbrac, SourceLocation rbrac,
Mike Stump1eb44332009-09-09 15:08:12 +0000176 QualType &ReturnType) {
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000177 if (!Method) {
Daniel Dunbar6660c8a2008-09-11 00:04:36 +0000178 // Apply default argument promotion as for (C99 6.5.2.2p6).
179 for (unsigned i = 0; i != NumArgs; i++)
180 DefaultArgumentPromotion(Args[i]);
181
Chris Lattner077bf5e2008-11-24 03:33:13 +0000182 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
183 diag::warn_inst_method_not_found;
184 Diag(lbrac, DiagID)
185 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000186 ReturnType = Context.getObjCIdType();
187 return false;
Daniel Dunbar637cebb2008-09-11 00:01:56 +0000188 }
Mike Stump1eb44332009-09-09 15:08:12 +0000189
Douglas Gregor2725ca82010-04-21 19:57:20 +0000190 ReturnType = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000192 unsigned NumNamedArgs = Sel.getNumArgs();
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000193 // Method might have more arguments than selector indicates. This is due
194 // to addition of c-style arguments in method.
195 if (Method->param_size() > Sel.getNumArgs())
196 NumNamedArgs = Method->param_size();
197 // FIXME. This need be cleaned up.
198 if (NumArgs < NumNamedArgs) {
Eric Christopherd77b9a22010-04-16 04:48:22 +0000199 Diag(lbrac, diag::err_typecheck_call_too_few_args) << 2
200 << NumNamedArgs << NumArgs;
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +0000201 return false;
202 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000203
Chris Lattner312531a2009-04-12 08:11:20 +0000204 bool IsError = false;
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000205 for (unsigned i = 0; i < NumNamedArgs; i++) {
Chris Lattner85a932e2008-01-04 22:32:30 +0000206 Expr *argExpr = Args[i];
207 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
Mike Stump1eb44332009-09-09 15:08:12 +0000208
Chris Lattner89951a82009-02-20 18:43:26 +0000209 QualType lhsType = Method->param_begin()[i]->getType();
Chris Lattner85a932e2008-01-04 22:32:30 +0000210 QualType rhsType = argExpr->getType();
211
Mike Stump1eb44332009-09-09 15:08:12 +0000212 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
Chris Lattner987798a2008-04-02 17:17:33 +0000213 if (lhsType->isArrayType())
214 lhsType = Context.getArrayDecayedType(lhsType);
Chris Lattner85a932e2008-01-04 22:32:30 +0000215 else if (lhsType->isFunctionType())
216 lhsType = Context.getPointerType(lhsType);
217
Mike Stump1eb44332009-09-09 15:08:12 +0000218 AssignConvertType Result =
Chris Lattner987798a2008-04-02 17:17:33 +0000219 CheckSingleAssignmentConstraints(lhsType, argExpr);
Fariborz Jahanianb00ab272010-04-20 20:28:15 +0000220 if (Result == Incompatible && !getLangOptions().CPlusPlus &&
221 CheckTransparentUnionArgumentConstraints(lhsType, argExpr)
222 == Sema::Compatible)
223 Result = Compatible;
224
Chris Lattner85a932e2008-01-04 22:32:30 +0000225 if (Args[i] != argExpr) // The expression was converted.
226 Args[i] = argExpr; // Make sure we store the converted expression.
Mike Stump1eb44332009-09-09 15:08:12 +0000227
228 IsError |=
Chris Lattner85a932e2008-01-04 22:32:30 +0000229 DiagnoseAssignmentResult(Result, argExpr->getLocStart(), lhsType, rhsType,
Douglas Gregor68647482009-12-16 03:45:30 +0000230 argExpr, AA_Sending);
Chris Lattner85a932e2008-01-04 22:32:30 +0000231 }
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000232
233 // Promote additional arguments to variadic methods.
234 if (Method->isVariadic()) {
Anders Carlssondce5e2c2009-01-16 16:48:51 +0000235 for (unsigned i = NumNamedArgs; i < NumArgs; ++i)
Chris Lattner312531a2009-04-12 08:11:20 +0000236 IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod);
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000237 } else {
238 // Check for extra arguments to non-variadic methods.
239 if (NumArgs != NumNamedArgs) {
Mike Stump1eb44332009-09-09 15:08:12 +0000240 Diag(Args[NumNamedArgs]->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000241 diag::err_typecheck_call_too_many_args)
Eric Christopherccfa9632010-04-16 04:56:46 +0000242 << 2 /*method*/ << NumNamedArgs << NumArgs
243 << Method->getSourceRange()
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000244 << SourceRange(Args[NumNamedArgs]->getLocStart(),
245 Args[NumArgs-1]->getLocEnd());
Daniel Dunbar91e19b22008-09-11 00:50:25 +0000246 }
247 }
248
Douglas Gregor2725ca82010-04-21 19:57:20 +0000249 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
Chris Lattner312531a2009-04-12 08:11:20 +0000250 return IsError;
Chris Lattner85a932e2008-01-04 22:32:30 +0000251}
252
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000253bool Sema::isSelfExpr(Expr *RExpr) {
254 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
255 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
256 return true;
257 return false;
258}
259
Steve Narofff1afaf62009-02-26 15:55:06 +0000260// Helper method for ActOnClassMethod/ActOnInstanceMethod.
261// Will search "local" class/category implementations for a method decl.
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000262// If failed, then we search in class's root for an instance method.
Steve Narofff1afaf62009-02-26 15:55:06 +0000263// Returns 0 if no method is found.
Steve Naroff5609ec02009-03-08 18:56:13 +0000264ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
Steve Narofff1afaf62009-02-26 15:55:06 +0000265 ObjCInterfaceDecl *ClassDecl) {
266 ObjCMethodDecl *Method = 0;
Steve Naroff5609ec02009-03-08 18:56:13 +0000267 // lookup in class and all superclasses
268 while (ClassDecl && !Method) {
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000269 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000270 Method = ImpDecl->getClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000271
Steve Naroff5609ec02009-03-08 18:56:13 +0000272 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000273 if (!Method)
274 Method = ClassDecl->getCategoryClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000275
Steve Naroff5609ec02009-03-08 18:56:13 +0000276 // Before we give up, check if the selector is an instance method.
277 // But only in the root. This matches gcc's behaviour and what the
278 // runtime expects.
279 if (!Method && !ClassDecl->getSuperClass()) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000280 Method = ClassDecl->lookupInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000281 // Look through local category implementations associated
Steve Naroff5609ec02009-03-08 18:56:13 +0000282 // with the root class.
Mike Stump1eb44332009-09-09 15:08:12 +0000283 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000284 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
285 }
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Steve Naroff5609ec02009-03-08 18:56:13 +0000287 ClassDecl = ClassDecl->getSuperClass();
Steve Narofff1afaf62009-02-26 15:55:06 +0000288 }
Steve Naroff5609ec02009-03-08 18:56:13 +0000289 return Method;
290}
291
292ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
293 ObjCInterfaceDecl *ClassDecl) {
294 ObjCMethodDecl *Method = 0;
295 while (ClassDecl && !Method) {
296 // If we have implementations in scope, check "private" methods.
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000297 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000298 Method = ImpDecl->getInstanceMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000299
Steve Naroff5609ec02009-03-08 18:56:13 +0000300 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000301 if (!Method)
302 Method = ClassDecl->getCategoryInstanceMethod(Sel);
Steve Naroff5609ec02009-03-08 18:56:13 +0000303 ClassDecl = ClassDecl->getSuperClass();
Fariborz Jahanian175ba1e2009-03-04 18:15:57 +0000304 }
Steve Narofff1afaf62009-02-26 15:55:06 +0000305 return Method;
306}
307
Chris Lattner7f816522010-04-11 07:45:24 +0000308/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
309/// objective C interface. This is a property reference expression.
310Action::OwningExprResult Sema::
311HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000312 Expr *BaseExpr, DeclarationName MemberName,
313 SourceLocation MemberLoc) {
Chris Lattner7f816522010-04-11 07:45:24 +0000314 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
315 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
316 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
317
318 // Search for a declared property first.
319 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
320 // Check whether we can reference this property.
321 if (DiagnoseUseOfDecl(PD, MemberLoc))
322 return ExprError();
323 QualType ResTy = PD->getType();
324 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
325 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
326 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
327 ResTy = Getter->getResultType();
328 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
329 MemberLoc, BaseExpr));
330 }
331 // Check protocols on qualified interfaces.
332 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
333 E = OPT->qual_end(); I != E; ++I)
334 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
335 // Check whether we can reference this property.
336 if (DiagnoseUseOfDecl(PD, MemberLoc))
337 return ExprError();
338
339 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
340 MemberLoc, BaseExpr));
341 }
342 // If that failed, look for an "implicit" property by seeing if the nullary
343 // selector is implemented.
344
345 // FIXME: The logic for looking up nullary and unary selectors should be
346 // shared with the code in ActOnInstanceMessage.
347
348 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
349 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
350
351 // If this reference is in an @implementation, check for 'private' methods.
352 if (!Getter)
353 Getter = IFace->lookupPrivateInstanceMethod(Sel);
354
355 // Look through local category implementations associated with the class.
356 if (!Getter)
357 Getter = IFace->getCategoryInstanceMethod(Sel);
358 if (Getter) {
359 // Check if we can reference this property.
360 if (DiagnoseUseOfDecl(Getter, MemberLoc))
361 return ExprError();
362 }
363 // If we found a getter then this may be a valid dot-reference, we
364 // will look for the matching setter, in case it is needed.
365 Selector SetterSel =
366 SelectorTable::constructSetterName(PP.getIdentifierTable(),
367 PP.getSelectorTable(), Member);
368 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
369 if (!Setter) {
370 // If this reference is in an @implementation, also check for 'private'
371 // methods.
372 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
373 }
374 // Look through local category implementations associated with the class.
375 if (!Setter)
376 Setter = IFace->getCategoryInstanceMethod(SetterSel);
377
378 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
379 return ExprError();
380
381 if (Getter) {
382 QualType PType;
383 PType = Getter->getResultType();
384 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
385 Setter, MemberLoc, BaseExpr));
386 }
387
388 // Attempt to correct for typos in property names.
389 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
Douglas Gregoraaf87162010-04-14 20:04:41 +0000390 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
Chris Lattner7f816522010-04-11 07:45:24 +0000391 Res.getAsSingle<ObjCPropertyDecl>()) {
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000392 DeclarationName TypoResult = Res.getLookupName();
Chris Lattner7f816522010-04-11 07:45:24 +0000393 Diag(MemberLoc, diag::err_property_not_found_suggest)
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000394 << MemberName << QualType(OPT, 0) << TypoResult
395 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
Chris Lattner7f816522010-04-11 07:45:24 +0000396 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
397 Diag(Property->getLocation(), diag::note_previous_decl)
398 << Property->getDeclName();
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000399 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc);
Chris Lattner7f816522010-04-11 07:45:24 +0000400 }
Chris Lattnerb9d4fc12010-04-11 07:51:10 +0000401
Chris Lattner7f816522010-04-11 07:45:24 +0000402 Diag(MemberLoc, diag::err_property_not_found)
403 << MemberName << QualType(OPT, 0);
404 if (Setter && !Getter)
405 Diag(Setter->getLocation(), diag::note_getter_unavailable)
406 << MemberName << BaseExpr->getSourceRange();
407 return ExprError();
Chris Lattner7f816522010-04-11 07:45:24 +0000408}
409
410
411
Chris Lattnereb483eb2010-04-11 08:28:14 +0000412Action::OwningExprResult Sema::
413ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
414 IdentifierInfo &propertyName,
415 SourceLocation receiverNameLoc,
416 SourceLocation propertyNameLoc) {
Mike Stump1eb44332009-09-09 15:08:12 +0000417
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000418 IdentifierInfo *receiverNamePtr = &receiverName;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000419 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
420 receiverNameLoc);
Chris Lattnereb483eb2010-04-11 08:28:14 +0000421 if (IFace == 0) {
422 // If the "receiver" is 'super' in a method, handle it as an expression-like
423 // property reference.
424 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
425 if (receiverNamePtr->isStr("super")) {
426 if (CurMethod->isInstanceMethod()) {
427 QualType T =
428 Context.getObjCInterfaceType(CurMethod->getClassInterface());
429 T = Context.getObjCObjectPointerType(T);
430 Expr *SuperExpr = new (Context) ObjCSuperExpr(receiverNameLoc, T);
431
432 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
433 SuperExpr, &propertyName,
434 propertyNameLoc);
435 }
Mike Stump1eb44332009-09-09 15:08:12 +0000436
Chris Lattnereb483eb2010-04-11 08:28:14 +0000437 // Otherwise, if this is a class method, try dispatching to our
438 // superclass.
439 IFace = CurMethod->getClassInterface()->getSuperClass();
440 }
441
442 if (IFace == 0) {
443 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
444 return ExprError();
445 }
446 }
447
448 // Search for a declared property first.
Steve Naroff61f72cb2009-03-09 21:12:44 +0000449 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000450 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000451
452 // If this reference is in an @implementation, check for 'private' methods.
453 if (!Getter)
454 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
455 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000456 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000457 Getter = ImpDecl->getClassMethod(Sel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000458
459 if (Getter) {
460 // FIXME: refactor/share with ActOnMemberReference().
461 // Check if we can reference this property.
462 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
463 return ExprError();
464 }
Mike Stump1eb44332009-09-09 15:08:12 +0000465
Steve Naroff61f72cb2009-03-09 21:12:44 +0000466 // Look for the matching setter, in case it is needed.
Mike Stump1eb44332009-09-09 15:08:12 +0000467 Selector SetterSel =
468 SelectorTable::constructSetterName(PP.getIdentifierTable(),
Steve Narofffdc92b72009-03-10 17:24:38 +0000469 PP.getSelectorTable(), &propertyName);
Mike Stump1eb44332009-09-09 15:08:12 +0000470
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000471 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000472 if (!Setter) {
473 // If this reference is in an @implementation, also check for 'private'
474 // methods.
475 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
476 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +0000477 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000478 Setter = ImpDecl->getClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000479 }
480 // Look through local category implementations associated with the class.
Argyrios Kyrtzidis1cb35dd2009-07-21 00:06:20 +0000481 if (!Setter)
482 Setter = IFace->getCategoryClassMethod(SetterSel);
Steve Naroff61f72cb2009-03-09 21:12:44 +0000483
484 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
485 return ExprError();
486
487 if (Getter || Setter) {
488 QualType PType;
489
490 if (Getter)
491 PType = Getter->getResultType();
492 else {
493 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
494 E = Setter->param_end(); PI != E; ++PI)
495 PType = (*PI)->getType();
496 }
Fariborz Jahanian09105f52009-08-20 17:02:02 +0000497 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(
Mike Stump1eb44332009-09-09 15:08:12 +0000498 Getter, PType, Setter,
Steve Naroff61f72cb2009-03-09 21:12:44 +0000499 propertyNameLoc, IFace, receiverNameLoc));
500 }
501 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
502 << &propertyName << Context.getObjCInterfaceType(IFace));
503}
504
Douglas Gregor47bd5432010-04-14 02:46:37 +0000505Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
506 IdentifierInfo *&Name,
507 SourceLocation NameLoc,
508 bool IsSuper,
509 bool HasTrailingDot) {
510 // If the identifier is "super" and there is no trailing dot, we're
511 // messaging super.
512 if (IsSuper && !HasTrailingDot && S->isInObjcMethodScope())
513 return ObjCSuperMessage;
514
515 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
516 LookupName(Result, S);
517
518 switch (Result.getResultKind()) {
519 case LookupResult::NotFound:
Douglas Gregored464422010-04-19 20:09:36 +0000520 // Normal name lookup didn't find anything. If we're in an
521 // Objective-C method, look for ivars. If we find one, we're done!
522 // FIXME: This is a hack. Ivar lookup should be part of normal lookup.
523 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
524 ObjCInterfaceDecl *ClassDeclared;
525 if (Method->getClassInterface()->lookupInstanceVariable(Name,
526 ClassDeclared))
527 return ObjCInstanceMessage;
528 }
529
Douglas Gregor47bd5432010-04-14 02:46:37 +0000530 // Break out; we'll perform typo correction below.
531 break;
532
533 case LookupResult::NotFoundInCurrentInstantiation:
534 case LookupResult::FoundOverloaded:
535 case LookupResult::FoundUnresolvedValue:
536 case LookupResult::Ambiguous:
537 Result.suppressDiagnostics();
538 return ObjCInstanceMessage;
539
540 case LookupResult::Found: {
541 // We found something. If it's a type, then we have a class
542 // message. Otherwise, it's an instance message.
543 NamedDecl *ND = Result.getFoundDecl();
544 if (isa<ObjCInterfaceDecl>(ND) || isa<TypeDecl>(ND) ||
545 isa<UnresolvedUsingTypenameDecl>(ND))
546 return ObjCClassMessage;
547
548 return ObjCInstanceMessage;
549 }
550 }
551
Douglas Gregoraaf87162010-04-14 20:04:41 +0000552 // Determine our typo-correction context.
553 CorrectTypoContext CTC = CTC_Expression;
554 if (ObjCMethodDecl *Method = getCurMethodDecl())
555 if (Method->getClassInterface() &&
556 Method->getClassInterface()->getSuperClass())
557 CTC = CTC_ObjCMessageReceiver;
558
559 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
560 if (Result.isSingleResult()) {
561 // If we found a declaration, correct when it refers to an Objective-C
562 // class.
563 NamedDecl *ND = Result.getFoundDecl();
564 if (isa<ObjCInterfaceDecl>(ND)) {
565 Diag(NameLoc, diag::err_unknown_receiver_suggest)
566 << Name << Result.getLookupName()
567 << FixItHint::CreateReplacement(SourceRange(NameLoc),
568 ND->getNameAsString());
569 Diag(ND->getLocation(), diag::note_previous_decl)
570 << Corrected;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000571
Douglas Gregoraaf87162010-04-14 20:04:41 +0000572 Name = ND->getIdentifier();
573 return ObjCClassMessage;
574 }
575 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
576 Corrected.getAsIdentifierInfo()->isStr("super")) {
577 // If we've found the keyword "super", this is a send to super.
578 Diag(NameLoc, diag::err_unknown_receiver_suggest)
579 << Name << Corrected
580 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
581 Name = Corrected.getAsIdentifierInfo();
582 return ObjCSuperMessage;
Douglas Gregor47bd5432010-04-14 02:46:37 +0000583 }
584 }
585
586 // Fall back: let the parser try to parse it as an instance message.
587 return ObjCInstanceMessage;
588}
Steve Naroff61f72cb2009-03-09 21:12:44 +0000589
Douglas Gregor2725ca82010-04-21 19:57:20 +0000590Sema::OwningExprResult Sema::ActOnSuperMessage(Scope *S,
591 SourceLocation SuperLoc,
592 Selector Sel,
593 SourceLocation LBracLoc,
594 SourceLocation SelectorLoc,
595 SourceLocation RBracLoc,
596 MultiExprArg Args) {
597 // Determine whether we are inside a method or not.
598 ObjCMethodDecl *Method = getCurMethodDecl();
Douglas Gregorf95861a2010-04-21 20:01:04 +0000599 if (!Method) {
600 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
601 return ExprError();
602 }
Chris Lattner85a932e2008-01-04 22:32:30 +0000603
Douglas Gregorf95861a2010-04-21 20:01:04 +0000604 ObjCInterfaceDecl *Class = Method->getClassInterface();
605 if (!Class) {
606 Diag(SuperLoc, diag::error_no_super_class_message)
607 << Method->getDeclName();
608 return ExprError();
609 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000610
Douglas Gregorf95861a2010-04-21 20:01:04 +0000611 ObjCInterfaceDecl *Super = Class->getSuperClass();
612 if (!Super) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000613 // The current class does not have a superclass.
614 Diag(SuperLoc, diag::error_no_super_class) << Class->getIdentifier();
615 return ExprError();
Chris Lattner15faee12010-04-12 05:38:43 +0000616 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000617
Douglas Gregorf95861a2010-04-21 20:01:04 +0000618 // We are in a method whose class has a superclass, so 'super'
619 // is acting as a keyword.
620 if (Method->isInstanceMethod()) {
621 // Since we are in an instance method, this is an instance
622 // message to the superclass instance.
623 QualType SuperTy = Context.getObjCInterfaceType(Super);
624 SuperTy = Context.getObjCObjectPointerType(SuperTy);
625 return BuildInstanceMessage(ExprArg(*this), SuperTy, SuperLoc,
626 Sel, LBracLoc, SelectorLoc, RBracLoc,
627 move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000628 }
Douglas Gregorf95861a2010-04-21 20:01:04 +0000629
630 // Since we are in a class method, this is a class message to
631 // the superclass.
632 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
633 Context.getObjCInterfaceType(Super),
634 SuperLoc, Sel, LBracLoc, SelectorLoc,
635 RBracLoc, move(Args));
Douglas Gregor2725ca82010-04-21 19:57:20 +0000636}
637
638/// \brief Build an Objective-C class message expression.
639///
640/// This routine takes care of both normal class messages and
641/// class messages to the superclass.
642///
643/// \param ReceiverTypeInfo Type source information that describes the
644/// receiver of this message. This may be NULL, in which case we are
645/// sending to the superclass and \p SuperLoc must be a valid source
646/// location.
647
648/// \param ReceiverType The type of the object receiving the
649/// message. When \p ReceiverTypeInfo is non-NULL, this is the same
650/// type as that refers to. For a superclass send, this is the type of
651/// the superclass.
652///
653/// \param SuperLoc The location of the "super" keyword in a
654/// superclass message.
655///
656/// \param Sel The selector to which the message is being sent.
657///
658/// \param LBracLoc The location of the opening square bracket ']'.
659///
660/// \param SelectorLoc The location of the first identifier in the selector.
661///
662/// \param RBrac The location of the closing square bracket ']'.
663///
664/// \param Args The message arguments.
665Sema::OwningExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
666 QualType ReceiverType,
667 SourceLocation SuperLoc,
668 Selector Sel,
669 SourceLocation LBracLoc,
670 SourceLocation SelectorLoc,
671 SourceLocation RBracLoc,
672 MultiExprArg ArgsIn) {
673 assert(!ReceiverType->isDependentType() &&
674 "Dependent class messages not yet implemented");
Chris Lattner15faee12010-04-12 05:38:43 +0000675
Douglas Gregor2725ca82010-04-21 19:57:20 +0000676 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
677 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Douglas Gregor2725ca82010-04-21 19:57:20 +0000679 // Find the class to which we are sending this message.
680 ObjCInterfaceDecl *Class = 0;
681 if (const ObjCInterfaceType *ClassType
682 = ReceiverType->getAs<ObjCInterfaceType>())
683 Class = ClassType->getDecl();
684 else {
685 Diag(Loc, diag::err_invalid_receiver_class_message)
686 << ReceiverType;
687 return ExprError();
Steve Naroff7c778f12008-07-25 19:39:00 +0000688 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000689 assert(Class && "We don't know which class we're messaging?");
690
691 // Find the method we are messaging.
Steve Naroffcb28be62008-06-04 23:08:38 +0000692 ObjCMethodDecl *Method = 0;
Douglas Gregor2725ca82010-04-21 19:57:20 +0000693 if (Class->isForwardDecl()) {
694 // A forward class used in messaging is treated as a 'Class'
695 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
696 Method = LookupFactoryMethodInGlobalPool(Sel,
697 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian89bc3142009-05-08 23:02:36 +0000698 if (Method)
Mike Stump1eb44332009-09-09 15:08:12 +0000699 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
Fariborz Jahanian9f8f0262009-05-08 23:45:49 +0000700 << Method->getDeclName();
Fariborz Jahanian89bc3142009-05-08 23:02:36 +0000701 }
702 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000703 Method = Class->lookupClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Steve Naroff7c778f12008-07-25 19:39:00 +0000705 // If we have an implementation in scope, check "private" methods.
Steve Narofff1afaf62009-02-26 15:55:06 +0000706 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000707 Method = LookupPrivateClassMethod(Sel, Class);
Steve Naroff7c778f12008-07-25 19:39:00 +0000708
Douglas Gregor2725ca82010-04-21 19:57:20 +0000709 if (Method && DiagnoseUseOfDecl(Method, Loc))
710 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Douglas Gregor2725ca82010-04-21 19:57:20 +0000712 // Check the argument types and determine the result type.
713 QualType ReturnType;
714 unsigned NumArgs = ArgsIn.size();
715 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
716 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
717 LBracLoc, RBracLoc, ReturnType)) {
718 for (unsigned I = 0; I != NumArgs; ++I)
719 Args[I]->Destroy(Context);
720 return ExprError();
721 }
Ted Kremenek4df728e2008-06-24 15:50:53 +0000722
Douglas Gregor2725ca82010-04-21 19:57:20 +0000723 // Construct the appropriate ObjCMessageExpr.
724 if (SuperLoc.isValid())
725 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
726 SuperLoc, /*IsInstanceSuper=*/false,
727 ReceiverType, Sel, Method, Args,
728 NumArgs, RBracLoc));
Mike Stump1eb44332009-09-09 15:08:12 +0000729
Douglas Gregor2725ca82010-04-21 19:57:20 +0000730 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
731 ReceiverTypeInfo, Sel, Method, Args,
732 NumArgs, RBracLoc));
Chris Lattner85a932e2008-01-04 22:32:30 +0000733}
734
Douglas Gregor2725ca82010-04-21 19:57:20 +0000735// ActOnClassMessage - used for both unary and keyword messages.
Chris Lattner85a932e2008-01-04 22:32:30 +0000736// ArgExprs is optional - if it is present, the number of expressions
737// is obtained from Sel.getNumArgs().
Douglas Gregor2725ca82010-04-21 19:57:20 +0000738Sema::OwningExprResult Sema::ActOnClassMessage(Scope *S,
739 TypeTy *Receiver,
740 Selector Sel,
741 SourceLocation LBracLoc,
742 SourceLocation SelectorLoc,
743 SourceLocation RBracLoc,
744 MultiExprArg Args) {
745 TypeSourceInfo *ReceiverTypeInfo;
746 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
747 if (ReceiverType.isNull())
748 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +0000749
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Douglas Gregor2725ca82010-04-21 19:57:20 +0000751 if (!ReceiverTypeInfo)
752 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
753
754 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
755 /*SuperLoc=*/SourceLocation(), Sel,
756 LBracLoc, SelectorLoc, RBracLoc, move(Args));
757}
758
759/// \brief Build an Objective-C instance message expression.
760///
761/// This routine takes care of both normal instance messages and
762/// instance messages to the superclass instance.
763///
764/// \param Receiver The expression that computes the object that will
765/// receive this message. This may be empty, in which case we are
766/// sending to the superclass instance and \p SuperLoc must be a valid
767/// source location.
768///
769/// \param ReceiverType The (static) type of the object receiving the
770/// message. When a \p Receiver expression is provided, this is the
771/// same type as that expression. For a superclass instance send, this
772/// is a pointer to the type of the superclass.
773///
774/// \param SuperLoc The location of the "super" keyword in a
775/// superclass instance message.
776///
777/// \param Sel The selector to which the message is being sent.
778///
779/// \param LBracLoc The location of the opening square bracket ']'.
780///
781/// \param SelectorLoc The location of the first identifier in the selector.
782///
783/// \param RBrac The location of the closing square bracket ']'.
784///
785/// \param Args The message arguments.
786Sema::OwningExprResult Sema::BuildInstanceMessage(ExprArg ReceiverE,
787 QualType ReceiverType,
788 SourceLocation SuperLoc,
789 Selector Sel,
790 SourceLocation LBracLoc,
791 SourceLocation SelectorLoc,
792 SourceLocation RBracLoc,
793 MultiExprArg ArgsIn) {
794 // If we have a receiver expression, perform appropriate promotions
795 // and determine receiver type.
796 Expr *Receiver = ReceiverE.takeAs<Expr>();
797 if (Receiver) {
798 // If necessary, apply function/array conversion to the receiver.
799 // C99 6.7.5.3p[7,8].
800 DefaultFunctionArrayLvalueConversion(Receiver);
801 ReceiverType = Receiver->getType();
802 }
803
804 // The location of the receiver.
805 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000806
Douglas Gregor04badcf2010-04-21 00:45:42 +0000807 ObjCMethodDecl *Method = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000808 // Handle messages to id.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000809 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType() ||
810 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
811 Method = LookupInstanceMethodInGlobalPool(Sel,
812 SourceRange(LBracLoc, RBracLoc));
Chris Lattner6e10a082008-02-01 06:57:39 +0000813 if (!Method)
Douglas Gregor2725ca82010-04-21 19:57:20 +0000814 Method = LookupFactoryMethodInGlobalPool(Sel,
815 SourceRange(LBracLoc, RBracLoc));
816 } else if (ReceiverType->isObjCClassType() ||
817 ReceiverType->isObjCQualifiedClassType()) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000818 // Handle messages to Class.
Chris Lattner6562fda2008-07-21 06:44:27 +0000819 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
Steve Naroffd526c2f2009-02-23 02:25:40 +0000820 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
821 // First check the public methods in the class interface.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000822 Method = ClassDecl->lookupClassMethod(Sel);
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Steve Narofff1afaf62009-02-26 15:55:06 +0000824 if (!Method)
Steve Naroff5609ec02009-03-08 18:56:13 +0000825 Method = LookupPrivateClassMethod(Sel, ClassDecl);
Mike Stump1eb44332009-09-09 15:08:12 +0000826
827 // FIXME: if we still haven't found a method, we need to look in
Steve Naroff470301b2009-07-22 16:07:01 +0000828 // protocols (if we have qualifiers).
Steve Naroffd526c2f2009-02-23 02:25:40 +0000829 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000830 if (Method && DiagnoseUseOfDecl(Method, Loc))
831 return ExprError();
Steve Naroffd526c2f2009-02-23 02:25:40 +0000832 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000833 if (!Method) {
834 // If not messaging 'self', look for any factory method named 'Sel'.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000835 if (!Receiver || !isSelfExpr(Receiver)) {
836 Method = LookupFactoryMethodInGlobalPool(Sel,
837 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanianb1006c72009-03-04 17:50:39 +0000838 if (!Method) {
Fariborz Jahanian041f2fd2009-05-05 18:34:37 +0000839 // If no class (factory) method was found, check if an _instance_
840 // method of the same name exists in the root class only.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000841 Method = LookupInstanceMethodInGlobalPool(Sel,
842 SourceRange(LBracLoc, RBracLoc));
Fariborz Jahanian041f2fd2009-05-05 18:34:37 +0000843 if (Method)
844 if (const ObjCInterfaceDecl *ID =
845 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
846 if (ID->getSuperClass())
Douglas Gregor2725ca82010-04-21 19:57:20 +0000847 Diag(Loc, diag::warn_root_inst_method_not_found)
848 << Sel << SourceRange(LBracLoc, RBracLoc);
Fariborz Jahanian041f2fd2009-05-05 18:34:37 +0000849 }
Fariborz Jahanianb1006c72009-03-04 17:50:39 +0000850 }
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000851 }
852 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000853 } else {
854 ObjCInterfaceDecl* ClassDecl = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000855
Douglas Gregor04badcf2010-04-21 00:45:42 +0000856 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
857 // long as one of the protocols implements the selector (if not, warn).
Douglas Gregor2725ca82010-04-21 19:57:20 +0000858 if (const ObjCObjectPointerType *QIdTy
859 = ReceiverType->getAsObjCQualifiedIdType()) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000860 // Search protocols for instance methods.
861 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
862 E = QIdTy->qual_end(); I != E; ++I) {
863 ObjCProtocolDecl *PDecl = *I;
864 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
865 break;
866 // Since we aren't supporting "Class<foo>", look for a class method.
867 if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
Chris Lattner85a932e2008-01-04 22:32:30 +0000868 break;
869 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000870 } else if (const ObjCObjectPointerType *OCIType
871 = ReceiverType->getAsObjCInterfacePointerType()) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000872 // We allow sending a message to a pointer to an interface (an object).
Douglas Gregor04badcf2010-04-21 00:45:42 +0000873 ClassDecl = OCIType->getInterfaceDecl();
874 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
875 // faster than the following method (which can do *many* linear searches).
876 // The idea is to add class info to InstanceMethodPool.
877 Method = ClassDecl->lookupInstanceMethod(Sel);
878
879 if (!Method) {
880 // Search protocol qualifiers.
881 for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(),
882 E = OCIType->qual_end(); QI != E; ++QI) {
883 if ((Method = (*QI)->lookupInstanceMethod(Sel)))
884 break;
Steve Naroff6b9dfd42009-03-04 15:11:40 +0000885 }
Fariborz Jahanian268bc8c2009-03-03 22:19:15 +0000886 }
Douglas Gregor04badcf2010-04-21 00:45:42 +0000887 if (!Method) {
888 // If we have implementations in scope, check "private" methods.
889 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
890
Douglas Gregor2725ca82010-04-21 19:57:20 +0000891 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000892 // If we still haven't found a method, look in the global pool. This
893 // behavior isn't very desirable, however we need it for GCC
894 // compatibility. FIXME: should we deviate??
895 if (OCIType->qual_empty()) {
Douglas Gregor2725ca82010-04-21 19:57:20 +0000896 Method = LookupInstanceMethodInGlobalPool(Sel,
897 SourceRange(LBracLoc, RBracLoc));
Douglas Gregor04badcf2010-04-21 00:45:42 +0000898 if (Method && !OCIType->getInterfaceDecl()->isForwardDecl())
Douglas Gregor2725ca82010-04-21 19:57:20 +0000899 Diag(Loc, diag::warn_maynot_respond)
Douglas Gregor04badcf2010-04-21 00:45:42 +0000900 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
901 }
902 }
903 }
Douglas Gregor2725ca82010-04-21 19:57:20 +0000904 if (Method && DiagnoseUseOfDecl(Method, Loc))
905 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000906 } else if (!Context.getObjCIdType().isNull() &&
Douglas Gregor2725ca82010-04-21 19:57:20 +0000907 (ReceiverType->isPointerType() ||
908 (ReceiverType->isIntegerType() &&
909 ReceiverType->isScalarType()))) {
Douglas Gregor04badcf2010-04-21 00:45:42 +0000910 // Implicitly convert integers and pointers to 'id' but emit a warning.
Douglas Gregor2725ca82010-04-21 19:57:20 +0000911 Diag(Loc, diag::warn_bad_receiver_type)
912 << ReceiverType
913 << Receiver->getSourceRange();
914 if (ReceiverType->isPointerType())
915 ImpCastExprToType(Receiver, Context.getObjCIdType(),
916 CastExpr::CK_BitCast);
Douglas Gregor04badcf2010-04-21 00:45:42 +0000917 else
Douglas Gregor2725ca82010-04-21 19:57:20 +0000918 ImpCastExprToType(Receiver, Context.getObjCIdType(),
Douglas Gregor04badcf2010-04-21 00:45:42 +0000919 CastExpr::CK_IntegralToPointer);
Douglas Gregor2725ca82010-04-21 19:57:20 +0000920 ReceiverType = Receiver->getType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000921 } else {
922 // Reject other random receiver types (e.g. structs).
Douglas Gregor2725ca82010-04-21 19:57:20 +0000923 Diag(Loc, diag::err_bad_receiver_type)
924 << ReceiverType << Receiver->getSourceRange();
925 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000926 }
Chris Lattnerfe1a5532008-07-21 05:57:44 +0000927 }
Mike Stump1eb44332009-09-09 15:08:12 +0000928
Douglas Gregor2725ca82010-04-21 19:57:20 +0000929 // Check the message arguments.
930 unsigned NumArgs = ArgsIn.size();
931 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
932 QualType ReturnType;
933 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, false,
934 LBracLoc, RBracLoc, ReturnType))
935 return ExprError();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000936
Douglas Gregor2725ca82010-04-21 19:57:20 +0000937 // Construct the appropriate ObjCMessageExpr instance.
938 if (SuperLoc.isValid())
939 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
940 SuperLoc, /*IsInstanceSuper=*/true,
941 ReceiverType, Sel, Method,
942 Args, NumArgs, RBracLoc));
Douglas Gregor04badcf2010-04-21 00:45:42 +0000943
Douglas Gregor2725ca82010-04-21 19:57:20 +0000944 return Owned(ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, Receiver,
945 Sel, Method, Args, NumArgs, RBracLoc));
946}
947
948// ActOnInstanceMessage - used for both unary and keyword messages.
949// ArgExprs is optional - if it is present, the number of expressions
950// is obtained from Sel.getNumArgs().
951Sema::OwningExprResult Sema::ActOnInstanceMessage(Scope *S,
952 ExprArg ReceiverE,
953 Selector Sel,
954 SourceLocation LBracLoc,
955 SourceLocation SelectorLoc,
956 SourceLocation RBracLoc,
957 MultiExprArg Args) {
958 Expr *Receiver = static_cast<Expr *>(ReceiverE.get());
959 if (!Receiver)
960 return ExprError();
961
962 return BuildInstanceMessage(move(ReceiverE), Receiver->getType(),
963 /*SuperLoc=*/SourceLocation(),
964 Sel, LBracLoc, SelectorLoc, RBracLoc,
965 move(Args));
Chris Lattner85a932e2008-01-04 22:32:30 +0000966}
Chris Lattnereca7be62008-04-07 05:30:13 +0000967