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/ScopeInfo.h"
18 #include "clang/Sema/Initialization.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/TypeLoc.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "clang/Lex/Preprocessor.h"
26 using namespace clang
;
29 ExprResult
Sema::ParseObjCStringLiteral(SourceLocation
*AtLocs
,
31 unsigned NumStrings
) {
32 StringLiteral
**Strings
= reinterpret_cast<StringLiteral
**>(strings
);
34 // Most ObjC strings are formed out of a single piece. However, we *can*
35 // have strings formed out of multiple @ strings with multiple pptokens in
36 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
37 // StringLiteral for ObjCStringLiteral to hold onto.
38 StringLiteral
*S
= Strings
[0];
40 // If we have a multi-part string, merge it all together.
41 if (NumStrings
!= 1) {
42 // Concatenate objc strings.
43 llvm::SmallString
<128> StrBuf
;
44 llvm::SmallVector
<SourceLocation
, 8> StrLocs
;
46 for (unsigned i
= 0; i
!= NumStrings
; ++i
) {
49 // ObjC strings can't be wide.
51 Diag(S
->getLocStart(), diag::err_cfstring_literal_not_string_constant
)
52 << S
->getSourceRange();
57 StrBuf
+= S
->getString();
59 // Get the locations of the string tokens.
60 StrLocs
.append(S
->tokloc_begin(), S
->tokloc_end());
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
=0;
83 std::string
StringClass(getLangOptions().ObjCConstantStringClass
);
85 if (StringClass
.empty())
86 NSIdent
= &Context
.Idents
.get("NSConstantString");
88 NSIdent
= &Context
.Idents
.get(StringClass
);
90 NamedDecl
*IF
= LookupSingleName(TUScope
, NSIdent
, AtLocs
[0],
92 if (ObjCInterfaceDecl
*StrIF
= dyn_cast_or_null
<ObjCInterfaceDecl
>(IF
)) {
93 Context
.setObjCConstantStringInterface(StrIF
);
94 Ty
= Context
.getObjCConstantStringInterface();
95 Ty
= Context
.getObjCObjectPointerType(Ty
);
97 // If there is no NSConstantString interface defined then treat this
98 // as error and recover from it.
99 Diag(S
->getLocStart(), diag::err_no_nsconstant_string_class
) << NSIdent
100 << S
->getSourceRange();
101 Ty
= Context
.getObjCIdType();
104 IdentifierInfo
*NSIdent
= &Context
.Idents
.get("NSString");
105 NamedDecl
*IF
= LookupSingleName(TUScope
, NSIdent
, AtLocs
[0],
107 if (ObjCInterfaceDecl
*StrIF
= dyn_cast_or_null
<ObjCInterfaceDecl
>(IF
)) {
108 Context
.setObjCConstantStringInterface(StrIF
);
109 Ty
= Context
.getObjCConstantStringInterface();
110 Ty
= Context
.getObjCObjectPointerType(Ty
);
112 // If there is no NSString interface defined then treat constant
113 // strings as untyped objects and let the runtime figure it out later.
114 Ty
= Context
.getObjCIdType();
118 return new (Context
) ObjCStringLiteral(S
, Ty
, AtLocs
[0]);
121 Expr
*Sema::BuildObjCEncodeExpression(SourceLocation AtLoc
,
122 TypeSourceInfo
*EncodedTypeInfo
,
123 SourceLocation RParenLoc
) {
124 QualType EncodedType
= EncodedTypeInfo
->getType();
126 if (EncodedType
->isDependentType())
127 StrTy
= Context
.DependentTy
;
130 Context
.getObjCEncodingForType(EncodedType
, Str
);
132 // The type of @encode is the same as the type of the corresponding string,
133 // which is an array type.
134 StrTy
= Context
.CharTy
;
135 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
136 if (getLangOptions().CPlusPlus
|| getLangOptions().ConstStrings
)
138 StrTy
= Context
.getConstantArrayType(StrTy
, llvm::APInt(32, Str
.size()+1),
139 ArrayType::Normal
, 0);
142 return new (Context
) ObjCEncodeExpr(StrTy
, EncodedTypeInfo
, AtLoc
, RParenLoc
);
145 ExprResult
Sema::ParseObjCEncodeExpression(SourceLocation AtLoc
,
146 SourceLocation EncodeLoc
,
147 SourceLocation LParenLoc
,
149 SourceLocation RParenLoc
) {
150 // FIXME: Preserve type source info ?
151 TypeSourceInfo
*TInfo
;
152 QualType EncodedType
= GetTypeFromParser(ty
, &TInfo
);
154 TInfo
= Context
.getTrivialTypeSourceInfo(EncodedType
,
155 PP
.getLocForEndOfToken(LParenLoc
));
157 return BuildObjCEncodeExpression(AtLoc
, TInfo
, RParenLoc
);
160 ExprResult
Sema::ParseObjCSelectorExpression(Selector Sel
,
161 SourceLocation AtLoc
,
162 SourceLocation SelLoc
,
163 SourceLocation LParenLoc
,
164 SourceLocation RParenLoc
) {
165 ObjCMethodDecl
*Method
= LookupInstanceMethodInGlobalPool(Sel
,
166 SourceRange(LParenLoc
, RParenLoc
), false, false);
168 Method
= LookupFactoryMethodInGlobalPool(Sel
,
169 SourceRange(LParenLoc
, RParenLoc
));
171 Diag(SelLoc
, diag::warn_undeclared_selector
) << Sel
;
173 llvm::DenseMap
<Selector
, SourceLocation
>::iterator Pos
174 = ReferencedSelectors
.find(Sel
);
175 if (Pos
== ReferencedSelectors
.end())
176 ReferencedSelectors
.insert(std::make_pair(Sel
, SelLoc
));
178 QualType Ty
= Context
.getObjCSelType();
179 return new (Context
) ObjCSelectorExpr(Ty
, Sel
, AtLoc
, RParenLoc
);
182 ExprResult
Sema::ParseObjCProtocolExpression(IdentifierInfo
*ProtocolId
,
183 SourceLocation AtLoc
,
184 SourceLocation ProtoLoc
,
185 SourceLocation LParenLoc
,
186 SourceLocation RParenLoc
) {
187 ObjCProtocolDecl
* PDecl
= LookupProtocol(ProtocolId
, ProtoLoc
);
189 Diag(ProtoLoc
, diag::err_undeclared_protocol
) << ProtocolId
;
193 QualType Ty
= Context
.getObjCProtoType();
196 Ty
= Context
.getObjCObjectPointerType(Ty
);
197 return new (Context
) ObjCProtocolExpr(Ty
, PDecl
, AtLoc
, RParenLoc
);
200 /// Try to capture an implicit reference to 'self'.
201 ObjCMethodDecl
*Sema::tryCaptureObjCSelf() {
202 // Ignore block scopes: we can capture through them.
203 DeclContext
*DC
= CurContext
;
205 if (isa
<BlockDecl
>(DC
)) DC
= cast
<BlockDecl
>(DC
)->getDeclContext();
206 else if (isa
<EnumDecl
>(DC
)) DC
= cast
<EnumDecl
>(DC
)->getDeclContext();
210 // If we're not in an ObjC method, error out. Note that, unlike the
211 // C++ case, we don't require an instance method --- class methods
212 // still have a 'self', and we really do still need to capture it!
213 ObjCMethodDecl
*method
= dyn_cast
<ObjCMethodDecl
>(DC
);
217 ImplicitParamDecl
*self
= method
->getSelfDecl();
218 assert(self
&& "capturing 'self' in non-definition?");
220 // Mark that we're closing on 'this' in all the block scopes, if applicable.
221 for (unsigned idx
= FunctionScopes
.size() - 1;
222 isa
<BlockScopeInfo
>(FunctionScopes
[idx
]);
224 BlockScopeInfo
*blockScope
= cast
<BlockScopeInfo
>(FunctionScopes
[idx
]);
225 unsigned &captureIndex
= blockScope
->CaptureMap
[self
];
226 if (captureIndex
) break;
228 bool nested
= isa
<BlockScopeInfo
>(FunctionScopes
[idx
-1]);
229 blockScope
->Captures
.push_back(
230 BlockDecl::Capture(self
, /*byref*/ false, nested
, /*copy*/ 0));
231 captureIndex
= blockScope
->Captures
.size(); // +1
238 bool Sema::CheckMessageArgumentTypes(Expr
**Args
, unsigned NumArgs
,
239 Selector Sel
, ObjCMethodDecl
*Method
,
241 SourceLocation lbrac
, SourceLocation rbrac
,
242 QualType
&ReturnType
, ExprValueKind
&VK
) {
244 // Apply default argument promotion as for (C99 6.5.2.2p6).
245 for (unsigned i
= 0; i
!= NumArgs
; i
++) {
246 if (Args
[i
]->isTypeDependent())
249 DefaultArgumentPromotion(Args
[i
]);
252 unsigned DiagID
= isClassMessage
? diag::warn_class_method_not_found
:
253 diag::warn_inst_method_not_found
;
255 << Sel
<< isClassMessage
<< SourceRange(lbrac
, rbrac
);
256 ReturnType
= Context
.getObjCIdType();
261 ReturnType
= Method
->getSendResultType();
262 VK
= Expr::getValueKindForType(Method
->getResultType());
264 unsigned NumNamedArgs
= Sel
.getNumArgs();
265 // Method might have more arguments than selector indicates. This is due
266 // to addition of c-style arguments in method.
267 if (Method
->param_size() > Sel
.getNumArgs())
268 NumNamedArgs
= Method
->param_size();
269 // FIXME. This need be cleaned up.
270 if (NumArgs
< NumNamedArgs
) {
271 Diag(lbrac
, diag::err_typecheck_call_too_few_args
)
272 << 2 << NumNamedArgs
<< NumArgs
;
276 bool IsError
= false;
277 for (unsigned i
= 0; i
< NumNamedArgs
; i
++) {
278 // We can't do any type-checking on a type-dependent argument.
279 if (Args
[i
]->isTypeDependent())
282 Expr
*argExpr
= Args
[i
];
284 ParmVarDecl
*Param
= Method
->param_begin()[i
];
285 assert(argExpr
&& "CheckMessageArgumentTypes(): missing expression");
287 if (RequireCompleteType(argExpr
->getSourceRange().getBegin(),
289 PDiag(diag::err_call_incomplete_argument
)
290 << argExpr
->getSourceRange()))
293 InitializedEntity Entity
= InitializedEntity::InitializeParameter(Context
,
295 ExprResult ArgE
= PerformCopyInitialization(Entity
, lbrac
, Owned(argExpr
));
296 if (ArgE
.isInvalid())
299 Args
[i
] = ArgE
.takeAs
<Expr
>();
302 // Promote additional arguments to variadic methods.
303 if (Method
->isVariadic()) {
304 for (unsigned i
= NumNamedArgs
; i
< NumArgs
; ++i
) {
305 if (Args
[i
]->isTypeDependent())
308 IsError
|= DefaultVariadicArgumentPromotion(Args
[i
], VariadicMethod
, 0);
311 // Check for extra arguments to non-variadic methods.
312 if (NumArgs
!= NumNamedArgs
) {
313 Diag(Args
[NumNamedArgs
]->getLocStart(),
314 diag::err_typecheck_call_too_many_args
)
315 << 2 /*method*/ << NumNamedArgs
<< NumArgs
316 << Method
->getSourceRange()
317 << SourceRange(Args
[NumNamedArgs
]->getLocStart(),
318 Args
[NumArgs
-1]->getLocEnd());
322 DiagnoseSentinelCalls(Method
, lbrac
, Args
, NumArgs
);
326 bool Sema::isSelfExpr(Expr
*RExpr
) {
327 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(RExpr
))
328 if (ICE
->getCastKind() == CK_LValueToRValue
)
329 RExpr
= ICE
->getSubExpr();
330 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(RExpr
))
331 if (DRE
->getDecl()->getIdentifier() == &Context
.Idents
.get("self"))
336 // Helper method for ActOnClassMethod/ActOnInstanceMethod.
337 // Will search "local" class/category implementations for a method decl.
338 // If failed, then we search in class's root for an instance method.
339 // Returns 0 if no method is found.
340 ObjCMethodDecl
*Sema::LookupPrivateClassMethod(Selector Sel
,
341 ObjCInterfaceDecl
*ClassDecl
) {
342 ObjCMethodDecl
*Method
= 0;
343 // lookup in class and all superclasses
344 while (ClassDecl
&& !Method
) {
345 if (ObjCImplementationDecl
*ImpDecl
= ClassDecl
->getImplementation())
346 Method
= ImpDecl
->getClassMethod(Sel
);
348 // Look through local category implementations associated with the class.
350 Method
= ClassDecl
->getCategoryClassMethod(Sel
);
352 // Before we give up, check if the selector is an instance method.
353 // But only in the root. This matches gcc's behaviour and what the
355 if (!Method
&& !ClassDecl
->getSuperClass()) {
356 Method
= ClassDecl
->lookupInstanceMethod(Sel
);
357 // Look through local category implementations associated
358 // with the root class.
360 Method
= LookupPrivateInstanceMethod(Sel
, ClassDecl
);
363 ClassDecl
= ClassDecl
->getSuperClass();
368 ObjCMethodDecl
*Sema::LookupPrivateInstanceMethod(Selector Sel
,
369 ObjCInterfaceDecl
*ClassDecl
) {
370 ObjCMethodDecl
*Method
= 0;
371 while (ClassDecl
&& !Method
) {
372 // If we have implementations in scope, check "private" methods.
373 if (ObjCImplementationDecl
*ImpDecl
= ClassDecl
->getImplementation())
374 Method
= ImpDecl
->getInstanceMethod(Sel
);
376 // Look through local category implementations associated with the class.
378 Method
= ClassDecl
->getCategoryInstanceMethod(Sel
);
379 ClassDecl
= ClassDecl
->getSuperClass();
384 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
385 /// objective C interface. This is a property reference expression.
387 HandleExprPropertyRefExpr(const ObjCObjectPointerType
*OPT
,
388 Expr
*BaseExpr
, DeclarationName MemberName
,
389 SourceLocation MemberLoc
,
390 SourceLocation SuperLoc
, QualType SuperType
,
392 const ObjCInterfaceType
*IFaceT
= OPT
->getInterfaceType();
393 ObjCInterfaceDecl
*IFace
= IFaceT
->getDecl();
394 IdentifierInfo
*Member
= MemberName
.getAsIdentifierInfo();
396 if (IFace
->isForwardDecl()) {
397 Diag(MemberLoc
, diag::err_property_not_found_forward_class
)
398 << MemberName
<< QualType(OPT
, 0);
399 Diag(IFace
->getLocation(), diag::note_forward_class
);
402 // Search for a declared property first.
403 if (ObjCPropertyDecl
*PD
= IFace
->FindPropertyDeclaration(Member
)) {
404 // Check whether we can reference this property.
405 if (DiagnoseUseOfDecl(PD
, MemberLoc
))
407 QualType ResTy
= PD
->getType();
408 Selector Sel
= PP
.getSelectorTable().getNullarySelector(Member
);
409 ObjCMethodDecl
*Getter
= IFace
->lookupInstanceMethod(Sel
);
410 if (DiagnosePropertyAccessorMismatch(PD
, Getter
, MemberLoc
))
411 ResTy
= Getter
->getResultType();
414 return Owned(new (Context
) ObjCPropertyRefExpr(PD
, ResTy
,
415 VK_LValue
, OK_ObjCProperty
,
417 SuperLoc
, SuperType
));
419 return Owned(new (Context
) ObjCPropertyRefExpr(PD
, ResTy
,
420 VK_LValue
, OK_ObjCProperty
,
421 MemberLoc
, BaseExpr
));
423 // Check protocols on qualified interfaces.
424 for (ObjCObjectPointerType::qual_iterator I
= OPT
->qual_begin(),
425 E
= OPT
->qual_end(); I
!= E
; ++I
)
426 if (ObjCPropertyDecl
*PD
= (*I
)->FindPropertyDeclaration(Member
)) {
427 // Check whether we can reference this property.
428 if (DiagnoseUseOfDecl(PD
, MemberLoc
))
431 return Owned(new (Context
) ObjCPropertyRefExpr(PD
, PD
->getType(),
435 SuperLoc
, SuperType
));
437 return Owned(new (Context
) ObjCPropertyRefExpr(PD
, PD
->getType(),
443 // If that failed, look for an "implicit" property by seeing if the nullary
444 // selector is implemented.
446 // FIXME: The logic for looking up nullary and unary selectors should be
447 // shared with the code in ActOnInstanceMessage.
449 Selector Sel
= PP
.getSelectorTable().getNullarySelector(Member
);
450 ObjCMethodDecl
*Getter
= IFace
->lookupInstanceMethod(Sel
);
452 // If this reference is in an @implementation, check for 'private' methods.
454 Getter
= IFace
->lookupPrivateMethod(Sel
);
456 // Look through local category implementations associated with the class.
458 Getter
= IFace
->getCategoryInstanceMethod(Sel
);
460 // Check if we can reference this property.
461 if (DiagnoseUseOfDecl(Getter
, MemberLoc
))
464 // If we found a getter then this may be a valid dot-reference, we
465 // will look for the matching setter, in case it is needed.
467 SelectorTable::constructSetterName(PP
.getIdentifierTable(),
468 PP
.getSelectorTable(), Member
);
469 ObjCMethodDecl
*Setter
= IFace
->lookupInstanceMethod(SetterSel
);
471 // If this reference is in an @implementation, also check for 'private'
473 Setter
= IFace
->lookupPrivateMethod(SetterSel
);
475 // Look through local category implementations associated with the class.
477 Setter
= IFace
->getCategoryInstanceMethod(SetterSel
);
479 if (Setter
&& DiagnoseUseOfDecl(Setter
, MemberLoc
))
482 if (Getter
|| Setter
) {
485 PType
= Getter
->getSendResultType();
487 ParmVarDecl
*ArgDecl
= *Setter
->param_begin();
488 PType
= ArgDecl
->getType();
491 ExprValueKind VK
= VK_LValue
;
492 ExprObjectKind OK
= OK_ObjCProperty
;
493 if (!getLangOptions().CPlusPlus
&& !PType
.hasQualifiers() &&
495 VK
= VK_RValue
, OK
= OK_Ordinary
;
498 return Owned(new (Context
) ObjCPropertyRefExpr(Getter
, Setter
,
501 SuperLoc
, SuperType
));
503 return Owned(new (Context
) ObjCPropertyRefExpr(Getter
, Setter
,
505 MemberLoc
, BaseExpr
));
509 // Attempt to correct for typos in property names.
510 LookupResult
Res(*this, MemberName
, MemberLoc
, LookupOrdinaryName
);
511 if (CorrectTypo(Res
, 0, 0, IFace
, false, CTC_NoKeywords
, OPT
) &&
512 Res
.getAsSingle
<ObjCPropertyDecl
>()) {
513 DeclarationName TypoResult
= Res
.getLookupName();
514 Diag(MemberLoc
, diag::err_property_not_found_suggest
)
515 << MemberName
<< QualType(OPT
, 0) << TypoResult
516 << FixItHint::CreateReplacement(MemberLoc
, TypoResult
.getAsString());
517 ObjCPropertyDecl
*Property
= Res
.getAsSingle
<ObjCPropertyDecl
>();
518 Diag(Property
->getLocation(), diag::note_previous_decl
)
519 << Property
->getDeclName();
520 return HandleExprPropertyRefExpr(OPT
, BaseExpr
, TypoResult
, MemberLoc
,
521 SuperLoc
, SuperType
, Super
);
523 ObjCInterfaceDecl
*ClassDeclared
;
524 if (ObjCIvarDecl
*Ivar
=
525 IFace
->lookupInstanceVariable(Member
, ClassDeclared
)) {
526 QualType T
= Ivar
->getType();
527 if (const ObjCObjectPointerType
* OBJPT
=
528 T
->getAsObjCInterfacePointerType()) {
529 const ObjCInterfaceType
*IFaceT
= OBJPT
->getInterfaceType();
530 if (ObjCInterfaceDecl
*IFace
= IFaceT
->getDecl())
531 if (IFace
->isForwardDecl()) {
532 Diag(MemberLoc
, diag::err_property_not_as_forward_class
)
533 << MemberName
<< IFace
;
534 Diag(IFace
->getLocation(), diag::note_forward_class
);
540 Diag(MemberLoc
, diag::err_property_not_found
)
541 << MemberName
<< QualType(OPT
, 0);
543 Diag(Setter
->getLocation(), diag::note_getter_unavailable
)
544 << MemberName
<< BaseExpr
->getSourceRange();
551 ActOnClassPropertyRefExpr(IdentifierInfo
&receiverName
,
552 IdentifierInfo
&propertyName
,
553 SourceLocation receiverNameLoc
,
554 SourceLocation propertyNameLoc
) {
556 IdentifierInfo
*receiverNamePtr
= &receiverName
;
557 ObjCInterfaceDecl
*IFace
= getObjCInterfaceDecl(receiverNamePtr
,
560 // If the "receiver" is 'super' in a method, handle it as an expression-like
561 // property reference.
562 if (receiverNamePtr
->isStr("super")) {
563 if (ObjCMethodDecl
*CurMethod
= tryCaptureObjCSelf()) {
564 if (CurMethod
->isInstanceMethod()) {
566 Context
.getObjCInterfaceType(CurMethod
->getClassInterface());
567 T
= Context
.getObjCObjectPointerType(T
);
569 return HandleExprPropertyRefExpr(T
->getAsObjCInterfacePointerType(),
570 /*BaseExpr*/0, &propertyName
,
572 receiverNameLoc
, T
, true);
575 // Otherwise, if this is a class method, try dispatching to our
577 IFace
= CurMethod
->getClassInterface()->getSuperClass();
582 Diag(receiverNameLoc
, diag::err_expected_ident_or_lparen
);
587 // Search for a declared property first.
588 Selector Sel
= PP
.getSelectorTable().getNullarySelector(&propertyName
);
589 ObjCMethodDecl
*Getter
= IFace
->lookupClassMethod(Sel
);
591 // If this reference is in an @implementation, check for 'private' methods.
593 if (ObjCMethodDecl
*CurMeth
= getCurMethodDecl())
594 if (ObjCInterfaceDecl
*ClassDecl
= CurMeth
->getClassInterface())
595 if (ObjCImplementationDecl
*ImpDecl
= ClassDecl
->getImplementation())
596 Getter
= ImpDecl
->getClassMethod(Sel
);
599 // FIXME: refactor/share with ActOnMemberReference().
600 // Check if we can reference this property.
601 if (DiagnoseUseOfDecl(Getter
, propertyNameLoc
))
605 // Look for the matching setter, in case it is needed.
607 SelectorTable::constructSetterName(PP
.getIdentifierTable(),
608 PP
.getSelectorTable(), &propertyName
);
610 ObjCMethodDecl
*Setter
= IFace
->lookupClassMethod(SetterSel
);
612 // If this reference is in an @implementation, also check for 'private'
614 if (ObjCMethodDecl
*CurMeth
= getCurMethodDecl())
615 if (ObjCInterfaceDecl
*ClassDecl
= CurMeth
->getClassInterface())
616 if (ObjCImplementationDecl
*ImpDecl
= ClassDecl
->getImplementation())
617 Setter
= ImpDecl
->getClassMethod(SetterSel
);
619 // Look through local category implementations associated with the class.
621 Setter
= IFace
->getCategoryClassMethod(SetterSel
);
623 if (Setter
&& DiagnoseUseOfDecl(Setter
, propertyNameLoc
))
626 if (Getter
|| Setter
) {
629 ExprValueKind VK
= VK_LValue
;
631 PType
= Getter
->getSendResultType();
632 if (!getLangOptions().CPlusPlus
&&
633 !PType
.hasQualifiers() && PType
->isVoidType())
636 for (ObjCMethodDecl::param_iterator PI
= Setter
->param_begin(),
637 E
= Setter
->param_end(); PI
!= E
; ++PI
)
638 PType
= (*PI
)->getType();
642 ExprObjectKind OK
= (VK
== VK_RValue
? OK_Ordinary
: OK_ObjCProperty
);
644 return Owned(new (Context
) ObjCPropertyRefExpr(Getter
, Setter
,
647 receiverNameLoc
, IFace
));
649 return ExprError(Diag(propertyNameLoc
, diag::err_property_not_found
)
650 << &propertyName
<< Context
.getObjCInterfaceType(IFace
));
653 Sema::ObjCMessageKind
Sema::getObjCMessageKind(Scope
*S
,
654 IdentifierInfo
*Name
,
655 SourceLocation NameLoc
,
658 ParsedType
&ReceiverType
) {
659 ReceiverType
= ParsedType();
661 // If the identifier is "super" and there is no trailing dot, we're
662 // messaging super. If the identifier is "super" and there is a
663 // trailing dot, it's an instance message.
664 if (IsSuper
&& S
->isInObjcMethodScope())
665 return HasTrailingDot
? ObjCInstanceMessage
: ObjCSuperMessage
;
667 LookupResult
Result(*this, Name
, NameLoc
, LookupOrdinaryName
);
668 LookupName(Result
, S
);
670 switch (Result
.getResultKind()) {
671 case LookupResult::NotFound
:
672 // Normal name lookup didn't find anything. If we're in an
673 // Objective-C method, look for ivars. If we find one, we're done!
674 // FIXME: This is a hack. Ivar lookup should be part of normal
676 if (ObjCMethodDecl
*Method
= getCurMethodDecl()) {
677 ObjCInterfaceDecl
*ClassDeclared
;
678 if (Method
->getClassInterface()->lookupInstanceVariable(Name
,
680 return ObjCInstanceMessage
;
683 // Break out; we'll perform typo correction below.
686 case LookupResult::NotFoundInCurrentInstantiation
:
687 case LookupResult::FoundOverloaded
:
688 case LookupResult::FoundUnresolvedValue
:
689 case LookupResult::Ambiguous
:
690 Result
.suppressDiagnostics();
691 return ObjCInstanceMessage
;
693 case LookupResult::Found
: {
694 // If the identifier is a class or not, and there is a trailing dot,
695 // it's an instance message.
697 return ObjCInstanceMessage
;
698 // We found something. If it's a type, then we have a class
699 // message. Otherwise, it's an instance message.
700 NamedDecl
*ND
= Result
.getFoundDecl();
702 if (ObjCInterfaceDecl
*Class
= dyn_cast
<ObjCInterfaceDecl
>(ND
))
703 T
= Context
.getObjCInterfaceType(Class
);
704 else if (TypeDecl
*Type
= dyn_cast
<TypeDecl
>(ND
))
705 T
= Context
.getTypeDeclType(Type
);
707 return ObjCInstanceMessage
;
709 // We have a class message, and T is the type we're
710 // messaging. Build source-location information for it.
711 TypeSourceInfo
*TSInfo
= Context
.getTrivialTypeSourceInfo(T
, NameLoc
);
712 ReceiverType
= CreateParsedType(T
, TSInfo
);
713 return ObjCClassMessage
;
717 // Determine our typo-correction context.
718 CorrectTypoContext CTC
= CTC_Expression
;
719 if (ObjCMethodDecl
*Method
= getCurMethodDecl())
720 if (Method
->getClassInterface() &&
721 Method
->getClassInterface()->getSuperClass())
722 CTC
= CTC_ObjCMessageReceiver
;
724 if (DeclarationName Corrected
= CorrectTypo(Result
, S
, 0, 0, false, CTC
)) {
725 if (Result
.isSingleResult()) {
726 // If we found a declaration, correct when it refers to an Objective-C
728 NamedDecl
*ND
= Result
.getFoundDecl();
729 if (ObjCInterfaceDecl
*Class
= dyn_cast
<ObjCInterfaceDecl
>(ND
)) {
730 Diag(NameLoc
, diag::err_unknown_receiver_suggest
)
731 << Name
<< Result
.getLookupName()
732 << FixItHint::CreateReplacement(SourceRange(NameLoc
),
733 ND
->getNameAsString());
734 Diag(ND
->getLocation(), diag::note_previous_decl
)
737 QualType T
= Context
.getObjCInterfaceType(Class
);
738 TypeSourceInfo
*TSInfo
= Context
.getTrivialTypeSourceInfo(T
, NameLoc
);
739 ReceiverType
= CreateParsedType(T
, TSInfo
);
740 return ObjCClassMessage
;
742 } else if (Result
.empty() && Corrected
.getAsIdentifierInfo() &&
743 Corrected
.getAsIdentifierInfo()->isStr("super")) {
744 // If we've found the keyword "super", this is a send to super.
745 Diag(NameLoc
, diag::err_unknown_receiver_suggest
)
747 << FixItHint::CreateReplacement(SourceRange(NameLoc
), "super");
748 return ObjCSuperMessage
;
752 // Fall back: let the parser try to parse it as an instance message.
753 return ObjCInstanceMessage
;
756 ExprResult
Sema::ActOnSuperMessage(Scope
*S
,
757 SourceLocation SuperLoc
,
759 SourceLocation LBracLoc
,
760 SourceLocation SelectorLoc
,
761 SourceLocation RBracLoc
,
763 // Determine whether we are inside a method or not.
764 ObjCMethodDecl
*Method
= tryCaptureObjCSelf();
766 Diag(SuperLoc
, diag::err_invalid_receiver_to_message_super
);
770 ObjCInterfaceDecl
*Class
= Method
->getClassInterface();
772 Diag(SuperLoc
, diag::error_no_super_class_message
)
773 << Method
->getDeclName();
777 ObjCInterfaceDecl
*Super
= Class
->getSuperClass();
779 // The current class does not have a superclass.
780 Diag(SuperLoc
, diag::error_root_class_cannot_use_super
)
781 << Class
->getIdentifier();
785 // We are in a method whose class has a superclass, so 'super'
786 // is acting as a keyword.
787 if (Method
->isInstanceMethod()) {
788 // Since we are in an instance method, this is an instance
789 // message to the superclass instance.
790 QualType SuperTy
= Context
.getObjCInterfaceType(Super
);
791 SuperTy
= Context
.getObjCObjectPointerType(SuperTy
);
792 return BuildInstanceMessage(0, SuperTy
, SuperLoc
,
794 LBracLoc
, SelectorLoc
, RBracLoc
, move(Args
));
797 // Since we are in a class method, this is a class message to
799 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
800 Context
.getObjCInterfaceType(Super
),
801 SuperLoc
, Sel
, /*Method=*/0,
802 LBracLoc
, SelectorLoc
, RBracLoc
, move(Args
));
805 /// \brief Build an Objective-C class message expression.
807 /// This routine takes care of both normal class messages and
808 /// class messages to the superclass.
810 /// \param ReceiverTypeInfo Type source information that describes the
811 /// receiver of this message. This may be NULL, in which case we are
812 /// sending to the superclass and \p SuperLoc must be a valid source
815 /// \param ReceiverType The type of the object receiving the
816 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
817 /// type as that refers to. For a superclass send, this is the type of
820 /// \param SuperLoc The location of the "super" keyword in a
821 /// superclass message.
823 /// \param Sel The selector to which the message is being sent.
825 /// \param Method The method that this class message is invoking, if
828 /// \param LBracLoc The location of the opening square bracket ']'.
830 /// \param RBrac The location of the closing square bracket ']'.
832 /// \param Args The message arguments.
833 ExprResult
Sema::BuildClassMessage(TypeSourceInfo
*ReceiverTypeInfo
,
834 QualType ReceiverType
,
835 SourceLocation SuperLoc
,
837 ObjCMethodDecl
*Method
,
838 SourceLocation LBracLoc
,
839 SourceLocation SelectorLoc
,
840 SourceLocation RBracLoc
,
841 MultiExprArg ArgsIn
) {
842 SourceLocation Loc
= SuperLoc
.isValid()? SuperLoc
843 : ReceiverTypeInfo
->getTypeLoc().getSourceRange().getBegin();
844 if (LBracLoc
.isInvalid()) {
845 Diag(Loc
, diag::err_missing_open_square_message_send
)
846 << FixItHint::CreateInsertion(Loc
, "[");
850 if (ReceiverType
->isDependentType()) {
851 // If the receiver type is dependent, we can't type-check anything
852 // at this point. Build a dependent expression.
853 unsigned NumArgs
= ArgsIn
.size();
854 Expr
**Args
= reinterpret_cast<Expr
**>(ArgsIn
.release());
855 assert(SuperLoc
.isInvalid() && "Message to super with dependent type");
856 return Owned(ObjCMessageExpr::Create(Context
, ReceiverType
,
857 VK_RValue
, LBracLoc
, ReceiverTypeInfo
,
858 Sel
, SelectorLoc
, /*Method=*/0,
859 Args
, NumArgs
, RBracLoc
));
862 // Find the class to which we are sending this message.
863 ObjCInterfaceDecl
*Class
= 0;
864 const ObjCObjectType
*ClassType
= ReceiverType
->getAs
<ObjCObjectType
>();
865 if (!ClassType
|| !(Class
= ClassType
->getInterface())) {
866 Diag(Loc
, diag::err_invalid_receiver_class_message
)
870 assert(Class
&& "We don't know which class we're messaging?");
872 // Find the method we are messaging.
874 if (Class
->isForwardDecl()) {
875 // A forward class used in messaging is treated as a 'Class'
876 Diag(Loc
, diag::warn_receiver_forward_class
) << Class
->getDeclName();
877 Method
= LookupFactoryMethodInGlobalPool(Sel
,
878 SourceRange(LBracLoc
, RBracLoc
));
880 Diag(Method
->getLocation(), diag::note_method_sent_forward_class
)
881 << Method
->getDeclName();
884 Method
= Class
->lookupClassMethod(Sel
);
886 // If we have an implementation in scope, check "private" methods.
888 Method
= LookupPrivateClassMethod(Sel
, Class
);
890 if (Method
&& DiagnoseUseOfDecl(Method
, Loc
))
894 // Check the argument types and determine the result type.
896 ExprValueKind VK
= VK_RValue
;
898 unsigned NumArgs
= ArgsIn
.size();
899 Expr
**Args
= reinterpret_cast<Expr
**>(ArgsIn
.release());
900 if (CheckMessageArgumentTypes(Args
, NumArgs
, Sel
, Method
, true,
901 LBracLoc
, RBracLoc
, ReturnType
, VK
))
904 if (Method
&& !Method
->getResultType()->isVoidType() &&
905 RequireCompleteType(LBracLoc
, Method
->getResultType(),
906 diag::err_illegal_message_expr_incomplete_type
))
909 // Construct the appropriate ObjCMessageExpr.
911 if (SuperLoc
.isValid())
912 Result
= ObjCMessageExpr::Create(Context
, ReturnType
, VK
, LBracLoc
,
913 SuperLoc
, /*IsInstanceSuper=*/false,
914 ReceiverType
, Sel
, SelectorLoc
,
915 Method
, Args
, NumArgs
, RBracLoc
);
917 Result
= ObjCMessageExpr::Create(Context
, ReturnType
, VK
, LBracLoc
,
918 ReceiverTypeInfo
, Sel
, SelectorLoc
,
919 Method
, Args
, NumArgs
, RBracLoc
);
920 return MaybeBindToTemporary(Result
);
923 // ActOnClassMessage - used for both unary and keyword messages.
924 // ArgExprs is optional - if it is present, the number of expressions
925 // is obtained from Sel.getNumArgs().
926 ExprResult
Sema::ActOnClassMessage(Scope
*S
,
929 SourceLocation LBracLoc
,
930 SourceLocation SelectorLoc
,
931 SourceLocation RBracLoc
,
933 TypeSourceInfo
*ReceiverTypeInfo
;
934 QualType ReceiverType
= GetTypeFromParser(Receiver
, &ReceiverTypeInfo
);
935 if (ReceiverType
.isNull())
939 if (!ReceiverTypeInfo
)
940 ReceiverTypeInfo
= Context
.getTrivialTypeSourceInfo(ReceiverType
, LBracLoc
);
942 return BuildClassMessage(ReceiverTypeInfo
, ReceiverType
,
943 /*SuperLoc=*/SourceLocation(), Sel
, /*Method=*/0,
944 LBracLoc
, SelectorLoc
, RBracLoc
, move(Args
));
947 /// \brief Build an Objective-C instance message expression.
949 /// This routine takes care of both normal instance messages and
950 /// instance messages to the superclass instance.
952 /// \param Receiver The expression that computes the object that will
953 /// receive this message. This may be empty, in which case we are
954 /// sending to the superclass instance and \p SuperLoc must be a valid
957 /// \param ReceiverType The (static) type of the object receiving the
958 /// message. When a \p Receiver expression is provided, this is the
959 /// same type as that expression. For a superclass instance send, this
960 /// is a pointer to the type of the superclass.
962 /// \param SuperLoc The location of the "super" keyword in a
963 /// superclass instance message.
965 /// \param Sel The selector to which the message is being sent.
967 /// \param Method The method that this instance message is invoking, if
970 /// \param LBracLoc The location of the opening square bracket ']'.
972 /// \param RBrac The location of the closing square bracket ']'.
974 /// \param Args The message arguments.
975 ExprResult
Sema::BuildInstanceMessage(Expr
*Receiver
,
976 QualType ReceiverType
,
977 SourceLocation SuperLoc
,
979 ObjCMethodDecl
*Method
,
980 SourceLocation LBracLoc
,
981 SourceLocation SelectorLoc
,
982 SourceLocation RBracLoc
,
983 MultiExprArg ArgsIn
) {
984 // The location of the receiver.
985 SourceLocation Loc
= SuperLoc
.isValid()? SuperLoc
: Receiver
->getLocStart();
987 if (LBracLoc
.isInvalid()) {
988 Diag(Loc
, diag::err_missing_open_square_message_send
)
989 << FixItHint::CreateInsertion(Loc
, "[");
993 // If we have a receiver expression, perform appropriate promotions
994 // and determine receiver type.
996 if (Receiver
->isTypeDependent()) {
997 // If the receiver is type-dependent, we can't type-check anything
998 // at this point. Build a dependent expression.
999 unsigned NumArgs
= ArgsIn
.size();
1000 Expr
**Args
= reinterpret_cast<Expr
**>(ArgsIn
.release());
1001 assert(SuperLoc
.isInvalid() && "Message to super with dependent type");
1002 return Owned(ObjCMessageExpr::Create(Context
, Context
.DependentTy
,
1003 VK_RValue
, LBracLoc
, Receiver
, Sel
,
1004 SelectorLoc
, /*Method=*/0,
1005 Args
, NumArgs
, RBracLoc
));
1008 // If necessary, apply function/array conversion to the receiver.
1009 // C99 6.7.5.3p[7,8].
1010 DefaultFunctionArrayLvalueConversion(Receiver
);
1011 ReceiverType
= Receiver
->getType();
1015 // Handle messages to id.
1016 bool receiverIsId
= ReceiverType
->isObjCIdType();
1017 if (receiverIsId
|| ReceiverType
->isBlockPointerType() ||
1018 (Receiver
&& Context
.isObjCNSObjectType(Receiver
->getType()))) {
1019 Method
= LookupInstanceMethodInGlobalPool(Sel
,
1020 SourceRange(LBracLoc
, RBracLoc
),
1023 Method
= LookupFactoryMethodInGlobalPool(Sel
,
1024 SourceRange(LBracLoc
, RBracLoc
),
1026 } else if (ReceiverType
->isObjCClassType() ||
1027 ReceiverType
->isObjCQualifiedClassType()) {
1028 // Handle messages to Class.
1029 if (ObjCMethodDecl
*CurMeth
= getCurMethodDecl()) {
1030 if (ObjCInterfaceDecl
*ClassDecl
= CurMeth
->getClassInterface()) {
1031 // First check the public methods in the class interface.
1032 Method
= ClassDecl
->lookupClassMethod(Sel
);
1035 Method
= LookupPrivateClassMethod(Sel
, ClassDecl
);
1037 // FIXME: if we still haven't found a method, we need to look in
1038 // protocols (if we have qualifiers).
1040 if (Method
&& DiagnoseUseOfDecl(Method
, Loc
))
1044 // If not messaging 'self', look for any factory method named 'Sel'.
1045 if (!Receiver
|| !isSelfExpr(Receiver
)) {
1046 Method
= LookupFactoryMethodInGlobalPool(Sel
,
1047 SourceRange(LBracLoc
, RBracLoc
),
1050 // If no class (factory) method was found, check if an _instance_
1051 // method of the same name exists in the root class only.
1052 Method
= LookupInstanceMethodInGlobalPool(Sel
,
1053 SourceRange(LBracLoc
, RBracLoc
),
1056 if (const ObjCInterfaceDecl
*ID
=
1057 dyn_cast
<ObjCInterfaceDecl
>(Method
->getDeclContext())) {
1058 if (ID
->getSuperClass())
1059 Diag(Loc
, diag::warn_root_inst_method_not_found
)
1060 << Sel
<< SourceRange(LBracLoc
, RBracLoc
);
1066 ObjCInterfaceDecl
* ClassDecl
= 0;
1068 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
1069 // long as one of the protocols implements the selector (if not, warn).
1070 if (const ObjCObjectPointerType
*QIdTy
1071 = ReceiverType
->getAsObjCQualifiedIdType()) {
1072 // Search protocols for instance methods.
1073 for (ObjCObjectPointerType::qual_iterator I
= QIdTy
->qual_begin(),
1074 E
= QIdTy
->qual_end(); I
!= E
; ++I
) {
1075 ObjCProtocolDecl
*PDecl
= *I
;
1076 if (PDecl
&& (Method
= PDecl
->lookupInstanceMethod(Sel
)))
1078 // Since we aren't supporting "Class<foo>", look for a class method.
1079 if (PDecl
&& (Method
= PDecl
->lookupClassMethod(Sel
)))
1082 } else if (const ObjCObjectPointerType
*OCIType
1083 = ReceiverType
->getAsObjCInterfacePointerType()) {
1084 // We allow sending a message to a pointer to an interface (an object).
1085 ClassDecl
= OCIType
->getInterfaceDecl();
1086 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1087 // faster than the following method (which can do *many* linear searches).
1088 // The idea is to add class info to MethodPool.
1089 Method
= ClassDecl
->lookupInstanceMethod(Sel
);
1092 // Search protocol qualifiers.
1093 for (ObjCObjectPointerType::qual_iterator QI
= OCIType
->qual_begin(),
1094 E
= OCIType
->qual_end(); QI
!= E
; ++QI
) {
1095 if ((Method
= (*QI
)->lookupInstanceMethod(Sel
)))
1099 bool forwardClass
= false;
1101 // If we have implementations in scope, check "private" methods.
1102 Method
= LookupPrivateInstanceMethod(Sel
, ClassDecl
);
1104 if (!Method
&& (!Receiver
|| !isSelfExpr(Receiver
))) {
1105 // If we still haven't found a method, look in the global pool. This
1106 // behavior isn't very desirable, however we need it for GCC
1107 // compatibility. FIXME: should we deviate??
1108 if (OCIType
->qual_empty()) {
1109 Method
= LookupInstanceMethodInGlobalPool(Sel
,
1110 SourceRange(LBracLoc
, RBracLoc
));
1111 forwardClass
= OCIType
->getInterfaceDecl()->isForwardDecl();
1112 if (Method
&& !forwardClass
)
1113 Diag(Loc
, diag::warn_maynot_respond
)
1114 << OCIType
->getInterfaceDecl()->getIdentifier() << Sel
;
1118 if (Method
&& DiagnoseUseOfDecl(Method
, Loc
, forwardClass
))
1120 } else if (!Context
.getObjCIdType().isNull() &&
1121 (ReceiverType
->isPointerType() ||
1122 ReceiverType
->isIntegerType())) {
1123 // Implicitly convert integers and pointers to 'id' but emit a warning.
1124 Diag(Loc
, diag::warn_bad_receiver_type
)
1126 << Receiver
->getSourceRange();
1127 if (ReceiverType
->isPointerType())
1128 ImpCastExprToType(Receiver
, Context
.getObjCIdType(),
1131 // TODO: specialized warning on null receivers?
1132 bool IsNull
= Receiver
->isNullPointerConstant(Context
,
1133 Expr::NPC_ValueDependentIsNull
);
1134 ImpCastExprToType(Receiver
, Context
.getObjCIdType(),
1135 IsNull
? CK_NullToPointer
: CK_IntegralToPointer
);
1137 ReceiverType
= Receiver
->getType();
1139 else if (getLangOptions().CPlusPlus
&&
1140 !PerformContextuallyConvertToObjCId(Receiver
)) {
1141 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(Receiver
)) {
1142 Receiver
= ICE
->getSubExpr();
1143 ReceiverType
= Receiver
->getType();
1145 return BuildInstanceMessage(Receiver
,
1155 // Reject other random receiver types (e.g. structs).
1156 Diag(Loc
, diag::err_bad_receiver_type
)
1157 << ReceiverType
<< Receiver
->getSourceRange();
1163 // Check the message arguments.
1164 unsigned NumArgs
= ArgsIn
.size();
1165 Expr
**Args
= reinterpret_cast<Expr
**>(ArgsIn
.release());
1166 QualType ReturnType
;
1167 ExprValueKind VK
= VK_RValue
;
1168 bool ClassMessage
= (ReceiverType
->isObjCClassType() ||
1169 ReceiverType
->isObjCQualifiedClassType());
1170 if (CheckMessageArgumentTypes(Args
, NumArgs
, Sel
, Method
, ClassMessage
,
1171 LBracLoc
, RBracLoc
, ReturnType
, VK
))
1174 if (Method
&& !Method
->getResultType()->isVoidType() &&
1175 RequireCompleteType(LBracLoc
, Method
->getResultType(),
1176 diag::err_illegal_message_expr_incomplete_type
))
1179 // Construct the appropriate ObjCMessageExpr instance.
1181 if (SuperLoc
.isValid())
1182 Result
= ObjCMessageExpr::Create(Context
, ReturnType
, VK
, LBracLoc
,
1183 SuperLoc
, /*IsInstanceSuper=*/true,
1184 ReceiverType
, Sel
, SelectorLoc
, Method
,
1185 Args
, NumArgs
, RBracLoc
);
1187 Result
= ObjCMessageExpr::Create(Context
, ReturnType
, VK
, LBracLoc
,
1188 Receiver
, Sel
, SelectorLoc
, Method
,
1189 Args
, NumArgs
, RBracLoc
);
1190 return MaybeBindToTemporary(Result
);
1193 // ActOnInstanceMessage - used for both unary and keyword messages.
1194 // ArgExprs is optional - if it is present, the number of expressions
1195 // is obtained from Sel.getNumArgs().
1196 ExprResult
Sema::ActOnInstanceMessage(Scope
*S
,
1199 SourceLocation LBracLoc
,
1200 SourceLocation SelectorLoc
,
1201 SourceLocation RBracLoc
,
1202 MultiExprArg Args
) {
1206 return BuildInstanceMessage(Receiver
, Receiver
->getType(),
1207 /*SuperLoc=*/SourceLocation(), Sel
, /*Method=*/0,
1208 LBracLoc
, SelectorLoc
, RBracLoc
, move(Args
));