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 //===----------------------------------------------------------------------===//
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeLoc.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "clang/Lex/Preprocessor.h"
24 using namespace clang;
26 Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
28 unsigned NumStrings) {
29 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
31 // Most ObjC strings are formed out of a single piece. However, we *can*
32 // have strings formed out of multiple @ strings with multiple pptokens in
33 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
34 // StringLiteral for ObjCStringLiteral to hold onto.
35 StringLiteral *S = Strings[0];
37 // If we have a multi-part string, merge it all together.
38 if (NumStrings != 1) {
39 // Concatenate objc strings.
40 llvm::SmallString<128> StrBuf;
41 llvm::SmallVector<SourceLocation, 8> StrLocs;
43 for (unsigned i = 0; i != NumStrings; ++i) {
46 // ObjC strings can't be wide.
48 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
49 << S->getSourceRange();
53 // Get the string data.
54 StrBuf.append(S->getStrData(), S->getStrData()+S->getByteLength());
56 // Get the locations of the string tokens.
57 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
59 // Free the temporary string.
63 // Create the aggregate string with the appropriate content and location
65 S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(), false,
66 Context.getPointerType(Context.CharTy),
67 &StrLocs[0], StrLocs.size());
70 // Verify that this composite string is acceptable for ObjC strings.
71 if (CheckObjCString(S))
74 // Initialize the constant string interface lazily. This assumes
75 // the NSString interface is seen in this translation unit. Note: We
76 // don't use NSConstantString, since the runtime team considers this
77 // interface private (even though it appears in the header files).
78 QualType Ty = Context.getObjCConstantStringInterface();
80 Ty = Context.getObjCObjectPointerType(Ty);
81 } else if (getLangOptions().NoConstantCFStrings) {
82 IdentifierInfo *NSIdent = &Context.Idents.get("NSConstantString");
83 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
85 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
86 Context.setObjCConstantStringInterface(StrIF);
87 Ty = Context.getObjCConstantStringInterface();
88 Ty = Context.getObjCObjectPointerType(Ty);
90 // If there is no NSConstantString interface defined then treat this
91 // as error and recover from it.
92 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
93 << S->getSourceRange();
94 Ty = Context.getObjCIdType();
97 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
98 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
100 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
101 Context.setObjCConstantStringInterface(StrIF);
102 Ty = Context.getObjCConstantStringInterface();
103 Ty = Context.getObjCObjectPointerType(Ty);
105 // If there is no NSString interface defined then treat constant
106 // strings as untyped objects and let the runtime figure it out later.
107 Ty = Context.getObjCIdType();
111 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
114 Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
115 TypeSourceInfo *EncodedTypeInfo,
116 SourceLocation RParenLoc) {
117 QualType EncodedType = EncodedTypeInfo->getType();
119 if (EncodedType->isDependentType())
120 StrTy = Context.DependentTy;
123 Context.getObjCEncodingForType(EncodedType, Str);
125 // The type of @encode is the same as the type of the corresponding string,
126 // which is an array type.
127 StrTy = Context.CharTy;
128 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
129 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
131 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
132 ArrayType::Normal, 0);
135 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
138 Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
139 SourceLocation EncodeLoc,
140 SourceLocation LParenLoc,
142 SourceLocation RParenLoc) {
143 // FIXME: Preserve type source info ?
144 TypeSourceInfo *TInfo;
145 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
147 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
148 PP.getLocForEndOfToken(LParenLoc));
150 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
153 Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
154 SourceLocation AtLoc,
155 SourceLocation SelLoc,
156 SourceLocation LParenLoc,
157 SourceLocation RParenLoc) {
158 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
159 SourceRange(LParenLoc, RParenLoc), false);
161 Method = LookupFactoryMethodInGlobalPool(Sel,
162 SourceRange(LParenLoc, RParenLoc));
164 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
166 QualType Ty = Context.getObjCSelType();
167 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
170 Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
171 SourceLocation AtLoc,
172 SourceLocation ProtoLoc,
173 SourceLocation LParenLoc,
174 SourceLocation RParenLoc) {
175 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
177 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
181 QualType Ty = Context.getObjCProtoType();
184 Ty = Context.getObjCObjectPointerType(Ty);
185 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
188 bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
189 Selector Sel, ObjCMethodDecl *Method,
191 SourceLocation lbrac, SourceLocation rbrac,
192 QualType &ReturnType) {
194 // Apply default argument promotion as for (C99 6.5.2.2p6).
195 for (unsigned i = 0; i != NumArgs; i++) {
196 if (Args[i]->isTypeDependent())
199 DefaultArgumentPromotion(Args[i]);
202 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
203 diag::warn_inst_method_not_found;
205 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
206 ReturnType = Context.getObjCIdType();
210 ReturnType = Method->getSendResultType();
212 unsigned NumNamedArgs = Sel.getNumArgs();
213 // Method might have more arguments than selector indicates. This is due
214 // to addition of c-style arguments in method.
215 if (Method->param_size() > Sel.getNumArgs())
216 NumNamedArgs = Method->param_size();
217 // FIXME. This need be cleaned up.
218 if (NumArgs < NumNamedArgs) {
219 Diag(lbrac, diag::err_typecheck_call_too_few_args) << 2
220 << NumNamedArgs << NumArgs;
224 bool IsError = false;
225 for (unsigned i = 0; i < NumNamedArgs; i++) {
226 // We can't do any type-checking on a type-dependent argument.
227 if (Args[i]->isTypeDependent())
230 Expr *argExpr = Args[i];
232 ParmVarDecl *Param = Method->param_begin()[i];
233 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
235 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
237 PDiag(diag::err_call_incomplete_argument)
238 << argExpr->getSourceRange()))
241 InitializedEntity Entity = InitializedEntity::InitializeParameter(Param);
242 OwningExprResult ArgE = PerformCopyInitialization(Entity,
244 Owned(argExpr->Retain()));
245 if (ArgE.isInvalid())
248 Args[i] = ArgE.takeAs<Expr>();
251 // Promote additional arguments to variadic methods.
252 if (Method->isVariadic()) {
253 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
254 if (Args[i]->isTypeDependent())
257 IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
260 // Check for extra arguments to non-variadic methods.
261 if (NumArgs != NumNamedArgs) {
262 Diag(Args[NumNamedArgs]->getLocStart(),
263 diag::err_typecheck_call_too_many_args)
264 << 2 /*method*/ << NumNamedArgs << NumArgs
265 << Method->getSourceRange()
266 << SourceRange(Args[NumNamedArgs]->getLocStart(),
267 Args[NumArgs-1]->getLocEnd());
271 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
275 bool Sema::isSelfExpr(Expr *RExpr) {
276 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
277 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
282 // Helper method for ActOnClassMethod/ActOnInstanceMethod.
283 // Will search "local" class/category implementations for a method decl.
284 // If failed, then we search in class's root for an instance method.
285 // Returns 0 if no method is found.
286 ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
287 ObjCInterfaceDecl *ClassDecl) {
288 ObjCMethodDecl *Method = 0;
289 // lookup in class and all superclasses
290 while (ClassDecl && !Method) {
291 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
292 Method = ImpDecl->getClassMethod(Sel);
294 // Look through local category implementations associated with the class.
296 Method = ClassDecl->getCategoryClassMethod(Sel);
298 // Before we give up, check if the selector is an instance method.
299 // But only in the root. This matches gcc's behaviour and what the
301 if (!Method && !ClassDecl->getSuperClass()) {
302 Method = ClassDecl->lookupInstanceMethod(Sel);
303 // Look through local category implementations associated
304 // with the root class.
306 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
309 ClassDecl = ClassDecl->getSuperClass();
314 ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
315 ObjCInterfaceDecl *ClassDecl) {
316 ObjCMethodDecl *Method = 0;
317 while (ClassDecl && !Method) {
318 // If we have implementations in scope, check "private" methods.
319 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
320 Method = ImpDecl->getInstanceMethod(Sel);
322 // Look through local category implementations associated with the class.
324 Method = ClassDecl->getCategoryInstanceMethod(Sel);
325 ClassDecl = ClassDecl->getSuperClass();
330 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
331 /// objective C interface. This is a property reference expression.
332 Action::OwningExprResult Sema::
333 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
334 Expr *BaseExpr, DeclarationName MemberName,
335 SourceLocation MemberLoc) {
336 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
337 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
338 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
340 // Search for a declared property first.
341 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
342 // Check whether we can reference this property.
343 if (DiagnoseUseOfDecl(PD, MemberLoc))
345 QualType ResTy = PD->getType();
346 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
347 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
348 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
349 ResTy = Getter->getSendResultType();
350 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
351 MemberLoc, BaseExpr));
353 // Check protocols on qualified interfaces.
354 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
355 E = OPT->qual_end(); I != E; ++I)
356 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
357 // Check whether we can reference this property.
358 if (DiagnoseUseOfDecl(PD, MemberLoc))
361 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
362 MemberLoc, BaseExpr));
364 // If that failed, look for an "implicit" property by seeing if the nullary
365 // selector is implemented.
367 // FIXME: The logic for looking up nullary and unary selectors should be
368 // shared with the code in ActOnInstanceMessage.
370 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
371 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
373 // If this reference is in an @implementation, check for 'private' methods.
375 Getter = IFace->lookupPrivateInstanceMethod(Sel);
377 // Look through local category implementations associated with the class.
379 Getter = IFace->getCategoryInstanceMethod(Sel);
381 // Check if we can reference this property.
382 if (DiagnoseUseOfDecl(Getter, MemberLoc))
385 // If we found a getter then this may be a valid dot-reference, we
386 // will look for the matching setter, in case it is needed.
388 SelectorTable::constructSetterName(PP.getIdentifierTable(),
389 PP.getSelectorTable(), Member);
390 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
392 // If this reference is in an @implementation, also check for 'private'
394 Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
396 // Look through local category implementations associated with the class.
398 Setter = IFace->getCategoryInstanceMethod(SetterSel);
400 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
405 PType = Getter->getSendResultType();
406 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
407 Setter, MemberLoc, BaseExpr));
410 // Attempt to correct for typos in property names.
411 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
412 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
413 Res.getAsSingle<ObjCPropertyDecl>()) {
414 DeclarationName TypoResult = Res.getLookupName();
415 Diag(MemberLoc, diag::err_property_not_found_suggest)
416 << MemberName << QualType(OPT, 0) << TypoResult
417 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
418 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
419 Diag(Property->getLocation(), diag::note_previous_decl)
420 << Property->getDeclName();
421 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc);
424 Diag(MemberLoc, diag::err_property_not_found)
425 << MemberName << QualType(OPT, 0);
426 if (Setter && !Getter)
427 Diag(Setter->getLocation(), diag::note_getter_unavailable)
428 << MemberName << BaseExpr->getSourceRange();
434 Action::OwningExprResult Sema::
435 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
436 IdentifierInfo &propertyName,
437 SourceLocation receiverNameLoc,
438 SourceLocation propertyNameLoc) {
440 IdentifierInfo *receiverNamePtr = &receiverName;
441 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
444 // If the "receiver" is 'super' in a method, handle it as an expression-like
445 // property reference.
446 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
447 if (receiverNamePtr->isStr("super")) {
448 if (CurMethod->isInstanceMethod()) {
450 Context.getObjCInterfaceType(CurMethod->getClassInterface());
451 T = Context.getObjCObjectPointerType(T);
452 Expr *SuperExpr = new (Context) ObjCSuperExpr(receiverNameLoc, T);
454 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
455 SuperExpr, &propertyName,
459 // Otherwise, if this is a class method, try dispatching to our
461 IFace = CurMethod->getClassInterface()->getSuperClass();
465 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
470 // Search for a declared property first.
471 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
472 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
474 // If this reference is in an @implementation, check for 'private' methods.
476 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
477 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
478 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
479 Getter = ImpDecl->getClassMethod(Sel);
482 // FIXME: refactor/share with ActOnMemberReference().
483 // Check if we can reference this property.
484 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
488 // Look for the matching setter, in case it is needed.
490 SelectorTable::constructSetterName(PP.getIdentifierTable(),
491 PP.getSelectorTable(), &propertyName);
493 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
495 // If this reference is in an @implementation, also check for 'private'
497 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
498 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
499 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
500 Setter = ImpDecl->getClassMethod(SetterSel);
502 // Look through local category implementations associated with the class.
504 Setter = IFace->getCategoryClassMethod(SetterSel);
506 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
509 if (Getter || Setter) {
513 PType = Getter->getSendResultType();
515 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
516 E = Setter->param_end(); PI != E; ++PI)
517 PType = (*PI)->getType();
519 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(
520 Getter, PType, Setter,
521 propertyNameLoc, IFace, receiverNameLoc));
523 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
524 << &propertyName << Context.getObjCInterfaceType(IFace));
527 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
528 IdentifierInfo *Name,
529 SourceLocation NameLoc,
532 TypeTy *&ReceiverType) {
535 // If the identifier is "super" and there is no trailing dot, we're
537 if (IsSuper && !HasTrailingDot && S->isInObjcMethodScope())
538 return ObjCSuperMessage;
540 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
541 LookupName(Result, S);
543 switch (Result.getResultKind()) {
544 case LookupResult::NotFound:
545 // Normal name lookup didn't find anything. If we're in an
546 // Objective-C method, look for ivars. If we find one, we're done!
547 // FIXME: This is a hack. Ivar lookup should be part of normal lookup.
548 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
549 ObjCInterfaceDecl *ClassDeclared;
550 if (Method->getClassInterface()->lookupInstanceVariable(Name,
552 return ObjCInstanceMessage;
555 // Break out; we'll perform typo correction below.
558 case LookupResult::NotFoundInCurrentInstantiation:
559 case LookupResult::FoundOverloaded:
560 case LookupResult::FoundUnresolvedValue:
561 case LookupResult::Ambiguous:
562 Result.suppressDiagnostics();
563 return ObjCInstanceMessage;
565 case LookupResult::Found: {
566 // We found something. If it's a type, then we have a class
567 // message. Otherwise, it's an instance message.
568 NamedDecl *ND = Result.getFoundDecl();
570 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
571 T = Context.getObjCInterfaceType(Class);
572 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
573 T = Context.getTypeDeclType(Type);
575 return ObjCInstanceMessage;
577 // We have a class message, and T is the type we're
578 // messaging. Build source-location information for it.
579 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
580 ReceiverType = CreateLocInfoType(T, TSInfo).getAsOpaquePtr();
581 return ObjCClassMessage;
585 // Determine our typo-correction context.
586 CorrectTypoContext CTC = CTC_Expression;
587 if (ObjCMethodDecl *Method = getCurMethodDecl())
588 if (Method->getClassInterface() &&
589 Method->getClassInterface()->getSuperClass())
590 CTC = CTC_ObjCMessageReceiver;
592 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
593 if (Result.isSingleResult()) {
594 // If we found a declaration, correct when it refers to an Objective-C
596 NamedDecl *ND = Result.getFoundDecl();
597 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
598 Diag(NameLoc, diag::err_unknown_receiver_suggest)
599 << Name << Result.getLookupName()
600 << FixItHint::CreateReplacement(SourceRange(NameLoc),
601 ND->getNameAsString());
602 Diag(ND->getLocation(), diag::note_previous_decl)
605 QualType T = Context.getObjCInterfaceType(Class);
606 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
607 ReceiverType = CreateLocInfoType(T, TSInfo).getAsOpaquePtr();
608 return ObjCClassMessage;
610 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
611 Corrected.getAsIdentifierInfo()->isStr("super")) {
612 // If we've found the keyword "super", this is a send to super.
613 Diag(NameLoc, diag::err_unknown_receiver_suggest)
615 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
616 Name = Corrected.getAsIdentifierInfo();
617 return ObjCSuperMessage;
621 // Fall back: let the parser try to parse it as an instance message.
622 return ObjCInstanceMessage;
625 Sema::OwningExprResult Sema::ActOnSuperMessage(Scope *S,
626 SourceLocation SuperLoc,
628 SourceLocation LBracLoc,
629 SourceLocation SelectorLoc,
630 SourceLocation RBracLoc,
632 // Determine whether we are inside a method or not.
633 ObjCMethodDecl *Method = getCurMethodDecl();
635 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
639 ObjCInterfaceDecl *Class = Method->getClassInterface();
641 Diag(SuperLoc, diag::error_no_super_class_message)
642 << Method->getDeclName();
646 ObjCInterfaceDecl *Super = Class->getSuperClass();
648 // The current class does not have a superclass.
649 Diag(SuperLoc, diag::error_no_super_class) << Class->getIdentifier();
653 // We are in a method whose class has a superclass, so 'super'
654 // is acting as a keyword.
655 if (Method->isInstanceMethod()) {
656 // Since we are in an instance method, this is an instance
657 // message to the superclass instance.
658 QualType SuperTy = Context.getObjCInterfaceType(Super);
659 SuperTy = Context.getObjCObjectPointerType(SuperTy);
660 return BuildInstanceMessage(ExprArg(*this), SuperTy, SuperLoc,
661 Sel, /*Method=*/0, LBracLoc, RBracLoc,
665 // Since we are in a class method, this is a class message to
667 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
668 Context.getObjCInterfaceType(Super),
669 SuperLoc, Sel, /*Method=*/0, LBracLoc, RBracLoc,
673 /// \brief Build an Objective-C class message expression.
675 /// This routine takes care of both normal class messages and
676 /// class messages to the superclass.
678 /// \param ReceiverTypeInfo Type source information that describes the
679 /// receiver of this message. This may be NULL, in which case we are
680 /// sending to the superclass and \p SuperLoc must be a valid source
683 /// \param ReceiverType The type of the object receiving the
684 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
685 /// type as that refers to. For a superclass send, this is the type of
688 /// \param SuperLoc The location of the "super" keyword in a
689 /// superclass message.
691 /// \param Sel The selector to which the message is being sent.
693 /// \param Method The method that this class message is invoking, if
696 /// \param LBracLoc The location of the opening square bracket ']'.
698 /// \param RBrac The location of the closing square bracket ']'.
700 /// \param Args The message arguments.
701 Sema::OwningExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
702 QualType ReceiverType,
703 SourceLocation SuperLoc,
705 ObjCMethodDecl *Method,
706 SourceLocation LBracLoc,
707 SourceLocation RBracLoc,
708 MultiExprArg ArgsIn) {
709 if (ReceiverType->isDependentType()) {
710 // If the receiver type is dependent, we can't type-check anything
711 // at this point. Build a dependent expression.
712 unsigned NumArgs = ArgsIn.size();
713 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
714 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
715 return Owned(ObjCMessageExpr::Create(Context, ReceiverType, LBracLoc,
716 ReceiverTypeInfo, Sel, /*Method=*/0,
717 Args, NumArgs, RBracLoc));
720 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
721 : ReceiverTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
723 // Find the class to which we are sending this message.
724 ObjCInterfaceDecl *Class = 0;
725 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
726 if (!ClassType || !(Class = ClassType->getInterface())) {
727 Diag(Loc, diag::err_invalid_receiver_class_message)
731 assert(Class && "We don't know which class we're messaging?");
733 // Find the method we are messaging.
735 if (Class->isForwardDecl()) {
736 // A forward class used in messaging is treated as a 'Class'
737 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
738 Method = LookupFactoryMethodInGlobalPool(Sel,
739 SourceRange(LBracLoc, RBracLoc));
741 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
742 << Method->getDeclName();
745 Method = Class->lookupClassMethod(Sel);
747 // If we have an implementation in scope, check "private" methods.
749 Method = LookupPrivateClassMethod(Sel, Class);
751 if (Method && DiagnoseUseOfDecl(Method, Loc))
755 // Check the argument types and determine the result type.
757 unsigned NumArgs = ArgsIn.size();
758 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
759 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
760 LBracLoc, RBracLoc, ReturnType)) {
761 for (unsigned I = 0; I != NumArgs; ++I)
762 Args[I]->Destroy(Context);
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 Sema::OwningExprResult 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 Sema::OwningExprResult Sema::BuildInstanceMessage(ExprArg ReceiverE,
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.
842 Expr *Receiver = ReceiverE.takeAs<Expr>();
844 if (Receiver->isTypeDependent()) {
845 // If the receiver is type-dependent, we can't type-check anything
846 // at this point. Build a dependent expression.
847 unsigned NumArgs = ArgsIn.size();
848 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
849 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
850 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
851 LBracLoc, Receiver, Sel,
852 /*Method=*/0, Args, NumArgs,
856 // If necessary, apply function/array conversion to the receiver.
857 // C99 6.7.5.3p[7,8].
858 DefaultFunctionArrayLvalueConversion(Receiver);
859 ReceiverType = Receiver->getType();
862 // The location of the receiver.
863 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
866 // Handle messages to id.
867 if (ReceiverType->isObjCIdType() || ReceiverType->isBlockPointerType() ||
868 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
869 Method = LookupInstanceMethodInGlobalPool(Sel,
870 SourceRange(LBracLoc, RBracLoc));
872 Method = LookupFactoryMethodInGlobalPool(Sel,
873 SourceRange(LBracLoc, RBracLoc));
874 } else if (ReceiverType->isObjCClassType() ||
875 ReceiverType->isObjCQualifiedClassType()) {
876 // Handle messages to Class.
877 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
878 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
879 // First check the public methods in the class interface.
880 Method = ClassDecl->lookupClassMethod(Sel);
883 Method = LookupPrivateClassMethod(Sel, ClassDecl);
885 // FIXME: if we still haven't found a method, we need to look in
886 // protocols (if we have qualifiers).
888 if (Method && DiagnoseUseOfDecl(Method, Loc))
892 // If not messaging 'self', look for any factory method named 'Sel'.
893 if (!Receiver || !isSelfExpr(Receiver)) {
894 Method = LookupFactoryMethodInGlobalPool(Sel,
895 SourceRange(LBracLoc, RBracLoc));
897 // If no class (factory) method was found, check if an _instance_
898 // method of the same name exists in the root class only.
899 Method = LookupInstanceMethodInGlobalPool(Sel,
900 SourceRange(LBracLoc, RBracLoc));
902 if (const ObjCInterfaceDecl *ID =
903 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
904 if (ID->getSuperClass())
905 Diag(Loc, diag::warn_root_inst_method_not_found)
906 << Sel << SourceRange(LBracLoc, RBracLoc);
912 ObjCInterfaceDecl* ClassDecl = 0;
914 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
915 // long as one of the protocols implements the selector (if not, warn).
916 if (const ObjCObjectPointerType *QIdTy
917 = ReceiverType->getAsObjCQualifiedIdType()) {
918 // Search protocols for instance methods.
919 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
920 E = QIdTy->qual_end(); I != E; ++I) {
921 ObjCProtocolDecl *PDecl = *I;
922 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
924 // Since we aren't supporting "Class<foo>", look for a class method.
925 if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
928 } else if (const ObjCObjectPointerType *OCIType
929 = ReceiverType->getAsObjCInterfacePointerType()) {
930 // We allow sending a message to a pointer to an interface (an object).
931 ClassDecl = OCIType->getInterfaceDecl();
932 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
933 // faster than the following method (which can do *many* linear searches).
934 // The idea is to add class info to InstanceMethodPool.
935 Method = ClassDecl->lookupInstanceMethod(Sel);
938 // Search protocol qualifiers.
939 for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(),
940 E = OCIType->qual_end(); QI != E; ++QI) {
941 if ((Method = (*QI)->lookupInstanceMethod(Sel)))
946 // If we have implementations in scope, check "private" methods.
947 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
949 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
950 // If we still haven't found a method, look in the global pool. This
951 // behavior isn't very desirable, however we need it for GCC
952 // compatibility. FIXME: should we deviate??
953 if (OCIType->qual_empty()) {
954 Method = LookupInstanceMethodInGlobalPool(Sel,
955 SourceRange(LBracLoc, RBracLoc));
956 if (Method && !OCIType->getInterfaceDecl()->isForwardDecl())
957 Diag(Loc, diag::warn_maynot_respond)
958 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
962 if (Method && DiagnoseUseOfDecl(Method, Loc))
964 } else if (!Context.getObjCIdType().isNull() &&
965 (ReceiverType->isPointerType() ||
966 (ReceiverType->isIntegerType() &&
967 ReceiverType->isScalarType()))) {
968 // Implicitly convert integers and pointers to 'id' but emit a warning.
969 Diag(Loc, diag::warn_bad_receiver_type)
971 << Receiver->getSourceRange();
972 if (ReceiverType->isPointerType())
973 ImpCastExprToType(Receiver, Context.getObjCIdType(),
974 CastExpr::CK_BitCast);
976 ImpCastExprToType(Receiver, Context.getObjCIdType(),
977 CastExpr::CK_IntegralToPointer);
978 ReceiverType = Receiver->getType();
980 else if (getLangOptions().CPlusPlus &&
981 !PerformContextuallyConvertToObjCId(Receiver)) {
982 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
983 Receiver = ICE->getSubExpr();
984 ReceiverType = Receiver->getType();
986 return BuildInstanceMessage(Owned(Receiver),
995 // Reject other random receiver types (e.g. structs).
996 Diag(Loc, diag::err_bad_receiver_type)
997 << ReceiverType << Receiver->getSourceRange();
1003 // Check the message arguments.
1004 unsigned NumArgs = ArgsIn.size();
1005 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1006 QualType ReturnType;
1007 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, false,
1008 LBracLoc, RBracLoc, ReturnType))
1011 if (!ReturnType->isVoidType()) {
1012 if (RequireCompleteType(LBracLoc, ReturnType,
1013 diag::err_illegal_message_expr_incomplete_type))
1017 // Construct the appropriate ObjCMessageExpr instance.
1019 if (SuperLoc.isValid())
1020 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc,
1021 SuperLoc, /*IsInstanceSuper=*/true,
1022 ReceiverType, Sel, Method,
1023 Args, NumArgs, RBracLoc);
1025 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, Receiver,
1026 Sel, Method, Args, NumArgs, RBracLoc);
1027 return MaybeBindToTemporary(Result);
1030 // ActOnInstanceMessage - used for both unary and keyword messages.
1031 // ArgExprs is optional - if it is present, the number of expressions
1032 // is obtained from Sel.getNumArgs().
1033 Sema::OwningExprResult Sema::ActOnInstanceMessage(Scope *S,
1036 SourceLocation LBracLoc,
1037 SourceLocation SelectorLoc,
1038 SourceLocation RBracLoc,
1039 MultiExprArg Args) {
1040 Expr *Receiver = static_cast<Expr *>(ReceiverE.get());
1044 return BuildInstanceMessage(move(ReceiverE), Receiver->getType(),
1045 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1046 LBracLoc, RBracLoc, move(Args));