Keep the source location of the selector in ObjCMessageExpr.
[clang.git] / lib / Sema / SemaExprObjC.cpp
blob5d5e8a528bb690aa105d465bf5c503ba7e7565c2
1 //===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for Objective-C expressions.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Lookup.h"
16 #include "clang/Sema/Scope.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "clang/Lex/Preprocessor.h"
25 using namespace clang;
27 ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs,
28 Expr **strings,
29 unsigned NumStrings) {
30 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings);
32 // Most ObjC strings are formed out of a single piece. However, we *can*
33 // have strings formed out of multiple @ strings with multiple pptokens in
34 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one
35 // StringLiteral for ObjCStringLiteral to hold onto.
36 StringLiteral *S = Strings[0];
38 // If we have a multi-part string, merge it all together.
39 if (NumStrings != 1) {
40 // Concatenate objc strings.
41 llvm::SmallString<128> StrBuf;
42 llvm::SmallVector<SourceLocation, 8> StrLocs;
44 for (unsigned i = 0; i != NumStrings; ++i) {
45 S = Strings[i];
47 // ObjC strings can't be wide.
48 if (S->isWide()) {
49 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant)
50 << S->getSourceRange();
51 return true;
54 // Append the string.
55 StrBuf += S->getString();
57 // Get the locations of the string tokens.
58 StrLocs.append(S->tokloc_begin(), S->tokloc_end());
61 // Create the aggregate string with the appropriate content and location
62 // information.
63 S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(), false,
64 Context.getPointerType(Context.CharTy),
65 &StrLocs[0], StrLocs.size());
68 // Verify that this composite string is acceptable for ObjC strings.
69 if (CheckObjCString(S))
70 return true;
72 // Initialize the constant string interface lazily. This assumes
73 // the NSString interface is seen in this translation unit. Note: We
74 // don't use NSConstantString, since the runtime team considers this
75 // interface private (even though it appears in the header files).
76 QualType Ty = Context.getObjCConstantStringInterface();
77 if (!Ty.isNull()) {
78 Ty = Context.getObjCObjectPointerType(Ty);
79 } else if (getLangOptions().NoConstantCFStrings) {
80 IdentifierInfo *NSIdent=0;
81 std::string StringClass(getLangOptions().ObjCConstantStringClass);
83 if (StringClass.empty())
84 NSIdent = &Context.Idents.get("NSConstantString");
85 else
86 NSIdent = &Context.Idents.get(StringClass);
88 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
89 LookupOrdinaryName);
90 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
91 Context.setObjCConstantStringInterface(StrIF);
92 Ty = Context.getObjCConstantStringInterface();
93 Ty = Context.getObjCObjectPointerType(Ty);
94 } else {
95 // If there is no NSConstantString interface defined then treat this
96 // as error and recover from it.
97 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent
98 << S->getSourceRange();
99 Ty = Context.getObjCIdType();
101 } else {
102 IdentifierInfo *NSIdent = &Context.Idents.get("NSString");
103 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0],
104 LookupOrdinaryName);
105 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) {
106 Context.setObjCConstantStringInterface(StrIF);
107 Ty = Context.getObjCConstantStringInterface();
108 Ty = Context.getObjCObjectPointerType(Ty);
109 } else {
110 // If there is no NSString interface defined then treat constant
111 // strings as untyped objects and let the runtime figure it out later.
112 Ty = Context.getObjCIdType();
116 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]);
119 Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc,
120 TypeSourceInfo *EncodedTypeInfo,
121 SourceLocation RParenLoc) {
122 QualType EncodedType = EncodedTypeInfo->getType();
123 QualType StrTy;
124 if (EncodedType->isDependentType())
125 StrTy = Context.DependentTy;
126 else {
127 std::string Str;
128 Context.getObjCEncodingForType(EncodedType, Str);
130 // The type of @encode is the same as the type of the corresponding string,
131 // which is an array type.
132 StrTy = Context.CharTy;
133 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
134 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
135 StrTy.addConst();
136 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1),
137 ArrayType::Normal, 0);
140 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc);
143 ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc,
144 SourceLocation EncodeLoc,
145 SourceLocation LParenLoc,
146 ParsedType ty,
147 SourceLocation RParenLoc) {
148 // FIXME: Preserve type source info ?
149 TypeSourceInfo *TInfo;
150 QualType EncodedType = GetTypeFromParser(ty, &TInfo);
151 if (!TInfo)
152 TInfo = Context.getTrivialTypeSourceInfo(EncodedType,
153 PP.getLocForEndOfToken(LParenLoc));
155 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc);
158 ExprResult Sema::ParseObjCSelectorExpression(Selector Sel,
159 SourceLocation AtLoc,
160 SourceLocation SelLoc,
161 SourceLocation LParenLoc,
162 SourceLocation RParenLoc) {
163 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel,
164 SourceRange(LParenLoc, RParenLoc), false, false);
165 if (!Method)
166 Method = LookupFactoryMethodInGlobalPool(Sel,
167 SourceRange(LParenLoc, RParenLoc));
168 if (!Method)
169 Diag(SelLoc, diag::warn_undeclared_selector) << Sel;
171 llvm::DenseMap<Selector, SourceLocation>::iterator Pos
172 = ReferencedSelectors.find(Sel);
173 if (Pos == ReferencedSelectors.end())
174 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc));
176 QualType Ty = Context.getObjCSelType();
177 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc);
180 ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId,
181 SourceLocation AtLoc,
182 SourceLocation ProtoLoc,
183 SourceLocation LParenLoc,
184 SourceLocation RParenLoc) {
185 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc);
186 if (!PDecl) {
187 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId;
188 return true;
191 QualType Ty = Context.getObjCProtoType();
192 if (Ty.isNull())
193 return true;
194 Ty = Context.getObjCObjectPointerType(Ty);
195 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc);
198 bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs,
199 Selector Sel, ObjCMethodDecl *Method,
200 bool isClassMessage,
201 SourceLocation lbrac, SourceLocation rbrac,
202 QualType &ReturnType, ExprValueKind &VK) {
203 if (!Method) {
204 // Apply default argument promotion as for (C99 6.5.2.2p6).
205 for (unsigned i = 0; i != NumArgs; i++) {
206 if (Args[i]->isTypeDependent())
207 continue;
209 DefaultArgumentPromotion(Args[i]);
212 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found :
213 diag::warn_inst_method_not_found;
214 Diag(lbrac, DiagID)
215 << Sel << isClassMessage << SourceRange(lbrac, rbrac);
216 ReturnType = Context.getObjCIdType();
217 VK = VK_RValue;
218 return false;
221 ReturnType = Method->getSendResultType();
222 VK = Expr::getValueKindForType(Method->getResultType());
224 unsigned NumNamedArgs = Sel.getNumArgs();
225 // Method might have more arguments than selector indicates. This is due
226 // to addition of c-style arguments in method.
227 if (Method->param_size() > Sel.getNumArgs())
228 NumNamedArgs = Method->param_size();
229 // FIXME. This need be cleaned up.
230 if (NumArgs < NumNamedArgs) {
231 Diag(lbrac, diag::err_typecheck_call_too_few_args)
232 << 2 << NumNamedArgs << NumArgs;
233 return false;
236 bool IsError = false;
237 for (unsigned i = 0; i < NumNamedArgs; i++) {
238 // We can't do any type-checking on a type-dependent argument.
239 if (Args[i]->isTypeDependent())
240 continue;
242 Expr *argExpr = Args[i];
244 ParmVarDecl *Param = Method->param_begin()[i];
245 assert(argExpr && "CheckMessageArgumentTypes(): missing expression");
247 if (RequireCompleteType(argExpr->getSourceRange().getBegin(),
248 Param->getType(),
249 PDiag(diag::err_call_incomplete_argument)
250 << argExpr->getSourceRange()))
251 return true;
253 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
254 Param);
255 ExprResult ArgE = PerformCopyInitialization(Entity, lbrac, Owned(argExpr));
256 if (ArgE.isInvalid())
257 IsError = true;
258 else
259 Args[i] = ArgE.takeAs<Expr>();
262 // Promote additional arguments to variadic methods.
263 if (Method->isVariadic()) {
264 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) {
265 if (Args[i]->isTypeDependent())
266 continue;
268 IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
270 } else {
271 // Check for extra arguments to non-variadic methods.
272 if (NumArgs != NumNamedArgs) {
273 Diag(Args[NumNamedArgs]->getLocStart(),
274 diag::err_typecheck_call_too_many_args)
275 << 2 /*method*/ << NumNamedArgs << NumArgs
276 << Method->getSourceRange()
277 << SourceRange(Args[NumNamedArgs]->getLocStart(),
278 Args[NumArgs-1]->getLocEnd());
282 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs);
283 return IsError;
286 bool Sema::isSelfExpr(Expr *RExpr) {
287 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RExpr))
288 if (ICE->getCastKind() == CK_LValueToRValue)
289 RExpr = ICE->getSubExpr();
290 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr))
291 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self"))
292 return true;
293 return false;
296 // Helper method for ActOnClassMethod/ActOnInstanceMethod.
297 // Will search "local" class/category implementations for a method decl.
298 // If failed, then we search in class's root for an instance method.
299 // Returns 0 if no method is found.
300 ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel,
301 ObjCInterfaceDecl *ClassDecl) {
302 ObjCMethodDecl *Method = 0;
303 // lookup in class and all superclasses
304 while (ClassDecl && !Method) {
305 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
306 Method = ImpDecl->getClassMethod(Sel);
308 // Look through local category implementations associated with the class.
309 if (!Method)
310 Method = ClassDecl->getCategoryClassMethod(Sel);
312 // Before we give up, check if the selector is an instance method.
313 // But only in the root. This matches gcc's behaviour and what the
314 // runtime expects.
315 if (!Method && !ClassDecl->getSuperClass()) {
316 Method = ClassDecl->lookupInstanceMethod(Sel);
317 // Look through local category implementations associated
318 // with the root class.
319 if (!Method)
320 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
323 ClassDecl = ClassDecl->getSuperClass();
325 return Method;
328 ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel,
329 ObjCInterfaceDecl *ClassDecl) {
330 ObjCMethodDecl *Method = 0;
331 while (ClassDecl && !Method) {
332 // If we have implementations in scope, check "private" methods.
333 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
334 Method = ImpDecl->getInstanceMethod(Sel);
336 // Look through local category implementations associated with the class.
337 if (!Method)
338 Method = ClassDecl->getCategoryInstanceMethod(Sel);
339 ClassDecl = ClassDecl->getSuperClass();
341 return Method;
344 /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an
345 /// objective C interface. This is a property reference expression.
346 ExprResult Sema::
347 HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT,
348 Expr *BaseExpr, DeclarationName MemberName,
349 SourceLocation MemberLoc,
350 SourceLocation SuperLoc, QualType SuperType,
351 bool Super) {
352 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
353 ObjCInterfaceDecl *IFace = IFaceT->getDecl();
354 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
356 // Search for a declared property first.
357 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
358 // Check whether we can reference this property.
359 if (DiagnoseUseOfDecl(PD, MemberLoc))
360 return ExprError();
361 QualType ResTy = PD->getType();
362 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
363 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
364 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
365 ResTy = Getter->getResultType();
367 if (Super)
368 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
369 VK_LValue, OK_ObjCProperty,
370 MemberLoc,
371 SuperLoc, SuperType));
372 else
373 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
374 VK_LValue, OK_ObjCProperty,
375 MemberLoc, BaseExpr));
377 // Check protocols on qualified interfaces.
378 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
379 E = OPT->qual_end(); I != E; ++I)
380 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
381 // Check whether we can reference this property.
382 if (DiagnoseUseOfDecl(PD, MemberLoc))
383 return ExprError();
384 if (Super)
385 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
386 VK_LValue,
387 OK_ObjCProperty,
388 MemberLoc,
389 SuperLoc, SuperType));
390 else
391 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
392 VK_LValue,
393 OK_ObjCProperty,
394 MemberLoc,
395 BaseExpr));
397 // If that failed, look for an "implicit" property by seeing if the nullary
398 // selector is implemented.
400 // FIXME: The logic for looking up nullary and unary selectors should be
401 // shared with the code in ActOnInstanceMessage.
403 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
404 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
406 // If this reference is in an @implementation, check for 'private' methods.
407 if (!Getter)
408 Getter = IFace->lookupPrivateMethod(Sel);
410 // Look through local category implementations associated with the class.
411 if (!Getter)
412 Getter = IFace->getCategoryInstanceMethod(Sel);
413 if (Getter) {
414 // Check if we can reference this property.
415 if (DiagnoseUseOfDecl(Getter, MemberLoc))
416 return ExprError();
418 // If we found a getter then this may be a valid dot-reference, we
419 // will look for the matching setter, in case it is needed.
420 Selector SetterSel =
421 SelectorTable::constructSetterName(PP.getIdentifierTable(),
422 PP.getSelectorTable(), Member);
423 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
424 if (!Setter) {
425 // If this reference is in an @implementation, also check for 'private'
426 // methods.
427 Setter = IFace->lookupPrivateMethod(SetterSel);
429 // Look through local category implementations associated with the class.
430 if (!Setter)
431 Setter = IFace->getCategoryInstanceMethod(SetterSel);
433 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
434 return ExprError();
436 if (Getter) {
437 QualType PType = Getter->getSendResultType();
438 ExprValueKind VK = VK_LValue;
439 ExprObjectKind OK = OK_ObjCProperty;
440 if (!getLangOptions().CPlusPlus && !PType.hasQualifiers() &&
441 PType->isVoidType())
442 VK = VK_RValue, OK = OK_Ordinary;
444 if (Super)
445 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
446 PType, VK, OK,
447 MemberLoc,
448 SuperLoc, SuperType));
449 else
450 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
451 PType, VK, OK,
452 MemberLoc, BaseExpr));
456 // Attempt to correct for typos in property names.
457 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName);
458 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) &&
459 Res.getAsSingle<ObjCPropertyDecl>()) {
460 DeclarationName TypoResult = Res.getLookupName();
461 Diag(MemberLoc, diag::err_property_not_found_suggest)
462 << MemberName << QualType(OPT, 0) << TypoResult
463 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString());
464 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>();
465 Diag(Property->getLocation(), diag::note_previous_decl)
466 << Property->getDeclName();
467 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc,
468 SuperLoc, SuperType, Super);
471 Diag(MemberLoc, diag::err_property_not_found)
472 << MemberName << QualType(OPT, 0);
473 if (Setter && !Getter)
474 Diag(Setter->getLocation(), diag::note_getter_unavailable)
475 << MemberName << BaseExpr->getSourceRange();
476 return ExprError();
481 ExprResult Sema::
482 ActOnClassPropertyRefExpr(IdentifierInfo &receiverName,
483 IdentifierInfo &propertyName,
484 SourceLocation receiverNameLoc,
485 SourceLocation propertyNameLoc) {
487 IdentifierInfo *receiverNamePtr = &receiverName;
488 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr,
489 receiverNameLoc);
490 if (IFace == 0) {
491 // If the "receiver" is 'super' in a method, handle it as an expression-like
492 // property reference.
493 if (ObjCMethodDecl *CurMethod = getCurMethodDecl())
494 if (receiverNamePtr->isStr("super")) {
495 if (CurMethod->isInstanceMethod()) {
496 QualType T =
497 Context.getObjCInterfaceType(CurMethod->getClassInterface());
498 T = Context.getObjCObjectPointerType(T);
500 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(),
501 /*BaseExpr*/0, &propertyName,
502 propertyNameLoc,
503 receiverNameLoc, T, true);
506 // Otherwise, if this is a class method, try dispatching to our
507 // superclass.
508 IFace = CurMethod->getClassInterface()->getSuperClass();
511 if (IFace == 0) {
512 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen);
513 return ExprError();
517 // Search for a declared property first.
518 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName);
519 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel);
521 // If this reference is in an @implementation, check for 'private' methods.
522 if (!Getter)
523 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
524 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
525 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
526 Getter = ImpDecl->getClassMethod(Sel);
528 if (Getter) {
529 // FIXME: refactor/share with ActOnMemberReference().
530 // Check if we can reference this property.
531 if (DiagnoseUseOfDecl(Getter, propertyNameLoc))
532 return ExprError();
535 // Look for the matching setter, in case it is needed.
536 Selector SetterSel =
537 SelectorTable::constructSetterName(PP.getIdentifierTable(),
538 PP.getSelectorTable(), &propertyName);
540 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
541 if (!Setter) {
542 // If this reference is in an @implementation, also check for 'private'
543 // methods.
544 if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
545 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
546 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation())
547 Setter = ImpDecl->getClassMethod(SetterSel);
549 // Look through local category implementations associated with the class.
550 if (!Setter)
551 Setter = IFace->getCategoryClassMethod(SetterSel);
553 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc))
554 return ExprError();
556 if (Getter || Setter) {
557 QualType PType;
559 ExprValueKind VK = VK_LValue;
560 if (Getter) {
561 PType = Getter->getSendResultType();
562 if (!getLangOptions().CPlusPlus &&
563 !PType.hasQualifiers() && PType->isVoidType())
564 VK = VK_RValue;
565 } else {
566 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(),
567 E = Setter->param_end(); PI != E; ++PI)
568 PType = (*PI)->getType();
569 VK = VK_LValue;
572 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
574 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
575 PType, VK, OK,
576 propertyNameLoc,
577 receiverNameLoc, IFace));
579 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found)
580 << &propertyName << Context.getObjCInterfaceType(IFace));
583 Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S,
584 IdentifierInfo *Name,
585 SourceLocation NameLoc,
586 bool IsSuper,
587 bool HasTrailingDot,
588 ParsedType &ReceiverType) {
589 ReceiverType = ParsedType();
591 // If the identifier is "super" and there is no trailing dot, we're
592 // messaging super. If the identifier is "super" and there is a
593 // trailing dot, it's an instance message.
594 if (IsSuper && S->isInObjcMethodScope())
595 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage;
597 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
598 LookupName(Result, S);
600 switch (Result.getResultKind()) {
601 case LookupResult::NotFound:
602 // Normal name lookup didn't find anything. If we're in an
603 // Objective-C method, look for ivars. If we find one, we're done!
604 // FIXME: This is a hack. Ivar lookup should be part of normal
605 // lookup.
606 if (ObjCMethodDecl *Method = getCurMethodDecl()) {
607 ObjCInterfaceDecl *ClassDeclared;
608 if (Method->getClassInterface()->lookupInstanceVariable(Name,
609 ClassDeclared))
610 return ObjCInstanceMessage;
613 // Break out; we'll perform typo correction below.
614 break;
616 case LookupResult::NotFoundInCurrentInstantiation:
617 case LookupResult::FoundOverloaded:
618 case LookupResult::FoundUnresolvedValue:
619 case LookupResult::Ambiguous:
620 Result.suppressDiagnostics();
621 return ObjCInstanceMessage;
623 case LookupResult::Found: {
624 // We found something. If it's a type, then we have a class
625 // message. Otherwise, it's an instance message.
626 NamedDecl *ND = Result.getFoundDecl();
627 QualType T;
628 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND))
629 T = Context.getObjCInterfaceType(Class);
630 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND))
631 T = Context.getTypeDeclType(Type);
632 else
633 return ObjCInstanceMessage;
635 // We have a class message, and T is the type we're
636 // messaging. Build source-location information for it.
637 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
638 ReceiverType = CreateParsedType(T, TSInfo);
639 return ObjCClassMessage;
643 // Determine our typo-correction context.
644 CorrectTypoContext CTC = CTC_Expression;
645 if (ObjCMethodDecl *Method = getCurMethodDecl())
646 if (Method->getClassInterface() &&
647 Method->getClassInterface()->getSuperClass())
648 CTC = CTC_ObjCMessageReceiver;
650 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) {
651 if (Result.isSingleResult()) {
652 // If we found a declaration, correct when it refers to an Objective-C
653 // class.
654 NamedDecl *ND = Result.getFoundDecl();
655 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) {
656 Diag(NameLoc, diag::err_unknown_receiver_suggest)
657 << Name << Result.getLookupName()
658 << FixItHint::CreateReplacement(SourceRange(NameLoc),
659 ND->getNameAsString());
660 Diag(ND->getLocation(), diag::note_previous_decl)
661 << Corrected;
663 QualType T = Context.getObjCInterfaceType(Class);
664 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc);
665 ReceiverType = CreateParsedType(T, TSInfo);
666 return ObjCClassMessage;
668 } else if (Result.empty() && Corrected.getAsIdentifierInfo() &&
669 Corrected.getAsIdentifierInfo()->isStr("super")) {
670 // If we've found the keyword "super", this is a send to super.
671 Diag(NameLoc, diag::err_unknown_receiver_suggest)
672 << Name << Corrected
673 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super");
674 Name = Corrected.getAsIdentifierInfo();
675 return ObjCSuperMessage;
679 // Fall back: let the parser try to parse it as an instance message.
680 return ObjCInstanceMessage;
683 ExprResult Sema::ActOnSuperMessage(Scope *S,
684 SourceLocation SuperLoc,
685 Selector Sel,
686 SourceLocation LBracLoc,
687 SourceLocation SelectorLoc,
688 SourceLocation RBracLoc,
689 MultiExprArg Args) {
690 // Determine whether we are inside a method or not.
691 ObjCMethodDecl *Method = getCurMethodDecl();
692 if (!Method) {
693 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super);
694 return ExprError();
697 ObjCInterfaceDecl *Class = Method->getClassInterface();
698 if (!Class) {
699 Diag(SuperLoc, diag::error_no_super_class_message)
700 << Method->getDeclName();
701 return ExprError();
704 ObjCInterfaceDecl *Super = Class->getSuperClass();
705 if (!Super) {
706 // The current class does not have a superclass.
707 Diag(SuperLoc, diag::error_no_super_class) << Class->getIdentifier();
708 return ExprError();
711 // We are in a method whose class has a superclass, so 'super'
712 // is acting as a keyword.
713 if (Method->isInstanceMethod()) {
714 // Since we are in an instance method, this is an instance
715 // message to the superclass instance.
716 QualType SuperTy = Context.getObjCInterfaceType(Super);
717 SuperTy = Context.getObjCObjectPointerType(SuperTy);
718 return BuildInstanceMessage(0, SuperTy, SuperLoc,
719 Sel, /*Method=*/0,
720 LBracLoc, SelectorLoc, RBracLoc, move(Args));
723 // Since we are in a class method, this is a class message to
724 // the superclass.
725 return BuildClassMessage(/*ReceiverTypeInfo=*/0,
726 Context.getObjCInterfaceType(Super),
727 SuperLoc, Sel, /*Method=*/0,
728 LBracLoc, SelectorLoc, RBracLoc, move(Args));
731 /// \brief Build an Objective-C class message expression.
733 /// This routine takes care of both normal class messages and
734 /// class messages to the superclass.
736 /// \param ReceiverTypeInfo Type source information that describes the
737 /// receiver of this message. This may be NULL, in which case we are
738 /// sending to the superclass and \p SuperLoc must be a valid source
739 /// location.
741 /// \param ReceiverType The type of the object receiving the
742 /// message. When \p ReceiverTypeInfo is non-NULL, this is the same
743 /// type as that refers to. For a superclass send, this is the type of
744 /// the superclass.
746 /// \param SuperLoc The location of the "super" keyword in a
747 /// superclass message.
749 /// \param Sel The selector to which the message is being sent.
751 /// \param Method The method that this class message is invoking, if
752 /// already known.
754 /// \param LBracLoc The location of the opening square bracket ']'.
756 /// \param RBrac The location of the closing square bracket ']'.
758 /// \param Args The message arguments.
759 ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo,
760 QualType ReceiverType,
761 SourceLocation SuperLoc,
762 Selector Sel,
763 ObjCMethodDecl *Method,
764 SourceLocation LBracLoc,
765 SourceLocation SelectorLoc,
766 SourceLocation RBracLoc,
767 MultiExprArg ArgsIn) {
768 SourceLocation Loc = SuperLoc.isValid()? SuperLoc
769 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin();
770 if (LBracLoc.isInvalid()) {
771 Diag(Loc, diag::err_missing_open_square_message_send)
772 << FixItHint::CreateInsertion(Loc, "[");
773 LBracLoc = Loc;
776 if (ReceiverType->isDependentType()) {
777 // If the receiver type is dependent, we can't type-check anything
778 // at this point. Build a dependent expression.
779 unsigned NumArgs = ArgsIn.size();
780 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
781 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
782 return Owned(ObjCMessageExpr::Create(Context, ReceiverType,
783 VK_RValue, LBracLoc, ReceiverTypeInfo,
784 Sel, SelectorLoc, /*Method=*/0,
785 Args, NumArgs, RBracLoc));
788 // Find the class to which we are sending this message.
789 ObjCInterfaceDecl *Class = 0;
790 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>();
791 if (!ClassType || !(Class = ClassType->getInterface())) {
792 Diag(Loc, diag::err_invalid_receiver_class_message)
793 << ReceiverType;
794 return ExprError();
796 assert(Class && "We don't know which class we're messaging?");
798 // Find the method we are messaging.
799 if (!Method) {
800 if (Class->isForwardDecl()) {
801 // A forward class used in messaging is treated as a 'Class'
802 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName();
803 Method = LookupFactoryMethodInGlobalPool(Sel,
804 SourceRange(LBracLoc, RBracLoc));
805 if (Method)
806 Diag(Method->getLocation(), diag::note_method_sent_forward_class)
807 << Method->getDeclName();
809 if (!Method)
810 Method = Class->lookupClassMethod(Sel);
812 // If we have an implementation in scope, check "private" methods.
813 if (!Method)
814 Method = LookupPrivateClassMethod(Sel, Class);
816 if (Method && DiagnoseUseOfDecl(Method, Loc))
817 return ExprError();
820 // Check the argument types and determine the result type.
821 QualType ReturnType;
822 ExprValueKind VK = VK_RValue;
824 unsigned NumArgs = ArgsIn.size();
825 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
826 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true,
827 LBracLoc, RBracLoc, ReturnType, VK))
828 return ExprError();
830 // Construct the appropriate ObjCMessageExpr.
831 Expr *Result;
832 if (SuperLoc.isValid())
833 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
834 SuperLoc, /*IsInstanceSuper=*/false,
835 ReceiverType, Sel, SelectorLoc,
836 Method, Args, NumArgs, RBracLoc);
837 else
838 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
839 ReceiverTypeInfo, Sel, SelectorLoc,
840 Method, Args, NumArgs, RBracLoc);
841 return MaybeBindToTemporary(Result);
844 // ActOnClassMessage - used for both unary and keyword messages.
845 // ArgExprs is optional - if it is present, the number of expressions
846 // is obtained from Sel.getNumArgs().
847 ExprResult Sema::ActOnClassMessage(Scope *S,
848 ParsedType Receiver,
849 Selector Sel,
850 SourceLocation LBracLoc,
851 SourceLocation SelectorLoc,
852 SourceLocation RBracLoc,
853 MultiExprArg Args) {
854 TypeSourceInfo *ReceiverTypeInfo;
855 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo);
856 if (ReceiverType.isNull())
857 return ExprError();
860 if (!ReceiverTypeInfo)
861 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc);
863 return BuildClassMessage(ReceiverTypeInfo, ReceiverType,
864 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
865 LBracLoc, SelectorLoc, RBracLoc, move(Args));
868 /// \brief Build an Objective-C instance message expression.
870 /// This routine takes care of both normal instance messages and
871 /// instance messages to the superclass instance.
873 /// \param Receiver The expression that computes the object that will
874 /// receive this message. This may be empty, in which case we are
875 /// sending to the superclass instance and \p SuperLoc must be a valid
876 /// source location.
878 /// \param ReceiverType The (static) type of the object receiving the
879 /// message. When a \p Receiver expression is provided, this is the
880 /// same type as that expression. For a superclass instance send, this
881 /// is a pointer to the type of the superclass.
883 /// \param SuperLoc The location of the "super" keyword in a
884 /// superclass instance message.
886 /// \param Sel The selector to which the message is being sent.
888 /// \param Method The method that this instance message is invoking, if
889 /// already known.
891 /// \param LBracLoc The location of the opening square bracket ']'.
893 /// \param RBrac The location of the closing square bracket ']'.
895 /// \param Args The message arguments.
896 ExprResult Sema::BuildInstanceMessage(Expr *Receiver,
897 QualType ReceiverType,
898 SourceLocation SuperLoc,
899 Selector Sel,
900 ObjCMethodDecl *Method,
901 SourceLocation LBracLoc,
902 SourceLocation SelectorLoc,
903 SourceLocation RBracLoc,
904 MultiExprArg ArgsIn) {
905 // The location of the receiver.
906 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart();
908 if (LBracLoc.isInvalid()) {
909 Diag(Loc, diag::err_missing_open_square_message_send)
910 << FixItHint::CreateInsertion(Loc, "[");
911 LBracLoc = Loc;
914 // If we have a receiver expression, perform appropriate promotions
915 // and determine receiver type.
916 if (Receiver) {
917 if (Receiver->isTypeDependent()) {
918 // If the receiver is type-dependent, we can't type-check anything
919 // at this point. Build a dependent expression.
920 unsigned NumArgs = ArgsIn.size();
921 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
922 assert(SuperLoc.isInvalid() && "Message to super with dependent type");
923 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy,
924 VK_RValue, LBracLoc, Receiver, Sel,
925 SelectorLoc, /*Method=*/0,
926 Args, NumArgs, RBracLoc));
929 // If necessary, apply function/array conversion to the receiver.
930 // C99 6.7.5.3p[7,8].
931 DefaultFunctionArrayLvalueConversion(Receiver);
932 ReceiverType = Receiver->getType();
935 if (!Method) {
936 // Handle messages to id.
937 bool receiverIsId = ReceiverType->isObjCIdType();
938 if (receiverIsId || ReceiverType->isBlockPointerType() ||
939 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) {
940 Method = LookupInstanceMethodInGlobalPool(Sel,
941 SourceRange(LBracLoc, RBracLoc),
942 receiverIsId);
943 if (!Method)
944 Method = LookupFactoryMethodInGlobalPool(Sel,
945 SourceRange(LBracLoc, RBracLoc),
946 receiverIsId);
947 } else if (ReceiverType->isObjCClassType() ||
948 ReceiverType->isObjCQualifiedClassType()) {
949 // Handle messages to Class.
950 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) {
951 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) {
952 // First check the public methods in the class interface.
953 Method = ClassDecl->lookupClassMethod(Sel);
955 if (!Method)
956 Method = LookupPrivateClassMethod(Sel, ClassDecl);
958 // FIXME: if we still haven't found a method, we need to look in
959 // protocols (if we have qualifiers).
961 if (Method && DiagnoseUseOfDecl(Method, Loc))
962 return ExprError();
964 if (!Method) {
965 // If not messaging 'self', look for any factory method named 'Sel'.
966 if (!Receiver || !isSelfExpr(Receiver)) {
967 Method = LookupFactoryMethodInGlobalPool(Sel,
968 SourceRange(LBracLoc, RBracLoc),
969 true);
970 if (!Method) {
971 // If no class (factory) method was found, check if an _instance_
972 // method of the same name exists in the root class only.
973 Method = LookupInstanceMethodInGlobalPool(Sel,
974 SourceRange(LBracLoc, RBracLoc),
975 true);
976 if (Method)
977 if (const ObjCInterfaceDecl *ID =
978 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) {
979 if (ID->getSuperClass())
980 Diag(Loc, diag::warn_root_inst_method_not_found)
981 << Sel << SourceRange(LBracLoc, RBracLoc);
986 } else {
987 ObjCInterfaceDecl* ClassDecl = 0;
989 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as
990 // long as one of the protocols implements the selector (if not, warn).
991 if (const ObjCObjectPointerType *QIdTy
992 = ReceiverType->getAsObjCQualifiedIdType()) {
993 // Search protocols for instance methods.
994 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
995 E = QIdTy->qual_end(); I != E; ++I) {
996 ObjCProtocolDecl *PDecl = *I;
997 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel)))
998 break;
999 // Since we aren't supporting "Class<foo>", look for a class method.
1000 if (PDecl && (Method = PDecl->lookupClassMethod(Sel)))
1001 break;
1003 } else if (const ObjCObjectPointerType *OCIType
1004 = ReceiverType->getAsObjCInterfacePointerType()) {
1005 // We allow sending a message to a pointer to an interface (an object).
1006 ClassDecl = OCIType->getInterfaceDecl();
1007 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be
1008 // faster than the following method (which can do *many* linear searches).
1009 // The idea is to add class info to MethodPool.
1010 Method = ClassDecl->lookupInstanceMethod(Sel);
1012 if (!Method) {
1013 // Search protocol qualifiers.
1014 for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(),
1015 E = OCIType->qual_end(); QI != E; ++QI) {
1016 if ((Method = (*QI)->lookupInstanceMethod(Sel)))
1017 break;
1020 if (!Method) {
1021 // If we have implementations in scope, check "private" methods.
1022 Method = LookupPrivateInstanceMethod(Sel, ClassDecl);
1024 if (!Method && (!Receiver || !isSelfExpr(Receiver))) {
1025 // If we still haven't found a method, look in the global pool. This
1026 // behavior isn't very desirable, however we need it for GCC
1027 // compatibility. FIXME: should we deviate??
1028 if (OCIType->qual_empty()) {
1029 Method = LookupInstanceMethodInGlobalPool(Sel,
1030 SourceRange(LBracLoc, RBracLoc));
1031 if (Method && !OCIType->getInterfaceDecl()->isForwardDecl())
1032 Diag(Loc, diag::warn_maynot_respond)
1033 << OCIType->getInterfaceDecl()->getIdentifier() << Sel;
1037 if (Method && DiagnoseUseOfDecl(Method, Loc))
1038 return ExprError();
1039 } else if (!Context.getObjCIdType().isNull() &&
1040 (ReceiverType->isPointerType() ||
1041 ReceiverType->isIntegerType())) {
1042 // Implicitly convert integers and pointers to 'id' but emit a warning.
1043 Diag(Loc, diag::warn_bad_receiver_type)
1044 << ReceiverType
1045 << Receiver->getSourceRange();
1046 if (ReceiverType->isPointerType())
1047 ImpCastExprToType(Receiver, Context.getObjCIdType(),
1048 CK_BitCast);
1049 else {
1050 // TODO: specialized warning on null receivers?
1051 bool IsNull = Receiver->isNullPointerConstant(Context,
1052 Expr::NPC_ValueDependentIsNull);
1053 ImpCastExprToType(Receiver, Context.getObjCIdType(),
1054 IsNull ? CK_NullToPointer : CK_IntegralToPointer);
1056 ReceiverType = Receiver->getType();
1058 else if (getLangOptions().CPlusPlus &&
1059 !PerformContextuallyConvertToObjCId(Receiver)) {
1060 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) {
1061 Receiver = ICE->getSubExpr();
1062 ReceiverType = Receiver->getType();
1064 return BuildInstanceMessage(Receiver,
1065 ReceiverType,
1066 SuperLoc,
1067 Sel,
1068 Method,
1069 LBracLoc,
1070 SelectorLoc,
1071 RBracLoc,
1072 move(ArgsIn));
1073 } else {
1074 // Reject other random receiver types (e.g. structs).
1075 Diag(Loc, diag::err_bad_receiver_type)
1076 << ReceiverType << Receiver->getSourceRange();
1077 return ExprError();
1082 // Check the message arguments.
1083 unsigned NumArgs = ArgsIn.size();
1084 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release());
1085 QualType ReturnType;
1086 ExprValueKind VK = VK_RValue;
1087 bool ClassMessage = (ReceiverType->isObjCClassType() ||
1088 ReceiverType->isObjCQualifiedClassType());
1089 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, ClassMessage,
1090 LBracLoc, RBracLoc, ReturnType, VK))
1091 return ExprError();
1093 if (!ReturnType->isVoidType()) {
1094 if (RequireCompleteType(LBracLoc, ReturnType,
1095 diag::err_illegal_message_expr_incomplete_type))
1096 return ExprError();
1099 // Construct the appropriate ObjCMessageExpr instance.
1100 Expr *Result;
1101 if (SuperLoc.isValid())
1102 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1103 SuperLoc, /*IsInstanceSuper=*/true,
1104 ReceiverType, Sel, SelectorLoc, Method,
1105 Args, NumArgs, RBracLoc);
1106 else
1107 Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc,
1108 Receiver, Sel, SelectorLoc, Method,
1109 Args, NumArgs, RBracLoc);
1110 return MaybeBindToTemporary(Result);
1113 // ActOnInstanceMessage - used for both unary and keyword messages.
1114 // ArgExprs is optional - if it is present, the number of expressions
1115 // is obtained from Sel.getNumArgs().
1116 ExprResult Sema::ActOnInstanceMessage(Scope *S,
1117 Expr *Receiver,
1118 Selector Sel,
1119 SourceLocation LBracLoc,
1120 SourceLocation SelectorLoc,
1121 SourceLocation RBracLoc,
1122 MultiExprArg Args) {
1123 if (!Receiver)
1124 return ExprError();
1126 return BuildInstanceMessage(Receiver, Receiver->getType(),
1127 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0,
1128 LBracLoc, SelectorLoc, RBracLoc, move(Args));