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 //===----------------------------------------------------------------------===//
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/ExprObjC.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "clang/Lex/Preprocessor.h"
21 using namespace clang
;
23 Sema::ExprResult
Sema::ParseObjCStringLiteral(SourceLocation
*AtLocs
,
25 unsigned NumStrings
) {
26 StringLiteral
**Strings
= reinterpret_cast<StringLiteral
**>(strings
);
28 // Most ObjC strings are formed out of a single piece. However, we *can*
29 // have strings formed out of multiple @ strings with multiple pptokens in
30 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
31 // StringLiteral for ObjCStringLiteral to hold onto.
32 StringLiteral
*S
= Strings
[0];
34 // If we have a multi-part string, merge it all together.
35 if (NumStrings
!= 1) {
36 // Concatenate objc strings.
37 llvm::SmallString
<128> StrBuf
;
38 llvm::SmallVector
<SourceLocation
, 8> StrLocs
;
40 for (unsigned i
= 0; i
!= NumStrings
; ++i
) {
43 // ObjC strings can't be wide.
45 Diag(S
->getLocStart(), diag::err_cfstring_literal_not_string_constant
)
46 << S
->getSourceRange();
50 // Get the string data.
51 StrBuf
.append(S
->getStrData(), S
->getStrData()+S
->getByteLength());
53 // Get the locations of the string tokens.
54 StrLocs
.append(S
->tokloc_begin(), S
->tokloc_end());
56 // Free the temporary string.
60 // Create the aggregate string with the appropriate content and location
62 S
= StringLiteral::Create(Context
, &StrBuf
[0], StrBuf
.size(), false,
63 Context
.getPointerType(Context
.CharTy
),
64 &StrLocs
[0], StrLocs
.size());
67 // Verify that this composite string is acceptable for ObjC strings.
68 if (CheckObjCString(S
))
71 // Initialize the constant string interface lazily. This assumes
72 // the NSString interface is seen in this translation unit. Note: We
73 // don't use NSConstantString, since the runtime team considers this
74 // interface private (even though it appears in the header files).
75 QualType Ty
= Context
.getObjCConstantStringInterface();
77 Ty
= Context
.getObjCObjectPointerType(Ty
);
79 IdentifierInfo
*NSIdent
= &Context
.Idents
.get("NSString");
80 NamedDecl
*IF
= LookupName(TUScope
, NSIdent
, LookupOrdinaryName
);
81 if (ObjCInterfaceDecl
*StrIF
= dyn_cast_or_null
<ObjCInterfaceDecl
>(IF
)) {
82 Context
.setObjCConstantStringInterface(StrIF
);
83 Ty
= Context
.getObjCConstantStringInterface();
84 Ty
= Context
.getObjCObjectPointerType(Ty
);
86 // If there is no NSString interface defined then treat constant
87 // strings as untyped objects and let the runtime figure it out later.
88 Ty
= Context
.getObjCIdType();
92 return new (Context
) ObjCStringLiteral(S
, Ty
, AtLocs
[0]);
95 Expr
*Sema::BuildObjCEncodeExpression(SourceLocation AtLoc
,
97 SourceLocation RParenLoc
) {
99 if (EncodedType
->isDependentType())
100 StrTy
= Context
.DependentTy
;
103 Context
.getObjCEncodingForType(EncodedType
, Str
);
105 // The type of @encode is the same as the type of the corresponding string,
106 // which is an array type.
107 StrTy
= Context
.CharTy
;
108 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
109 if (getLangOptions().CPlusPlus
)
111 StrTy
= Context
.getConstantArrayType(StrTy
, llvm::APInt(32, Str
.size()+1),
112 ArrayType::Normal
, 0);
115 return new (Context
) ObjCEncodeExpr(StrTy
, EncodedType
, AtLoc
, RParenLoc
);
118 Sema::ExprResult
Sema::ParseObjCEncodeExpression(SourceLocation AtLoc
,
119 SourceLocation EncodeLoc
,
120 SourceLocation LParenLoc
,
122 SourceLocation RParenLoc
) {
123 QualType EncodedType
= QualType::getFromOpaquePtr(ty
);
125 return BuildObjCEncodeExpression(AtLoc
, EncodedType
, RParenLoc
);
128 Sema::ExprResult
Sema::ParseObjCSelectorExpression(Selector Sel
,
129 SourceLocation AtLoc
,
130 SourceLocation SelLoc
,
131 SourceLocation LParenLoc
,
132 SourceLocation RParenLoc
) {
133 ObjCMethodDecl
*Method
= LookupInstanceMethodInGlobalPool(Sel
,
134 SourceRange(LParenLoc
, RParenLoc
));
136 Method
= LookupFactoryMethodInGlobalPool(Sel
,
137 SourceRange(LParenLoc
, RParenLoc
));
139 Diag(SelLoc
, diag::warn_undeclared_selector
) << Sel
;
141 QualType Ty
= Context
.getObjCSelType();
142 return new (Context
) ObjCSelectorExpr(Ty
, Sel
, AtLoc
, RParenLoc
);
145 Sema::ExprResult
Sema::ParseObjCProtocolExpression(IdentifierInfo
*ProtocolId
,
146 SourceLocation AtLoc
,
147 SourceLocation ProtoLoc
,
148 SourceLocation LParenLoc
,
149 SourceLocation RParenLoc
) {
150 ObjCProtocolDecl
* PDecl
= LookupProtocol(ProtocolId
);
152 Diag(ProtoLoc
, diag::err_undeclared_protocol
) << ProtocolId
;
156 QualType Ty
= Context
.getObjCProtoType();
159 Ty
= Context
.getObjCObjectPointerType(Ty
);
160 return new (Context
) ObjCProtocolExpr(Ty
, PDecl
, AtLoc
, RParenLoc
);
163 bool Sema::CheckMessageArgumentTypes(Expr
**Args
, unsigned NumArgs
,
164 Selector Sel
, ObjCMethodDecl
*Method
,
166 SourceLocation lbrac
, SourceLocation rbrac
,
167 QualType
&ReturnType
) {
169 // Apply default argument promotion as for (C99 6.5.2.2p6).
170 for (unsigned i
= 0; i
!= NumArgs
; i
++)
171 DefaultArgumentPromotion(Args
[i
]);
173 unsigned DiagID
= isClassMessage
? diag::warn_class_method_not_found
:
174 diag::warn_inst_method_not_found
;
176 << Sel
<< isClassMessage
<< SourceRange(lbrac
, rbrac
);
177 ReturnType
= Context
.getObjCIdType();
181 ReturnType
= Method
->getResultType();
183 unsigned NumNamedArgs
= Sel
.getNumArgs();
184 assert(NumArgs
>= NumNamedArgs
&& "Too few arguments for selector!");
186 bool IsError
= false;
187 for (unsigned i
= 0; i
< NumNamedArgs
; i
++) {
188 Expr
*argExpr
= Args
[i
];
189 assert(argExpr
&& "CheckMessageArgumentTypes(): missing expression");
191 QualType lhsType
= Method
->param_begin()[i
]->getType();
192 QualType rhsType
= argExpr
->getType();
194 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8].
195 if (lhsType
->isArrayType())
196 lhsType
= Context
.getArrayDecayedType(lhsType
);
197 else if (lhsType
->isFunctionType())
198 lhsType
= Context
.getPointerType(lhsType
);
200 AssignConvertType Result
=
201 CheckSingleAssignmentConstraints(lhsType
, argExpr
);
202 if (Args
[i
] != argExpr
) // The expression was converted.
203 Args
[i
] = argExpr
; // Make sure we store the converted expression.
206 DiagnoseAssignmentResult(Result
, argExpr
->getLocStart(), lhsType
, rhsType
,
210 // Promote additional arguments to variadic methods.
211 if (Method
->isVariadic()) {
212 for (unsigned i
= NumNamedArgs
; i
< NumArgs
; ++i
)
213 IsError
|= DefaultVariadicArgumentPromotion(Args
[i
], VariadicMethod
);
215 // Check for extra arguments to non-variadic methods.
216 if (NumArgs
!= NumNamedArgs
) {
217 Diag(Args
[NumNamedArgs
]->getLocStart(),
218 diag::err_typecheck_call_too_many_args
)
219 << 2 /*method*/ << Method
->getSourceRange()
220 << SourceRange(Args
[NumNamedArgs
]->getLocStart(),
221 Args
[NumArgs
-1]->getLocEnd());
228 bool Sema::isSelfExpr(Expr
*RExpr
) {
229 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(RExpr
))
230 if (DRE
->getDecl()->getIdentifier() == &Context
.Idents
.get("self"))
235 // Helper method for ActOnClassMethod/ActOnInstanceMethod.
236 // Will search "local" class/category implementations for a method decl.
237 // If failed, then we search in class's root for an instance method.
238 // Returns 0 if no method is found.
239 ObjCMethodDecl
*Sema::LookupPrivateClassMethod(Selector Sel
,
240 ObjCInterfaceDecl
*ClassDecl
) {
241 ObjCMethodDecl
*Method
= 0;
242 // lookup in class and all superclasses
243 while (ClassDecl
&& !Method
) {
244 if (ObjCImplementationDecl
*ImpDecl
245 = LookupObjCImplementation(ClassDecl
->getIdentifier()))
246 Method
= ImpDecl
->getClassMethod(Sel
);
248 // Look through local category implementations associated with the class.
250 for (unsigned i
= 0; i
< ObjCCategoryImpls
.size() && !Method
; i
++) {
251 if (ObjCCategoryImpls
[i
]->getClassInterface() == ClassDecl
)
252 Method
= ObjCCategoryImpls
[i
]->getClassMethod(Sel
);
256 // Before we give up, check if the selector is an instance method.
257 // But only in the root. This matches gcc's behaviour and what the
259 if (!Method
&& !ClassDecl
->getSuperClass()) {
260 Method
= ClassDecl
->lookupInstanceMethod(Sel
);
261 // Look through local category implementations associated
262 // with the root class.
264 Method
= LookupPrivateInstanceMethod(Sel
, ClassDecl
);
267 ClassDecl
= ClassDecl
->getSuperClass();
272 ObjCMethodDecl
*Sema::LookupPrivateInstanceMethod(Selector Sel
,
273 ObjCInterfaceDecl
*ClassDecl
) {
274 ObjCMethodDecl
*Method
= 0;
275 while (ClassDecl
&& !Method
) {
276 // If we have implementations in scope, check "private" methods.
277 if (ObjCImplementationDecl
*ImpDecl
278 = LookupObjCImplementation(ClassDecl
->getIdentifier()))
279 Method
= ImpDecl
->getInstanceMethod(Sel
);
281 // Look through local category implementations associated with the class.
283 for (unsigned i
= 0; i
< ObjCCategoryImpls
.size() && !Method
; i
++) {
284 if (ObjCCategoryImpls
[i
]->getClassInterface() == ClassDecl
)
285 Method
= ObjCCategoryImpls
[i
]->getInstanceMethod(Sel
);
288 ClassDecl
= ClassDecl
->getSuperClass();
293 Action::OwningExprResult
Sema::ActOnClassPropertyRefExpr(
294 IdentifierInfo
&receiverName
,
295 IdentifierInfo
&propertyName
,
296 SourceLocation
&receiverNameLoc
,
297 SourceLocation
&propertyNameLoc
) {
299 ObjCInterfaceDecl
*IFace
= getObjCInterfaceDecl(&receiverName
);
301 // Search for a declared property first.
303 Selector Sel
= PP
.getSelectorTable().getNullarySelector(&propertyName
);
304 ObjCMethodDecl
*Getter
= IFace
->lookupClassMethod(Sel
);
306 // If this reference is in an @implementation, check for 'private' methods.
308 if (ObjCMethodDecl
*CurMeth
= getCurMethodDecl())
309 if (ObjCInterfaceDecl
*ClassDecl
= CurMeth
->getClassInterface())
310 if (ObjCImplementationDecl
*ImpDecl
311 = LookupObjCImplementation(ClassDecl
->getIdentifier()))
312 Getter
= ImpDecl
->getClassMethod(Sel
);
315 // FIXME: refactor/share with ActOnMemberReference().
316 // Check if we can reference this property.
317 if (DiagnoseUseOfDecl(Getter
, propertyNameLoc
))
321 // Look for the matching setter, in case it is needed.
323 SelectorTable::constructSetterName(PP
.getIdentifierTable(),
324 PP
.getSelectorTable(), &propertyName
);
326 ObjCMethodDecl
*Setter
= IFace
->lookupClassMethod(SetterSel
);
328 // If this reference is in an @implementation, also check for 'private'
330 if (ObjCMethodDecl
*CurMeth
= getCurMethodDecl())
331 if (ObjCInterfaceDecl
*ClassDecl
= CurMeth
->getClassInterface())
332 if (ObjCImplementationDecl
*ImpDecl
333 = LookupObjCImplementation(ClassDecl
->getIdentifier()))
334 Setter
= ImpDecl
->getClassMethod(SetterSel
);
336 // Look through local category implementations associated with the class.
338 for (unsigned i
= 0; i
< ObjCCategoryImpls
.size() && !Setter
; i
++) {
339 if (ObjCCategoryImpls
[i
]->getClassInterface() == IFace
)
340 Setter
= ObjCCategoryImpls
[i
]->getClassMethod(SetterSel
);
344 if (Setter
&& DiagnoseUseOfDecl(Setter
, propertyNameLoc
))
347 if (Getter
|| Setter
) {
351 PType
= Getter
->getResultType();
353 for (ObjCMethodDecl::param_iterator PI
= Setter
->param_begin(),
354 E
= Setter
->param_end(); PI
!= E
; ++PI
)
355 PType
= (*PI
)->getType();
357 return Owned(new (Context
) ObjCKVCRefExpr(Getter
, PType
, Setter
,
358 propertyNameLoc
, IFace
, receiverNameLoc
));
360 return ExprError(Diag(propertyNameLoc
, diag::err_property_not_found
)
361 << &propertyName
<< Context
.getObjCInterfaceType(IFace
));
365 // ActOnClassMessage - used for both unary and keyword messages.
366 // ArgExprs is optional - if it is present, the number of expressions
367 // is obtained from Sel.getNumArgs().
368 Sema::ExprResult
Sema::ActOnClassMessage(
370 IdentifierInfo
*receiverName
, Selector Sel
,
371 SourceLocation lbrac
, SourceLocation receiverLoc
,
372 SourceLocation selectorLoc
, SourceLocation rbrac
,
373 ExprTy
**Args
, unsigned NumArgs
)
375 assert(receiverName
&& "missing receiver class name");
377 Expr
**ArgExprs
= reinterpret_cast<Expr
**>(Args
);
378 ObjCInterfaceDecl
* ClassDecl
= 0;
379 bool isSuper
= false;
381 if (receiverName
->isStr("super")) {
382 if (getCurMethodDecl()) {
384 ObjCInterfaceDecl
*OID
= getCurMethodDecl()->getClassInterface();
386 return Diag(lbrac
, diag::error_no_super_class_message
)
387 << getCurMethodDecl()->getDeclName();
388 ClassDecl
= OID
->getSuperClass();
390 return Diag(lbrac
, diag::error_no_super_class
) << OID
->getDeclName();
391 if (getCurMethodDecl()->isInstanceMethod()) {
392 QualType superTy
= Context
.getObjCInterfaceType(ClassDecl
);
393 superTy
= Context
.getObjCObjectPointerType(superTy
);
394 ExprResult ReceiverExpr
= new (Context
) ObjCSuperExpr(SourceLocation(),
396 // We are really in an instance method, redirect.
397 return ActOnInstanceMessage(ReceiverExpr
.get(), Sel
, lbrac
,
398 selectorLoc
, rbrac
, Args
, NumArgs
);
400 // We are sending a message to 'super' within a class method. Do nothing,
401 // the receiver will pass through as 'super' (how convenient:-).
403 // 'super' has been used outside a method context. If a variable named
404 // 'super' has been declared, redirect. If not, produce a diagnostic.
405 NamedDecl
*SuperDecl
= LookupName(S
, receiverName
, LookupOrdinaryName
);
406 ValueDecl
*VD
= dyn_cast_or_null
<ValueDecl
>(SuperDecl
);
408 ExprResult ReceiverExpr
= new (Context
) DeclRefExpr(VD
, VD
->getType(),
410 // We are really in an instance method, redirect.
411 return ActOnInstanceMessage(ReceiverExpr
.get(), Sel
, lbrac
,
412 selectorLoc
, rbrac
, Args
, NumArgs
);
414 return Diag(receiverLoc
, diag::err_undeclared_var_use
) << receiverName
;
417 ClassDecl
= getObjCInterfaceDecl(receiverName
);
419 // The following code allows for the following GCC-ism:
421 // typedef XCElementDisplayRect XCElementGraphicsRect;
423 // @implementation XCRASlice
424 // - whatever { // Note that XCElementGraphicsRect is a typedef name.
425 // _sGraphicsDelegate =[[XCElementGraphicsRect alloc] init];
428 // If necessary, the following lookup could move to getObjCInterfaceDecl().
430 NamedDecl
*IDecl
= LookupName(TUScope
, receiverName
, LookupOrdinaryName
);
431 if (TypedefDecl
*OCTD
= dyn_cast_or_null
<TypedefDecl
>(IDecl
)) {
432 const ObjCInterfaceType
*OCIT
;
433 OCIT
= OCTD
->getUnderlyingType()->getAsObjCInterfaceType();
435 Diag(receiverLoc
, diag::err_invalid_receiver_to_message
);
438 ClassDecl
= OCIT
->getDecl();
441 assert(ClassDecl
&& "missing interface declaration");
442 ObjCMethodDecl
*Method
= 0;
444 if (ClassDecl
->isForwardDecl()) {
445 // A forward class used in messaging is tread as a 'Class'
446 Diag(lbrac
, diag::warn_receiver_forward_class
) << ClassDecl
->getDeclName();
447 Method
= LookupFactoryMethodInGlobalPool(Sel
, SourceRange(lbrac
,rbrac
));
449 Diag(Method
->getLocation(), diag::note_method_sent_forward_class
)
450 << Method
->getDeclName();
453 Method
= ClassDecl
->lookupClassMethod(Sel
);
455 // If we have an implementation in scope, check "private" methods.
457 Method
= LookupPrivateClassMethod(Sel
, ClassDecl
);
459 if (Method
&& DiagnoseUseOfDecl(Method
, receiverLoc
))
462 if (CheckMessageArgumentTypes(ArgExprs
, NumArgs
, Sel
, Method
, true,
463 lbrac
, rbrac
, returnType
))
466 returnType
= returnType
.getNonReferenceType();
468 // If we have the ObjCInterfaceDecl* for the class that is receiving the
469 // message, use that to construct the ObjCMessageExpr. Otherwise pass on the
470 // IdentifierInfo* for the class.
471 // FIXME: need to do a better job handling 'super' usage within a class. For
472 // now, we simply pass the "super" identifier through (which isn't consistent
473 // with instance methods.
475 return new (Context
) ObjCMessageExpr(receiverName
, Sel
, returnType
, Method
,
476 lbrac
, rbrac
, ArgExprs
, NumArgs
);
478 return new (Context
) ObjCMessageExpr(ClassDecl
, Sel
, returnType
, Method
,
479 lbrac
, rbrac
, ArgExprs
, NumArgs
);
482 // ActOnInstanceMessage - used for both unary and keyword messages.
483 // ArgExprs is optional - if it is present, the number of expressions
484 // is obtained from Sel.getNumArgs().
485 Sema::ExprResult
Sema::ActOnInstanceMessage(ExprTy
*receiver
, Selector Sel
,
486 SourceLocation lbrac
,
487 SourceLocation receiverLoc
,
488 SourceLocation rbrac
,
489 ExprTy
**Args
, unsigned NumArgs
) {
490 assert(receiver
&& "missing receiver expression");
492 Expr
**ArgExprs
= reinterpret_cast<Expr
**>(Args
);
493 Expr
*RExpr
= static_cast<Expr
*>(receiver
);
495 // If necessary, apply function/array conversion to the receiver.
496 // C99 6.7.5.3p[7,8].
497 DefaultFunctionArrayConversion(RExpr
);
500 QualType ReceiverCType
=
501 Context
.getCanonicalType(RExpr
->getType()).getUnqualifiedType();
503 // Handle messages to 'super'.
504 if (isa
<ObjCSuperExpr
>(RExpr
)) {
505 ObjCMethodDecl
*Method
= 0;
506 if (ObjCMethodDecl
*CurMeth
= getCurMethodDecl()) {
507 // If we have an interface in scope, check 'super' methods.
508 if (ObjCInterfaceDecl
*ClassDecl
= CurMeth
->getClassInterface())
509 if (ObjCInterfaceDecl
*SuperDecl
= ClassDecl
->getSuperClass()) {
510 Method
= SuperDecl
->lookupInstanceMethod(Sel
);
513 // If we have implementations in scope, check "private" methods.
514 Method
= LookupPrivateInstanceMethod(Sel
, SuperDecl
);
518 if (Method
&& DiagnoseUseOfDecl(Method
, receiverLoc
))
521 if (CheckMessageArgumentTypes(ArgExprs
, NumArgs
, Sel
, Method
, false,
522 lbrac
, rbrac
, returnType
))
525 returnType
= returnType
.getNonReferenceType();
526 return new (Context
) ObjCMessageExpr(RExpr
, Sel
, returnType
, Method
, lbrac
,
527 rbrac
, ArgExprs
, NumArgs
);
530 // Handle messages to id.
531 if (ReceiverCType
== Context
.getCanonicalType(Context
.getObjCIdType()) ||
532 ReceiverCType
->isBlockPointerType() ||
533 Context
.isObjCNSObjectType(RExpr
->getType())) {
534 ObjCMethodDecl
*Method
= LookupInstanceMethodInGlobalPool(
535 Sel
, SourceRange(lbrac
,rbrac
));
537 Method
= LookupFactoryMethodInGlobalPool(Sel
, SourceRange(lbrac
, rbrac
));
538 if (CheckMessageArgumentTypes(ArgExprs
, NumArgs
, Sel
, Method
, false,
539 lbrac
, rbrac
, returnType
))
541 returnType
= returnType
.getNonReferenceType();
542 return new (Context
) ObjCMessageExpr(RExpr
, Sel
, returnType
, Method
, lbrac
,
543 rbrac
, ArgExprs
, NumArgs
);
546 // Handle messages to Class.
547 if (ReceiverCType
== Context
.getCanonicalType(Context
.getObjCClassType())) {
548 ObjCMethodDecl
*Method
= 0;
550 if (ObjCMethodDecl
*CurMeth
= getCurMethodDecl()) {
551 if (ObjCInterfaceDecl
*ClassDecl
= CurMeth
->getClassInterface()) {
552 // First check the public methods in the class interface.
553 Method
= ClassDecl
->lookupClassMethod(Sel
);
556 Method
= LookupPrivateClassMethod(Sel
, ClassDecl
);
558 if (Method
&& DiagnoseUseOfDecl(Method
, receiverLoc
))
562 // If not messaging 'self', look for any factory method named 'Sel'.
563 if (!isSelfExpr(RExpr
)) {
564 Method
= LookupFactoryMethodInGlobalPool(Sel
, SourceRange(lbrac
,rbrac
));
566 // If no class (factory) method was found, check if an _instance_
567 // method of the same name exists in the root class only.
568 Method
= LookupInstanceMethodInGlobalPool(
569 Sel
, SourceRange(lbrac
,rbrac
));
571 if (const ObjCInterfaceDecl
*ID
=
572 dyn_cast
<ObjCInterfaceDecl
>(Method
->getDeclContext())) {
573 if (ID
->getSuperClass())
574 Diag(lbrac
, diag::warn_root_inst_method_not_found
)
575 << Sel
<< SourceRange(lbrac
, rbrac
);
580 if (CheckMessageArgumentTypes(ArgExprs
, NumArgs
, Sel
, Method
, false,
581 lbrac
, rbrac
, returnType
))
583 returnType
= returnType
.getNonReferenceType();
584 return new (Context
) ObjCMessageExpr(RExpr
, Sel
, returnType
, Method
, lbrac
,
585 rbrac
, ArgExprs
, NumArgs
);
588 ObjCMethodDecl
*Method
= 0;
589 ObjCInterfaceDecl
* ClassDecl
= 0;
591 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
592 // long as one of the protocols implements the selector (if not, warn).
593 if (const ObjCObjectPointerType
*QIdTy
=
594 ReceiverCType
->getAsObjCQualifiedIdType()) {
595 // Search protocols for instance methods.
596 for (ObjCObjectPointerType::qual_iterator I
= QIdTy
->qual_begin(),
597 E
= QIdTy
->qual_end(); I
!= E
; ++I
) {
598 ObjCProtocolDecl
*PDecl
= *I
;
599 if (PDecl
&& (Method
= PDecl
->lookupInstanceMethod(Sel
)))
601 // Since we aren't supporting "Class<foo>", look for a class method.
602 if (PDecl
&& (Method
= PDecl
->lookupClassMethod(Sel
)))
605 } else if (const ObjCObjectPointerType
*OCIType
=
606 ReceiverCType
->getAsObjCInterfacePointerType()) {
607 // We allow sending a message to a pointer to an interface (an object).
609 ClassDecl
= OCIType
->getInterfaceDecl();
610 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
611 // faster than the following method (which can do *many* linear searches).
612 // The idea is to add class info to InstanceMethodPool.
613 Method
= ClassDecl
->lookupInstanceMethod(Sel
);
616 // Search protocol qualifiers.
617 for (ObjCObjectPointerType::qual_iterator QI
= OCIType
->qual_begin(),
618 E
= OCIType
->qual_end(); QI
!= E
; ++QI
) {
619 if ((Method
= (*QI
)->lookupInstanceMethod(Sel
)))
624 // If we have implementations in scope, check "private" methods.
625 Method
= LookupPrivateInstanceMethod(Sel
, ClassDecl
);
627 if (!Method
&& !isSelfExpr(RExpr
)) {
628 // If we still haven't found a method, look in the global pool. This
629 // behavior isn't very desirable, however we need it for GCC
630 // compatibility. FIXME: should we deviate??
631 if (OCIType
->qual_empty()) {
632 Method
= LookupInstanceMethodInGlobalPool(
633 Sel
, SourceRange(lbrac
,rbrac
));
634 if (Method
&& !OCIType
->getInterfaceDecl()->isForwardDecl())
635 Diag(lbrac
, diag::warn_maynot_respond
)
636 << OCIType
->getInterfaceDecl()->getIdentifier()->getName() << Sel
;
640 if (Method
&& DiagnoseUseOfDecl(Method
, receiverLoc
))
642 } else if (!Context
.getObjCIdType().isNull() &&
643 (ReceiverCType
->isPointerType() ||
644 (ReceiverCType
->isIntegerType() &&
645 ReceiverCType
->isScalarType()))) {
646 // Implicitly convert integers and pointers to 'id' but emit a warning.
647 Diag(lbrac
, diag::warn_bad_receiver_type
)
648 << RExpr
->getType() << RExpr
->getSourceRange();
649 ImpCastExprToType(RExpr
, Context
.getObjCIdType());
651 // Reject other random receiver types (e.g. structs).
652 Diag(lbrac
, diag::err_bad_receiver_type
)
653 << RExpr
->getType() << RExpr
->getSourceRange();
658 DiagnoseSentinelCalls(Method
, receiverLoc
, ArgExprs
, NumArgs
);
659 if (CheckMessageArgumentTypes(ArgExprs
, NumArgs
, Sel
, Method
, false,
660 lbrac
, rbrac
, returnType
))
662 returnType
= returnType
.getNonReferenceType();
663 return new (Context
) ObjCMessageExpr(RExpr
, Sel
, returnType
, Method
, lbrac
,
664 rbrac
, ArgExprs
, NumArgs
);
667 //===----------------------------------------------------------------------===//
668 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's.
669 //===----------------------------------------------------------------------===//
671 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the
672 /// inheritance hierarchy of 'rProto'.
673 static bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl
*lProto
,
674 ObjCProtocolDecl
*rProto
) {
675 if (lProto
== rProto
)
677 for (ObjCProtocolDecl::protocol_iterator PI
= rProto
->protocol_begin(),
678 E
= rProto
->protocol_end(); PI
!= E
; ++PI
)
679 if (ProtocolCompatibleWithProtocol(lProto
, *PI
))
684 /// ClassImplementsProtocol - Checks that 'lProto' protocol
685 /// has been implemented in IDecl class, its super class or categories (if
686 /// lookupCategory is true).
687 static bool ClassImplementsProtocol(ObjCProtocolDecl
*lProto
,
688 ObjCInterfaceDecl
*IDecl
,
690 bool RHSIsQualifiedID
= false) {
692 // 1st, look up the class.
693 const ObjCList
<ObjCProtocolDecl
> &Protocols
=
694 IDecl
->getReferencedProtocols();
696 for (ObjCList
<ObjCProtocolDecl
>::iterator PI
= Protocols
.begin(),
697 E
= Protocols
.end(); PI
!= E
; ++PI
) {
698 if (ProtocolCompatibleWithProtocol(lProto
, *PI
))
700 // This is dubious and is added to be compatible with gcc. In gcc, it is
701 // also allowed assigning a protocol-qualified 'id' type to a LHS object
702 // when protocol in qualified LHS is in list of protocols in the rhs 'id'
703 // object. This IMO, should be a bug.
704 // FIXME: Treat this as an extension, and flag this as an error when GCC
705 // extensions are not enabled.
706 if (RHSIsQualifiedID
&& ProtocolCompatibleWithProtocol(*PI
, lProto
))
710 // 2nd, look up the category.
712 for (ObjCCategoryDecl
*CDecl
= IDecl
->getCategoryList(); CDecl
;
713 CDecl
= CDecl
->getNextClassCategory()) {
714 for (ObjCCategoryDecl::protocol_iterator PI
= CDecl
->protocol_begin(),
715 E
= CDecl
->protocol_end(); PI
!= E
; ++PI
)
716 if (ProtocolCompatibleWithProtocol(lProto
, *PI
))
720 // 3rd, look up the super class(s)
721 if (IDecl
->getSuperClass())
723 ClassImplementsProtocol(lProto
, IDecl
->getSuperClass(), lookupCategory
,
729 /// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...>
730 /// return true if lhs's protocols conform to rhs's protocol; false
732 bool Sema::QualifiedIdConformsQualifiedId(QualType lhs
, QualType rhs
) {
733 if (lhs
->isObjCQualifiedIdType() && rhs
->isObjCQualifiedIdType())
734 return ObjCQualifiedIdTypesAreCompatible(lhs
, rhs
, false);
738 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an
739 /// ObjCQualifiedIDType.
740 /// FIXME: Move to ASTContext::typesAreCompatible() and friends.
741 bool Sema::ObjCQualifiedIdTypesAreCompatible(QualType lhs
, QualType rhs
,
743 // Allow id<P..> and an 'id' or void* type in all cases.
744 if (lhs
->isVoidPointerType() ||
745 lhs
->isObjCIdType() || lhs
->isObjCClassType())
747 else if (rhs
->isVoidPointerType() ||
748 rhs
->isObjCIdType() || rhs
->isObjCClassType())
751 if (const ObjCObjectPointerType
*lhsQID
= lhs
->getAsObjCQualifiedIdType()) {
752 const ObjCObjectPointerType
*rhsOPT
= rhs
->getAsObjCObjectPointerType();
754 if (!rhsOPT
) return false;
756 if (rhsOPT
->qual_empty()) {
757 // If the RHS is a unqualified interface pointer "NSString*",
758 // make sure we check the class hierarchy.
759 if (ObjCInterfaceDecl
*rhsID
= rhsOPT
->getInterfaceDecl()) {
760 for (ObjCObjectPointerType::qual_iterator I
= lhsQID
->qual_begin(),
761 E
= lhsQID
->qual_end(); I
!= E
; ++I
) {
762 // when comparing an id<P> on lhs with a static type on rhs,
763 // see if static class implements all of id's protocols, directly or
764 // through its super class and categories.
765 if (!ClassImplementsProtocol(*I
, rhsID
, true))
769 // If there are no qualifiers and no interface, we have an 'id'.
772 // Both the right and left sides have qualifiers.
773 for (ObjCObjectPointerType::qual_iterator I
= lhsQID
->qual_begin(),
774 E
= lhsQID
->qual_end(); I
!= E
; ++I
) {
775 ObjCProtocolDecl
*lhsProto
= *I
;
778 // when comparing an id<P> on lhs with a static type on rhs,
779 // see if static class implements all of id's protocols, directly or
780 // through its super class and categories.
781 for (ObjCObjectPointerType::qual_iterator J
= rhsOPT
->qual_begin(),
782 E
= rhsOPT
->qual_end(); J
!= E
; ++J
) {
783 ObjCProtocolDecl
*rhsProto
= *J
;
784 if (ProtocolCompatibleWithProtocol(lhsProto
, rhsProto
) ||
785 (compare
&& ProtocolCompatibleWithProtocol(rhsProto
, lhsProto
))) {
790 // If the RHS is a qualified interface pointer "NSString<P>*",
791 // make sure we check the class hierarchy.
792 if (ObjCInterfaceDecl
*rhsID
= rhsOPT
->getInterfaceDecl()) {
793 for (ObjCObjectPointerType::qual_iterator I
= lhsQID
->qual_begin(),
794 E
= lhsQID
->qual_end(); I
!= E
; ++I
) {
795 // when comparing an id<P> on lhs with a static type on rhs,
796 // see if static class implements all of id's protocols, directly or
797 // through its super class and categories.
798 if (ClassImplementsProtocol(*I
, rhsID
, true)) {
811 const ObjCObjectPointerType
*rhsQID
= rhs
->getAsObjCQualifiedIdType();
812 assert(rhsQID
&& "One of the LHS/RHS should be id<x>");
814 if (const ObjCObjectPointerType
*lhsOPT
=
815 lhs
->getAsObjCInterfacePointerType()) {
816 if (lhsOPT
->qual_empty()) {
818 if (ObjCInterfaceDecl
*lhsID
= lhsOPT
->getInterfaceDecl()) {
819 for (ObjCObjectPointerType::qual_iterator I
= rhsQID
->qual_begin(),
820 E
= rhsQID
->qual_end(); I
!= E
; ++I
) {
821 // when comparing an id<P> on lhs with a static type on rhs,
822 // see if static class implements all of id's protocols, directly or
823 // through its super class and categories.
824 if (ClassImplementsProtocol(*I
, lhsID
, true)) {
834 // Both the right and left sides have qualifiers.
835 for (ObjCObjectPointerType::qual_iterator I
= lhsOPT
->qual_begin(),
836 E
= lhsOPT
->qual_end(); I
!= E
; ++I
) {
837 ObjCProtocolDecl
*lhsProto
= *I
;
840 // when comparing an id<P> on lhs with a static type on rhs,
841 // see if static class implements all of id's protocols, directly or
842 // through its super class and categories.
843 for (ObjCObjectPointerType::qual_iterator J
= rhsQID
->qual_begin(),
844 E
= rhsQID
->qual_end(); J
!= E
; ++J
) {
845 ObjCProtocolDecl
*rhsProto
= *J
;
846 if (ProtocolCompatibleWithProtocol(lhsProto
, rhsProto
) ||
847 (compare
&& ProtocolCompatibleWithProtocol(rhsProto
, lhsProto
))) {
857 // FIXME: The code below will be removed when ObjCQualifiedInterfaceType is
859 if (!lhs
->isPointerType())
862 QualType ltype
= lhs
->getAsPointerType()->getPointeeType();
863 if (const ObjCInterfaceType
*lhsQI
=
864 ltype
->getAsObjCQualifiedInterfaceType()) {
865 ObjCObjectPointerType::qual_iterator LHSProtoI
= lhsQI
->qual_begin();
866 ObjCObjectPointerType::qual_iterator LHSProtoE
= lhsQI
->qual_end();
867 for (; LHSProtoI
!= LHSProtoE
; ++LHSProtoI
) {
869 ObjCProtocolDecl
*lhsProto
= *LHSProtoI
;
870 for (ObjCObjectPointerType::qual_iterator I
= rhsQID
->qual_begin(),
871 E
= rhsQID
->qual_end(); I
!= E
; ++I
) {
872 ObjCProtocolDecl
*rhsProto
= *I
;
873 if (ProtocolCompatibleWithProtocol(lhsProto
, rhsProto
) ||
874 (compare
&& ProtocolCompatibleWithProtocol(rhsProto
, lhsProto
))) {