1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for Objective-C expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Lookup.h"
16 #include "clang/Sema/Scope.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "clang/Lex/Preprocessor.h"
25 using namespace clang;
27 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
29 unsigned NumStrings) {
30 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
32 // Most ObjC strings are formed out of a single piece. However, we *can*
33 // have strings formed out of multiple @ strings with multiple pptokens in
34 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
35 // StringLiteral for ObjCStringLiteral to hold onto.
36 StringLiteral *S = Strings[0];
38 // If we have a multi-part string, merge it all together.
39 if (NumStrings != 1) {
40 // Concatenate objc strings.
41 llvm::SmallString<128> StrBuf;
42 llvm::SmallVector<SourceLocation, 8> StrLocs;
44 for (unsigned i = 0; i != NumStrings; ++i) {
47 // ObjC strings can't be wide.
49 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
50 << S->getSourceRange();
55 StrBuf += S->getString();
57 // Get the locations of the string tokens.
58 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
61 // Create the aggregate string with the appropriate content and location
63 S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(), false,
64 Context.getPointerType(Context.CharTy),
65 &StrLocs[0], StrLocs.size());
68 // Verify that this composite string is acceptable for ObjC strings.
69 if (CheckObjCString(S))
72 // Initialize the constant string interface lazily. This assumes
73 // the NSString interface is seen in this translation unit. Note: We
74 // don't use NSConstantString, since the runtime team considers this
75 // interface private (even though it appears in the header files).
76 QualType Ty = Context.getObjCConstantStringInterface();
78 Ty = Context.getObjCObjectPointerType(Ty);
79 } else if (getLangOptions().NoConstantCFStrings) {
80 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
81 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
83 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
84 Context.setObjCConstantStringInterface(StrIF);
85 Ty = Context.getObjCConstantStringInterface();
86 Ty = Context.getObjCObjectPointerType(Ty);
88 // If there is no NSConstantString interface defined then treat this
89 // as error and recover from it.
90 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
91 << S->getSourceRange();
92 Ty = Context.getObjCIdType();
95 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
96 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
98 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
99 Context.setObjCConstantStringInterface(StrIF);
100 Ty = Context.getObjCConstantStringInterface();
101 Ty = Context.getObjCObjectPointerType(Ty);
103 // If there is no NSString interface defined then treat constant
104 // strings as untyped objects and let the runtime figure it out later.
105 Ty = Context.getObjCIdType();
109 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
112 Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
113 TypeSourceInfo *EncodedTypeInfo,
114 SourceLocation RParenLoc) {
115 QualType EncodedType = EncodedTypeInfo->getType();
117 if (EncodedType->isDependentType())
118 StrTy = Context.DependentTy;
121 Context.getObjCEncodingForType(EncodedType, Str);
123 // The type of @encode is the same as the type of the corresponding string,
124 // which is an array type.
125 StrTy = Context.CharTy;
126 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
127 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
129 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
130 ArrayType::Normal, 0);
133 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
136 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
137 SourceLocation EncodeLoc,
138 SourceLocation LParenLoc,
140 SourceLocation RParenLoc) {
141 // FIXME: Preserve type source info ?
142 TypeSourceInfo *TInfo;
143 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
145 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
146 PP.getLocForEndOfToken(LParenLoc));
148 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
151 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
152 SourceLocation AtLoc,
153 SourceLocation SelLoc,
154 SourceLocation LParenLoc,
155 SourceLocation RParenLoc) {
156 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
157 SourceRange(LParenLoc, RParenLoc), false, false);
159 Method = LookupFactoryMethodInGlobalPool(Sel,
160 SourceRange(LParenLoc, RParenLoc));
162 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
164 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
165 = ReferencedSelectors.find(Sel);
166 if (Pos == ReferencedSelectors.end())
167 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
169 QualType Ty = Context.getObjCSelType();
170 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
173 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
174 SourceLocation AtLoc,
175 SourceLocation ProtoLoc,
176 SourceLocation LParenLoc,
177 SourceLocation RParenLoc) {
178 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
180 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
184 QualType Ty = Context.getObjCProtoType();
187 Ty = Context.getObjCObjectPointerType(Ty);
188 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
191 bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
192 Selector Sel, ObjCMethodDecl *Method,
194 SourceLocation lbrac, SourceLocation rbrac,
195 QualType &ReturnType) {
197 // Apply default argument promotion as for (C99 6.5.2.2p6).
198 for (unsigned i = 0; i != NumArgs; i++) {
199 if (Args[i]->isTypeDependent())
202 DefaultArgumentPromotion(Args[i]);
205 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
206 diag::warn_inst_method_not_found;
208 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
209 ReturnType = Context.getObjCIdType();
213 ReturnType = Method->getSendResultType();
215 unsigned NumNamedArgs = Sel.getNumArgs();
216 // Method might have more arguments than selector indicates. This is due
217 // to addition of c-style arguments in method.
218 if (Method->param_size() > Sel.getNumArgs())
219 NumNamedArgs = Method->param_size();
220 // FIXME. This need be cleaned up.
221 if (NumArgs < NumNamedArgs) {
222 Diag(lbrac, diag::err_typecheck_call_too_few_args) << 2
223 << NumNamedArgs << NumArgs;
227 bool IsError = false;
228 for (unsigned i = 0; i < NumNamedArgs; i++) {
229 // We can't do any type-checking on a type-dependent argument.
230 if (Args[i]->isTypeDependent())
233 Expr *argExpr = Args[i];
235 ParmVarDecl *Param = Method->param_begin()[i];
236 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
238 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
240 PDiag(diag::err_call_incomplete_argument)
241 << argExpr->getSourceRange()))
244 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
245 ExprResult ArgE = PerformCopyInitialization(Entity,
247 Owned(argExpr->Retain()));
248 if (ArgE.isInvalid())
251 Args[i] = ArgE.takeAs<Expr>();
254 // Promote additional arguments to variadic methods.
255 if (Method->isVariadic()) {
256 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
257 if (Args[i]->isTypeDependent())
260 IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
263 // Check for extra arguments to non-variadic methods.
264 if (NumArgs != NumNamedArgs) {
265 Diag(Args[NumNamedArgs]->getLocStart(),
266 diag::err_typecheck_call_too_many_args)
267 << 2 /*method*/ << NumNamedArgs << NumArgs
268 << Method->getSourceRange()
269 << SourceRange(Args[NumNamedArgs]->getLocStart(),
270 Args[NumArgs-1]->getLocEnd());
274 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
278 bool Sema::isSelfExpr(Expr *RExpr) {
279 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
280 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
285 // Helper method for ActOnClassMethod/ActOnInstanceMethod.
286 // Will search "local" class/category implementations for a method decl.
287 // If failed, then we search in class's root for an instance method.
288 // Returns 0 if no method is found.
289 ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
290 ObjCInterfaceDecl *ClassDecl) {
291 ObjCMethodDecl *Method = 0;
292 // lookup in class and all superclasses
293 while (ClassDecl && !Method) {
294 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
295 Method = ImpDecl->getClassMethod(Sel);
297 // Look through local category implementations associated with the class.
299 Method = ClassDecl->getCategoryClassMethod(Sel);
301 // Before we give up, check if the selector is an instance method.
302 // But only in the root. This matches gcc's behaviour and what the
304 if (!Method && !ClassDecl->getSuperClass()) {
305 Method = ClassDecl->lookupInstanceMethod(Sel);
306 // Look through local category implementations associated
307 // with the root class.
309 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
312 ClassDecl = ClassDecl->getSuperClass();
317 ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
318 ObjCInterfaceDecl *ClassDecl) {
319 ObjCMethodDecl *Method = 0;
320 while (ClassDecl && !Method) {
321 // If we have implementations in scope, check "private" methods.
322 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
323 Method = ImpDecl->getInstanceMethod(Sel);
325 // Look through local category implementations associated with the class.
327 Method = ClassDecl->getCategoryInstanceMethod(Sel);
328 ClassDecl = ClassDecl->getSuperClass();
333 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
334 /// objective C interface. This is a property reference expression.
336 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
337 Expr *BaseExpr, DeclarationName MemberName,
338 SourceLocation MemberLoc) {
339 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
340 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
341 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
343 // Search for a declared property first.
344 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
345 // Check whether we can reference this property.
346 if (DiagnoseUseOfDecl(PD, MemberLoc))
348 QualType ResTy = PD->getType();
349 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
350 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
351 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
352 ResTy = Getter->getSendResultType();
353 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
354 MemberLoc, BaseExpr));
356 // Check protocols on qualified interfaces.
357 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
358 E = OPT->qual_end(); I != E; ++I)
359 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
360 // Check whether we can reference this property.
361 if (DiagnoseUseOfDecl(PD, MemberLoc))
364 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
365 MemberLoc, BaseExpr));
367 // If that failed, look for an "implicit" property by seeing if the nullary
368 // selector is implemented.
370 // FIXME: The logic for looking up nullary and unary selectors should be
371 // shared with the code in ActOnInstanceMessage.
373 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
374 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
376 // If this reference is in an @implementation, check for 'private' methods.
378 Getter = IFace->lookupPrivateInstanceMethod(Sel);
380 // Look through local category implementations associated with the class.
382 Getter = IFace->getCategoryInstanceMethod(Sel);
384 // Check if we can reference this property.
385 if (DiagnoseUseOfDecl(Getter, MemberLoc))
388 // If we found a getter then this may be a valid dot-reference, we
389 // will look for the matching setter, in case it is needed.
391 SelectorTable::constructSetterName(PP.getIdentifierTable(),
392 PP.getSelectorTable(), Member);
393 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
395 // If this reference is in an @implementation, also check for 'private'
397 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
399 // Look through local category implementations associated with the class.
401 Setter = IFace->getCategoryInstanceMethod(SetterSel);
403 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
408 PType = Getter->getSendResultType();
409 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
410 Setter, MemberLoc, BaseExpr));
413 // Attempt to correct for typos in property names.
414 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
415 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
416 Res.getAsSingle<ObjCPropertyDecl>()) {
417 DeclarationName TypoResult = Res.getLookupName();
418 Diag(MemberLoc, diag::err_property_not_found_suggest)
419 << MemberName << QualType(OPT, 0) << TypoResult
420 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
421 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
422 Diag(Property->getLocation(), diag::note_previous_decl)
423 << Property->getDeclName();
424 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc);
427 Diag(MemberLoc, diag::err_property_not_found)
428 << MemberName << QualType(OPT, 0);
429 if (Setter && !Getter)
430 Diag(Setter->getLocation(), diag::note_getter_unavailable)
431 << MemberName << BaseExpr->getSourceRange();
438 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
439 IdentifierInfo &propertyName,
440 SourceLocation receiverNameLoc,
441 SourceLocation propertyNameLoc) {
443 IdentifierInfo *receiverNamePtr = &receiverName;
444 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
447 // If the "receiver" is 'super' in a method, handle it as an expression-like
448 // property reference.
449 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
450 if (receiverNamePtr->isStr("super")) {
451 if (CurMethod->isInstanceMethod()) {
453 Context.getObjCInterfaceType(CurMethod->getClassInterface());
454 T = Context.getObjCObjectPointerType(T);
455 Expr *SuperExpr = new (Context) ObjCSuperExpr(receiverNameLoc, T);
457 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
458 SuperExpr, &propertyName,
462 // Otherwise, if this is a class method, try dispatching to our
464 IFace = CurMethod->getClassInterface()->getSuperClass();
468 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
473 // Search for a declared property first.
474 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
475 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
477 // If this reference is in an @implementation, check for 'private' methods.
479 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
480 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
481 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
482 Getter = ImpDecl->getClassMethod(Sel);
485 // FIXME: refactor/share with ActOnMemberReference().
486 // Check if we can reference this property.
487 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
491 // Look for the matching setter, in case it is needed.
493 SelectorTable::constructSetterName(PP.getIdentifierTable(),
494 PP.getSelectorTable(), &propertyName);
496 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
498 // If this reference is in an @implementation, also check for 'private'
500 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
501 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
502 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
503 Setter = ImpDecl->getClassMethod(SetterSel);
505 // Look through local category implementations associated with the class.
507 Setter = IFace->getCategoryClassMethod(SetterSel);
509 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
512 if (Getter || Setter) {
516 PType = Getter->getSendResultType();
518 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
519 E = Setter->param_end(); PI != E; ++PI)
520 PType = (*PI)->getType();
522 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(
523 Getter, PType, Setter,
524 propertyNameLoc, IFace, receiverNameLoc));
526 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
527 << &propertyName << Context.getObjCInterfaceType(IFace));
530 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
531 IdentifierInfo *Name,
532 SourceLocation NameLoc,
535 ParsedType &ReceiverType) {
536 ReceiverType = ParsedType();
538 // If the identifier is "super" and there is no trailing dot, we're
540 if (IsSuper && !HasTrailingDot && S->isInObjcMethodScope())
541 return ObjCSuperMessage;
543 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
544 LookupName(Result, S);
546 switch (Result.getResultKind()) {
547 case LookupResult::NotFound:
548 // Normal name lookup didn't find anything. If we're in an
549 // Objective-C method, look for ivars. If we find one, we're done!
550 // FIXME: This is a hack. Ivar lookup should be part of normal lookup.
551 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
552 ObjCInterfaceDecl *ClassDeclared;
553 if (Method->getClassInterface()->lookupInstanceVariable(Name,
555 return ObjCInstanceMessage;
558 // Break out; we'll perform typo correction below.
561 case LookupResult::NotFoundInCurrentInstantiation:
562 case LookupResult::FoundOverloaded:
563 case LookupResult::FoundUnresolvedValue:
564 case LookupResult::Ambiguous:
565 Result.suppressDiagnostics();
566 return ObjCInstanceMessage;
568 case LookupResult::Found: {
569 // We found something. If it's a type, then we have a class
570 // message. Otherwise, it's an instance message.
571 NamedDecl *ND = Result.getFoundDecl();
573 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
574 T = Context.getObjCInterfaceType(Class);
575 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
576 T = Context.getTypeDeclType(Type);
578 return ObjCInstanceMessage;
580 // We have a class message, and T is the type we're
581 // messaging. Build source-location information for it.
582 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
583 ReceiverType = CreateParsedType(T, TSInfo);
584 return ObjCClassMessage;
588 // Determine our typo-correction context.
589 CorrectTypoContext CTC = CTC_Expression;
590 if (ObjCMethodDecl *Method = getCurMethodDecl())
591 if (Method->getClassInterface() &&
592 Method->getClassInterface()->getSuperClass())
593 CTC = CTC_ObjCMessageReceiver;
595 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
596 if (Result.isSingleResult()) {
597 // If we found a declaration, correct when it refers to an Objective-C
599 NamedDecl *ND = Result.getFoundDecl();
600 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
601 Diag(NameLoc, diag::err_unknown_receiver_suggest)
602 << Name << Result.getLookupName()
603 << FixItHint::CreateReplacement(SourceRange(NameLoc),
604 ND->getNameAsString());
605 Diag(ND->getLocation(), diag::note_previous_decl)
608 QualType T = Context.getObjCInterfaceType(Class);
609 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
610 ReceiverType = CreateParsedType(T, TSInfo);
611 return ObjCClassMessage;
613 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
614 Corrected.getAsIdentifierInfo()->isStr("super")) {
615 // If we've found the keyword "super", this is a send to super.
616 Diag(NameLoc, diag::err_unknown_receiver_suggest)
618 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
619 Name = Corrected.getAsIdentifierInfo();
620 return ObjCSuperMessage;
624 // Fall back: let the parser try to parse it as an instance message.
625 return ObjCInstanceMessage;
628 ExprResult Sema::ActOnSuperMessage(Scope *S,
629 SourceLocation SuperLoc,
631 SourceLocation LBracLoc,
632 SourceLocation SelectorLoc,
633 SourceLocation RBracLoc,
635 // Determine whether we are inside a method or not.
636 ObjCMethodDecl *Method = getCurMethodDecl();
638 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
642 ObjCInterfaceDecl *Class = Method->getClassInterface();
644 Diag(SuperLoc, diag::error_no_super_class_message)
645 << Method->getDeclName();
649 ObjCInterfaceDecl *Super = Class->getSuperClass();
651 // The current class does not have a superclass.
652 Diag(SuperLoc, diag::error_no_super_class) << Class->getIdentifier();
656 // We are in a method whose class has a superclass, so 'super'
657 // is acting as a keyword.
658 if (Method->isInstanceMethod()) {
659 // Since we are in an instance method, this is an instance
660 // message to the superclass instance.
661 QualType SuperTy = Context.getObjCInterfaceType(Super);
662 SuperTy = Context.getObjCObjectPointerType(SuperTy);
663 return BuildInstanceMessage(0, SuperTy, SuperLoc,
664 Sel, /*Method=*/0, LBracLoc, RBracLoc,
668 // Since we are in a class method, this is a class message to
670 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
671 Context.getObjCInterfaceType(Super),
672 SuperLoc, Sel, /*Method=*/0, LBracLoc, RBracLoc,
676 /// \brief Build an Objective-C class message expression.
678 /// This routine takes care of both normal class messages and
679 /// class messages to the superclass.
681 /// \param ReceiverTypeInfo Type source information that describes the
682 /// receiver of this message. This may be NULL, in which case we are
683 /// sending to the superclass and \p SuperLoc must be a valid source
686 /// \param ReceiverType The type of the object receiving the
687 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
688 /// type as that refers to. For a superclass send, this is the type of
691 /// \param SuperLoc The location of the "super" keyword in a
692 /// superclass message.
694 /// \param Sel The selector to which the message is being sent.
696 /// \param Method The method that this class message is invoking, if
699 /// \param LBracLoc The location of the opening square bracket ']'.
701 /// \param RBrac The location of the closing square bracket ']'.
703 /// \param Args The message arguments.
704 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
705 QualType ReceiverType,
706 SourceLocation SuperLoc,
708 ObjCMethodDecl *Method,
709 SourceLocation LBracLoc,
710 SourceLocation RBracLoc,
711 MultiExprArg ArgsIn) {
712 if (ReceiverType->isDependentType()) {
713 // If the receiver type is dependent, we can't type-check anything
714 // at this point. Build a dependent expression.
715 unsigned NumArgs = ArgsIn.size();
716 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
717 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
718 return Owned(ObjCMessageExpr::Create(Context, ReceiverType, LBracLoc,
719 ReceiverTypeInfo, Sel, /*Method=*/0,
720 Args, NumArgs, RBracLoc));
723 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
724 : ReceiverTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
726 // Find the class to which we are sending this message.
727 ObjCInterfaceDecl *Class = 0;
728 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
729 if (!ClassType || !(Class = ClassType->getInterface())) {
730 Diag(Loc, diag::err_invalid_receiver_class_message)
734 assert(Class && "We don't know which class we're messaging?");
736 // Find the method we are messaging.
738 if (Class->isForwardDecl()) {
739 // A forward class used in messaging is treated as a 'Class'
740 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
741 Method = LookupFactoryMethodInGlobalPool(Sel,
742 SourceRange(LBracLoc, RBracLoc));
744 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
745 << Method->getDeclName();
748 Method = Class->lookupClassMethod(Sel);
750 // If we have an implementation in scope, check "private" methods.
752 Method = LookupPrivateClassMethod(Sel, Class);
754 if (Method && DiagnoseUseOfDecl(Method, Loc))
758 // Check the argument types and determine the result type.
760 unsigned NumArgs = ArgsIn.size();
761 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
762 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
763 LBracLoc, RBracLoc, ReturnType))
766 // Construct the appropriate ObjCMessageExpr.
768 if (SuperLoc.isValid())
769 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
770 SuperLoc, /*IsInstanceSuper=*/false,
771 ReceiverType, Sel, Method, Args,
774 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
775 ReceiverTypeInfo, Sel, Method, Args,
777 return MaybeBindToTemporary(Result);
780 // ActOnClassMessage - used for both unary and keyword messages.
781 // ArgExprs is optional - if it is present, the number of expressions
782 // is obtained from Sel.getNumArgs().
783 ExprResult Sema::ActOnClassMessage(Scope *S,
786 SourceLocation LBracLoc,
787 SourceLocation SelectorLoc,
788 SourceLocation RBracLoc,
790 TypeSourceInfo *ReceiverTypeInfo;
791 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
792 if (ReceiverType.isNull())
796 if (!ReceiverTypeInfo)
797 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
799 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
800 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
801 LBracLoc, RBracLoc, move(Args));
804 /// \brief Build an Objective-C instance message expression.
806 /// This routine takes care of both normal instance messages and
807 /// instance messages to the superclass instance.
809 /// \param Receiver The expression that computes the object that will
810 /// receive this message. This may be empty, in which case we are
811 /// sending to the superclass instance and \p SuperLoc must be a valid
814 /// \param ReceiverType The (static) type of the object receiving the
815 /// message. When a \p Receiver expression is provided, this is the
816 /// same type as that expression. For a superclass instance send, this
817 /// is a pointer to the type of the superclass.
819 /// \param SuperLoc The location of the "super" keyword in a
820 /// superclass instance message.
822 /// \param Sel The selector to which the message is being sent.
824 /// \param Method The method that this instance message is invoking, if
827 /// \param LBracLoc The location of the opening square bracket ']'.
829 /// \param RBrac The location of the closing square bracket ']'.
831 /// \param Args The message arguments.
832 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
833 QualType ReceiverType,
834 SourceLocation SuperLoc,
836 ObjCMethodDecl *Method,
837 SourceLocation LBracLoc,
838 SourceLocation RBracLoc,
839 MultiExprArg ArgsIn) {
840 // If we have a receiver expression, perform appropriate promotions
841 // and determine receiver type.
843 if (Receiver->isTypeDependent()) {
844 // If the receiver is type-dependent, we can't type-check anything
845 // at this point. Build a dependent expression.
846 unsigned NumArgs = ArgsIn.size();
847 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
848 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
849 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
850 LBracLoc, Receiver, Sel,
851 /*Method=*/0, Args, NumArgs,
855 // If necessary, apply function/array conversion to the receiver.
856 // C99 6.7.5.3p[7,8].
857 DefaultFunctionArrayLvalueConversion(Receiver);
858 ReceiverType = Receiver->getType();
861 // The location of the receiver.
862 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
865 // Handle messages to id.
866 bool receiverIsId = ReceiverType->isObjCIdType();
867 if (receiverIsId || ReceiverType->isBlockPointerType() ||
868 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
869 Method = LookupInstanceMethodInGlobalPool(Sel,
870 SourceRange(LBracLoc, RBracLoc),
873 Method = LookupFactoryMethodInGlobalPool(Sel,
874 SourceRange(LBracLoc, RBracLoc),
876 } else if (ReceiverType->isObjCClassType() ||
877 ReceiverType->isObjCQualifiedClassType()) {
878 // Handle messages to Class.
879 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
880 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
881 // First check the public methods in the class interface.
882 Method = ClassDecl->lookupClassMethod(Sel);
885 Method = LookupPrivateClassMethod(Sel, ClassDecl);
887 // FIXME: if we still haven't found a method, we need to look in
888 // protocols (if we have qualifiers).
890 if (Method && DiagnoseUseOfDecl(Method, Loc))
894 // If not messaging 'self', look for any factory method named 'Sel'.
895 if (!Receiver || !isSelfExpr(Receiver)) {
896 Method = LookupFactoryMethodInGlobalPool(Sel,
897 SourceRange(LBracLoc, RBracLoc),
900 // If no class (factory) method was found, check if an _instance_
901 // method of the same name exists in the root class only.
902 Method = LookupInstanceMethodInGlobalPool(Sel,
903 SourceRange(LBracLoc, RBracLoc),
906 if (const ObjCInterfaceDecl *ID =
907 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
908 if (ID->getSuperClass())
909 Diag(Loc, diag::warn_root_inst_method_not_found)
910 << Sel << SourceRange(LBracLoc, RBracLoc);
916 ObjCInterfaceDecl* ClassDecl = 0;
918 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
919 // long as one of the protocols implements the selector (if not, warn).
920 if (const ObjCObjectPointerType *QIdTy
921 = ReceiverType->getAsObjCQualifiedIdType()) {
922 // Search protocols for instance methods.
923 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
924 E = QIdTy->qual_end(); I != E; ++I) {
925 ObjCProtocolDecl *PDecl = *I;
926 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
928 // Since we aren't supporting "Class<foo>", look for a class method.
929 if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
932 } else if (const ObjCObjectPointerType *OCIType
933 = ReceiverType->getAsObjCInterfacePointerType()) {
934 // We allow sending a message to a pointer to an interface (an object).
935 ClassDecl = OCIType->getInterfaceDecl();
936 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
937 // faster than the following method (which can do *many* linear searches).
938 // The idea is to add class info to MethodPool.
939 Method = ClassDecl->lookupInstanceMethod(Sel);
942 // Search protocol qualifiers.
943 for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(),
944 E = OCIType->qual_end(); QI != E; ++QI) {
945 if ((Method = (*QI)->lookupInstanceMethod(Sel)))
950 // If we have implementations in scope, check "private" methods.
951 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
953 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
954 // If we still haven't found a method, look in the global pool. This
955 // behavior isn't very desirable, however we need it for GCC
956 // compatibility. FIXME: should we deviate??
957 if (OCIType->qual_empty()) {
958 Method = LookupInstanceMethodInGlobalPool(Sel,
959 SourceRange(LBracLoc, RBracLoc));
960 if (Method && !OCIType->getInterfaceDecl()->isForwardDecl())
961 Diag(Loc, diag::warn_maynot_respond)
962 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
966 if (Method && DiagnoseUseOfDecl(Method, Loc))
968 } else if (!Context.getObjCIdType().isNull() &&
969 (ReceiverType->isPointerType() ||
970 ReceiverType->isIntegerType())) {
971 // Implicitly convert integers and pointers to 'id' but emit a warning.
972 Diag(Loc, diag::warn_bad_receiver_type)
974 << Receiver->getSourceRange();
975 if (ReceiverType->isPointerType())
976 ImpCastExprToType(Receiver, Context.getObjCIdType(),
979 ImpCastExprToType(Receiver, Context.getObjCIdType(),
980 CK_IntegralToPointer);
981 ReceiverType = Receiver->getType();
983 else if (getLangOptions().CPlusPlus &&
984 !PerformContextuallyConvertToObjCId(Receiver)) {
985 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
986 Receiver = ICE->getSubExpr();
987 ReceiverType = Receiver->getType();
989 return BuildInstanceMessage(Receiver,
998 // Reject other random receiver types (e.g. structs).
999 Diag(Loc, diag::err_bad_receiver_type)
1000 << ReceiverType << Receiver->getSourceRange();
1006 // Check the message arguments.
1007 unsigned NumArgs = ArgsIn.size();
1008 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1009 QualType ReturnType;
1010 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, false,
1011 LBracLoc, RBracLoc, ReturnType))
1014 if (!ReturnType->isVoidType()) {
1015 if (RequireCompleteType(LBracLoc, ReturnType,
1016 diag::err_illegal_message_expr_incomplete_type))
1020 // Construct the appropriate ObjCMessageExpr instance.
1022 if (SuperLoc.isValid())
1023 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
1024 SuperLoc, /*IsInstanceSuper=*/true,
1025 ReceiverType, Sel, Method,
1026 Args, NumArgs, RBracLoc);
1028 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, Receiver,
1029 Sel, Method, Args, NumArgs, RBracLoc);
1030 return MaybeBindToTemporary(Result);
1033 // ActOnInstanceMessage - used for both unary and keyword messages.
1034 // ArgExprs is optional - if it is present, the number of expressions
1035 // is obtained from Sel.getNumArgs().
1036 ExprResult Sema::ActOnInstanceMessage(Scope *S,
1039 SourceLocation LBracLoc,
1040 SourceLocation SelectorLoc,
1041 SourceLocation RBracLoc,
1042 MultiExprArg Args) {
1046 return BuildInstanceMessage(Receiver, Receiver->getType(),
1047 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1048 LBracLoc, RBracLoc, move(Args));