SemaExprObjC.cpp revision b9d1dba5986d9b5cd4e1a5ff93759b3704593829
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. 11// 12//===----------------------------------------------------------------------===// 13 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" 24 25using namespace clang; 26 27ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs, 28 Expr **strings, 29 unsigned NumStrings) { 30 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings); 31 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]; 37 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; 43 44 for (unsigned i = 0; i != NumStrings; ++i) { 45 S = Strings[i]; 46 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; 52 } 53 54 // Append the string. 55 StrBuf += S->getString(); 56 57 // Get the locations of the string tokens. 58 StrLocs.append(S->tokloc_begin(), S->tokloc_end()); 59 } 60 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()); 66 } 67 68 // Verify that this composite string is acceptable for ObjC strings. 69 if (CheckObjCString(S)) 70 return true; 71 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 = &Context.Idents.get("NSConstantString"); 81 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0], 82 LookupOrdinaryName); 83 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { 84 Context.setObjCConstantStringInterface(StrIF); 85 Ty = Context.getObjCConstantStringInterface(); 86 Ty = Context.getObjCObjectPointerType(Ty); 87 } else { 88 // If there is no NSConstantString interface defined then treat this 89 // as error and recover from it. 90 Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent 91 << S->getSourceRange(); 92 Ty = Context.getObjCIdType(); 93 } 94 } else { 95 IdentifierInfo *NSIdent = &Context.Idents.get("NSString"); 96 NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLocs[0], 97 LookupOrdinaryName); 98 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { 99 Context.setObjCConstantStringInterface(StrIF); 100 Ty = Context.getObjCConstantStringInterface(); 101 Ty = Context.getObjCObjectPointerType(Ty); 102 } else { 103 // If there is no NSString interface defined then treat constant 104 // strings as untyped objects and let the runtime figure it out later. 105 Ty = Context.getObjCIdType(); 106 } 107 } 108 109 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]); 110} 111 112Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc, 113 TypeSourceInfo *EncodedTypeInfo, 114 SourceLocation RParenLoc) { 115 QualType EncodedType = EncodedTypeInfo->getType(); 116 QualType StrTy; 117 if (EncodedType->isDependentType()) 118 StrTy = Context.DependentTy; 119 else { 120 std::string Str; 121 Context.getObjCEncodingForType(EncodedType, Str); 122 123 // The type of @encode is the same as the type of the corresponding string, 124 // which is an array type. 125 StrTy = Context.CharTy; 126 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 127 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings) 128 StrTy.addConst(); 129 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1), 130 ArrayType::Normal, 0); 131 } 132 133 return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc); 134} 135 136ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc, 137 SourceLocation EncodeLoc, 138 SourceLocation LParenLoc, 139 ParsedType ty, 140 SourceLocation RParenLoc) { 141 // FIXME: Preserve type source info ? 142 TypeSourceInfo *TInfo; 143 QualType EncodedType = GetTypeFromParser(ty, &TInfo); 144 if (!TInfo) 145 TInfo = Context.getTrivialTypeSourceInfo(EncodedType, 146 PP.getLocForEndOfToken(LParenLoc)); 147 148 return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc); 149} 150 151ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, 152 SourceLocation AtLoc, 153 SourceLocation SelLoc, 154 SourceLocation LParenLoc, 155 SourceLocation RParenLoc) { 156 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel, 157 SourceRange(LParenLoc, RParenLoc), false, false); 158 if (!Method) 159 Method = LookupFactoryMethodInGlobalPool(Sel, 160 SourceRange(LParenLoc, RParenLoc)); 161 if (!Method) 162 Diag(SelLoc, diag::warn_undeclared_selector) << Sel; 163 164 llvm::DenseMap<Selector, SourceLocation>::iterator Pos 165 = ReferencedSelectors.find(Sel); 166 if (Pos == ReferencedSelectors.end()) 167 ReferencedSelectors.insert(std::make_pair(Sel, SelLoc)); 168 169 QualType Ty = Context.getObjCSelType(); 170 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc); 171} 172 173ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId, 174 SourceLocation AtLoc, 175 SourceLocation ProtoLoc, 176 SourceLocation LParenLoc, 177 SourceLocation RParenLoc) { 178 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoLoc); 179 if (!PDecl) { 180 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId; 181 return true; 182 } 183 184 QualType Ty = Context.getObjCProtoType(); 185 if (Ty.isNull()) 186 return true; 187 Ty = Context.getObjCObjectPointerType(Ty); 188 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc); 189} 190 191bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs, 192 Selector Sel, ObjCMethodDecl *Method, 193 bool isClassMessage, 194 SourceLocation lbrac, SourceLocation rbrac, 195 QualType &ReturnType) { 196 if (!Method) { 197 // Apply default argument promotion as for (C99 6.5.2.2p6). 198 for (unsigned i = 0; i != NumArgs; i++) { 199 if (Args[i]->isTypeDependent()) 200 continue; 201 202 DefaultArgumentPromotion(Args[i]); 203 } 204 205 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found : 206 diag::warn_inst_method_not_found; 207 Diag(lbrac, DiagID) 208 << Sel << isClassMessage << SourceRange(lbrac, rbrac); 209 ReturnType = Context.getObjCIdType(); 210 return false; 211 } 212 213 ReturnType = Method->getSendResultType(); 214 215 unsigned NumNamedArgs = Sel.getNumArgs(); 216 // Method might have more arguments than selector indicates. This is due 217 // to addition of c-style arguments in method. 218 if (Method->param_size() > Sel.getNumArgs()) 219 NumNamedArgs = Method->param_size(); 220 // FIXME. This need be cleaned up. 221 if (NumArgs < NumNamedArgs) { 222 Diag(lbrac, diag::err_typecheck_call_too_few_args) << 2 223 << NumNamedArgs << NumArgs; 224 return false; 225 } 226 227 bool IsError = false; 228 for (unsigned i = 0; i < NumNamedArgs; i++) { 229 // We can't do any type-checking on a type-dependent argument. 230 if (Args[i]->isTypeDependent()) 231 continue; 232 233 Expr *argExpr = Args[i]; 234 235 ParmVarDecl *Param = Method->param_begin()[i]; 236 assert(argExpr && "CheckMessageArgumentTypes(): missing expression"); 237 238 if (RequireCompleteType(argExpr->getSourceRange().getBegin(), 239 Param->getType(), 240 PDiag(diag::err_call_incomplete_argument) 241 << argExpr->getSourceRange())) 242 return true; 243 244 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 245 Param); 246 ExprResult ArgE = PerformCopyInitialization(Entity, 247 SourceLocation(), 248 Owned(argExpr->Retain())); 249 if (ArgE.isInvalid()) 250 IsError = true; 251 else 252 Args[i] = ArgE.takeAs<Expr>(); 253 } 254 255 // Promote additional arguments to variadic methods. 256 if (Method->isVariadic()) { 257 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) { 258 if (Args[i]->isTypeDependent()) 259 continue; 260 261 IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 262 } 263 } else { 264 // Check for extra arguments to non-variadic methods. 265 if (NumArgs != NumNamedArgs) { 266 Diag(Args[NumNamedArgs]->getLocStart(), 267 diag::err_typecheck_call_too_many_args) 268 << 2 /*method*/ << NumNamedArgs << NumArgs 269 << Method->getSourceRange() 270 << SourceRange(Args[NumNamedArgs]->getLocStart(), 271 Args[NumArgs-1]->getLocEnd()); 272 } 273 } 274 275 DiagnoseSentinelCalls(Method, lbrac, Args, NumArgs); 276 return IsError; 277} 278 279bool Sema::isSelfExpr(Expr *RExpr) { 280 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr)) 281 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self")) 282 return true; 283 return false; 284} 285 286// Helper method for ActOnClassMethod/ActOnInstanceMethod. 287// Will search "local" class/category implementations for a method decl. 288// If failed, then we search in class's root for an instance method. 289// Returns 0 if no method is found. 290ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel, 291 ObjCInterfaceDecl *ClassDecl) { 292 ObjCMethodDecl *Method = 0; 293 // lookup in class and all superclasses 294 while (ClassDecl && !Method) { 295 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation()) 296 Method = ImpDecl->getClassMethod(Sel); 297 298 // Look through local category implementations associated with the class. 299 if (!Method) 300 Method = ClassDecl->getCategoryClassMethod(Sel); 301 302 // Before we give up, check if the selector is an instance method. 303 // But only in the root. This matches gcc's behaviour and what the 304 // runtime expects. 305 if (!Method && !ClassDecl->getSuperClass()) { 306 Method = ClassDecl->lookupInstanceMethod(Sel); 307 // Look through local category implementations associated 308 // with the root class. 309 if (!Method) 310 Method = LookupPrivateInstanceMethod(Sel, ClassDecl); 311 } 312 313 ClassDecl = ClassDecl->getSuperClass(); 314 } 315 return Method; 316} 317 318ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel, 319 ObjCInterfaceDecl *ClassDecl) { 320 ObjCMethodDecl *Method = 0; 321 while (ClassDecl && !Method) { 322 // If we have implementations in scope, check "private" methods. 323 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation()) 324 Method = ImpDecl->getInstanceMethod(Sel); 325 326 // Look through local category implementations associated with the class. 327 if (!Method) 328 Method = ClassDecl->getCategoryInstanceMethod(Sel); 329 ClassDecl = ClassDecl->getSuperClass(); 330 } 331 return Method; 332} 333 334/// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an 335/// objective C interface. This is a property reference expression. 336ExprResult Sema:: 337HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, 338 Expr *BaseExpr, DeclarationName MemberName, 339 SourceLocation MemberLoc, 340 SourceLocation SuperLoc, QualType SuperType, 341 bool Super) { 342 const ObjCInterfaceType *IFaceT = OPT->getInterfaceType(); 343 ObjCInterfaceDecl *IFace = IFaceT->getDecl(); 344 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 345 346 // Search for a declared property first. 347 if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) { 348 // Check whether we can reference this property. 349 if (DiagnoseUseOfDecl(PD, MemberLoc)) 350 return ExprError(); 351 QualType ResTy = PD->getType(); 352 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 353 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 354 if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc)) 355 ResTy = Getter->getSendResultType(); 356 if (Super) 357 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy, 358 MemberLoc, 359 SuperLoc, SuperType)); 360 else 361 return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy, 362 MemberLoc, BaseExpr)); 363 } 364 // Check protocols on qualified interfaces. 365 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 366 E = OPT->qual_end(); I != E; ++I) 367 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) { 368 // Check whether we can reference this property. 369 if (DiagnoseUseOfDecl(PD, MemberLoc)) 370 return ExprError(); 371 if (Super) 372 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 373 MemberLoc, 374 SuperLoc, SuperType)); 375 else 376 return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(), 377 MemberLoc, 378 BaseExpr)); 379 } 380 // If that failed, look for an "implicit" property by seeing if the nullary 381 // selector is implemented. 382 383 // FIXME: The logic for looking up nullary and unary selectors should be 384 // shared with the code in ActOnInstanceMessage. 385 386 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 387 ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); 388 389 // If this reference is in an @implementation, check for 'private' methods. 390 if (!Getter) 391 Getter = IFace->lookupPrivateInstanceMethod(Sel); 392 393 // Look through local category implementations associated with the class. 394 if (!Getter) 395 Getter = IFace->getCategoryInstanceMethod(Sel); 396 if (Getter) { 397 // Check if we can reference this property. 398 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 399 return ExprError(); 400 } 401 // If we found a getter then this may be a valid dot-reference, we 402 // will look for the matching setter, in case it is needed. 403 Selector SetterSel = 404 SelectorTable::constructSetterName(PP.getIdentifierTable(), 405 PP.getSelectorTable(), Member); 406 ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); 407 if (!Setter) { 408 // If this reference is in an @implementation, also check for 'private' 409 // methods. 410 Setter = IFace->lookupPrivateInstanceMethod(SetterSel); 411 } 412 // Look through local category implementations associated with the class. 413 if (!Setter) 414 Setter = IFace->getCategoryInstanceMethod(SetterSel); 415 416 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 417 return ExprError(); 418 419 if (Getter) { 420 QualType PType; 421 PType = Getter->getSendResultType(); 422 if (Super) 423 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType, 424 Setter, MemberLoc, 425 SuperLoc, SuperType)); 426 else 427 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType, 428 Setter, MemberLoc, 429 BaseExpr)); 430 431 } 432 433 // Attempt to correct for typos in property names. 434 LookupResult Res(*this, MemberName, MemberLoc, LookupOrdinaryName); 435 if (CorrectTypo(Res, 0, 0, IFace, false, CTC_NoKeywords, OPT) && 436 Res.getAsSingle<ObjCPropertyDecl>()) { 437 DeclarationName TypoResult = Res.getLookupName(); 438 Diag(MemberLoc, diag::err_property_not_found_suggest) 439 << MemberName << QualType(OPT, 0) << TypoResult 440 << FixItHint::CreateReplacement(MemberLoc, TypoResult.getAsString()); 441 ObjCPropertyDecl *Property = Res.getAsSingle<ObjCPropertyDecl>(); 442 Diag(Property->getLocation(), diag::note_previous_decl) 443 << Property->getDeclName(); 444 return HandleExprPropertyRefExpr(OPT, BaseExpr, TypoResult, MemberLoc, 445 SuperLoc, SuperType, Super); 446 } 447 448 Diag(MemberLoc, diag::err_property_not_found) 449 << MemberName << QualType(OPT, 0); 450 if (Setter && !Getter) 451 Diag(Setter->getLocation(), diag::note_getter_unavailable) 452 << MemberName << BaseExpr->getSourceRange(); 453 return ExprError(); 454} 455 456 457 458ExprResult Sema:: 459ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, 460 IdentifierInfo &propertyName, 461 SourceLocation receiverNameLoc, 462 SourceLocation propertyNameLoc) { 463 464 IdentifierInfo *receiverNamePtr = &receiverName; 465 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr, 466 receiverNameLoc); 467 if (IFace == 0) { 468 // If the "receiver" is 'super' in a method, handle it as an expression-like 469 // property reference. 470 if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) 471 if (receiverNamePtr->isStr("super")) { 472 if (CurMethod->isInstanceMethod()) { 473 QualType T = 474 Context.getObjCInterfaceType(CurMethod->getClassInterface()); 475 T = Context.getObjCObjectPointerType(T); 476 477 return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(), 478 /*BaseExpr*/0, &propertyName, 479 propertyNameLoc, 480 receiverNameLoc, T, true); 481 } 482 483 // Otherwise, if this is a class method, try dispatching to our 484 // superclass. 485 IFace = CurMethod->getClassInterface()->getSuperClass(); 486 } 487 488 if (IFace == 0) { 489 Diag(receiverNameLoc, diag::err_expected_ident_or_lparen); 490 return ExprError(); 491 } 492 } 493 494 // Search for a declared property first. 495 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName); 496 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel); 497 498 // If this reference is in an @implementation, check for 'private' methods. 499 if (!Getter) 500 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 501 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 502 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation()) 503 Getter = ImpDecl->getClassMethod(Sel); 504 505 if (Getter) { 506 // FIXME: refactor/share with ActOnMemberReference(). 507 // Check if we can reference this property. 508 if (DiagnoseUseOfDecl(Getter, propertyNameLoc)) 509 return ExprError(); 510 } 511 512 // Look for the matching setter, in case it is needed. 513 Selector SetterSel = 514 SelectorTable::constructSetterName(PP.getIdentifierTable(), 515 PP.getSelectorTable(), &propertyName); 516 517 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 518 if (!Setter) { 519 // If this reference is in an @implementation, also check for 'private' 520 // methods. 521 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 522 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 523 if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation()) 524 Setter = ImpDecl->getClassMethod(SetterSel); 525 } 526 // Look through local category implementations associated with the class. 527 if (!Setter) 528 Setter = IFace->getCategoryClassMethod(SetterSel); 529 530 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc)) 531 return ExprError(); 532 533 if (Getter || Setter) { 534 QualType PType; 535 536 if (Getter) 537 PType = Getter->getSendResultType(); 538 else { 539 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(), 540 E = Setter->param_end(); PI != E; ++PI) 541 PType = (*PI)->getType(); 542 } 543 return Owned(new (Context) ObjCImplicitSetterGetterRefExpr( 544 Getter, PType, Setter, 545 propertyNameLoc, IFace, receiverNameLoc)); 546 } 547 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found) 548 << &propertyName << Context.getObjCInterfaceType(IFace)); 549} 550 551Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S, 552 IdentifierInfo *Name, 553 SourceLocation NameLoc, 554 bool IsSuper, 555 bool HasTrailingDot, 556 ParsedType &ReceiverType) { 557 ReceiverType = ParsedType(); 558 559 // If the identifier is "super" and there is no trailing dot, we're 560 // messaging super. If the identifier is "super" and there is a 561 // trailing dot, it's an instance message. 562 if (IsSuper && S->isInObjcMethodScope()) 563 return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage; 564 565 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); 566 LookupName(Result, S); 567 568 switch (Result.getResultKind()) { 569 case LookupResult::NotFound: 570 // Normal name lookup didn't find anything. If we're in an 571 // Objective-C method, look for ivars. If we find one, we're done! 572 // FIXME: This is a hack. Ivar lookup should be part of normal 573 // lookup. 574 if (ObjCMethodDecl *Method = getCurMethodDecl()) { 575 ObjCInterfaceDecl *ClassDeclared; 576 if (Method->getClassInterface()->lookupInstanceVariable(Name, 577 ClassDeclared)) 578 return ObjCInstanceMessage; 579 } 580 581 // Break out; we'll perform typo correction below. 582 break; 583 584 case LookupResult::NotFoundInCurrentInstantiation: 585 case LookupResult::FoundOverloaded: 586 case LookupResult::FoundUnresolvedValue: 587 case LookupResult::Ambiguous: 588 Result.suppressDiagnostics(); 589 return ObjCInstanceMessage; 590 591 case LookupResult::Found: { 592 // We found something. If it's a type, then we have a class 593 // message. Otherwise, it's an instance message. 594 NamedDecl *ND = Result.getFoundDecl(); 595 QualType T; 596 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) 597 T = Context.getObjCInterfaceType(Class); 598 else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) 599 T = Context.getTypeDeclType(Type); 600 else 601 return ObjCInstanceMessage; 602 603 // We have a class message, and T is the type we're 604 // messaging. Build source-location information for it. 605 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc); 606 ReceiverType = CreateParsedType(T, TSInfo); 607 return ObjCClassMessage; 608 } 609 } 610 611 // Determine our typo-correction context. 612 CorrectTypoContext CTC = CTC_Expression; 613 if (ObjCMethodDecl *Method = getCurMethodDecl()) 614 if (Method->getClassInterface() && 615 Method->getClassInterface()->getSuperClass()) 616 CTC = CTC_ObjCMessageReceiver; 617 618 if (DeclarationName Corrected = CorrectTypo(Result, S, 0, 0, false, CTC)) { 619 if (Result.isSingleResult()) { 620 // If we found a declaration, correct when it refers to an Objective-C 621 // class. 622 NamedDecl *ND = Result.getFoundDecl(); 623 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) { 624 Diag(NameLoc, diag::err_unknown_receiver_suggest) 625 << Name << Result.getLookupName() 626 << FixItHint::CreateReplacement(SourceRange(NameLoc), 627 ND->getNameAsString()); 628 Diag(ND->getLocation(), diag::note_previous_decl) 629 << Corrected; 630 631 QualType T = Context.getObjCInterfaceType(Class); 632 TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc); 633 ReceiverType = CreateParsedType(T, TSInfo); 634 return ObjCClassMessage; 635 } 636 } else if (Result.empty() && Corrected.getAsIdentifierInfo() && 637 Corrected.getAsIdentifierInfo()->isStr("super")) { 638 // If we've found the keyword "super", this is a send to super. 639 Diag(NameLoc, diag::err_unknown_receiver_suggest) 640 << Name << Corrected 641 << FixItHint::CreateReplacement(SourceRange(NameLoc), "super"); 642 Name = Corrected.getAsIdentifierInfo(); 643 return ObjCSuperMessage; 644 } 645 } 646 647 // Fall back: let the parser try to parse it as an instance message. 648 return ObjCInstanceMessage; 649} 650 651ExprResult Sema::ActOnSuperMessage(Scope *S, 652 SourceLocation SuperLoc, 653 Selector Sel, 654 SourceLocation LBracLoc, 655 SourceLocation SelectorLoc, 656 SourceLocation RBracLoc, 657 MultiExprArg Args) { 658 // Determine whether we are inside a method or not. 659 ObjCMethodDecl *Method = getCurMethodDecl(); 660 if (!Method) { 661 Diag(SuperLoc, diag::err_invalid_receiver_to_message_super); 662 return ExprError(); 663 } 664 665 ObjCInterfaceDecl *Class = Method->getClassInterface(); 666 if (!Class) { 667 Diag(SuperLoc, diag::error_no_super_class_message) 668 << Method->getDeclName(); 669 return ExprError(); 670 } 671 672 ObjCInterfaceDecl *Super = Class->getSuperClass(); 673 if (!Super) { 674 // The current class does not have a superclass. 675 Diag(SuperLoc, diag::error_no_super_class) << Class->getIdentifier(); 676 return ExprError(); 677 } 678 679 // We are in a method whose class has a superclass, so 'super' 680 // is acting as a keyword. 681 if (Method->isInstanceMethod()) { 682 // Since we are in an instance method, this is an instance 683 // message to the superclass instance. 684 QualType SuperTy = Context.getObjCInterfaceType(Super); 685 SuperTy = Context.getObjCObjectPointerType(SuperTy); 686 return BuildInstanceMessage(0, SuperTy, SuperLoc, 687 Sel, /*Method=*/0, LBracLoc, RBracLoc, 688 move(Args)); 689 } 690 691 // Since we are in a class method, this is a class message to 692 // the superclass. 693 return BuildClassMessage(/*ReceiverTypeInfo=*/0, 694 Context.getObjCInterfaceType(Super), 695 SuperLoc, Sel, /*Method=*/0, LBracLoc, RBracLoc, 696 move(Args)); 697} 698 699/// \brief Build an Objective-C class message expression. 700/// 701/// This routine takes care of both normal class messages and 702/// class messages to the superclass. 703/// 704/// \param ReceiverTypeInfo Type source information that describes the 705/// receiver of this message. This may be NULL, in which case we are 706/// sending to the superclass and \p SuperLoc must be a valid source 707/// location. 708 709/// \param ReceiverType The type of the object receiving the 710/// message. When \p ReceiverTypeInfo is non-NULL, this is the same 711/// type as that refers to. For a superclass send, this is the type of 712/// the superclass. 713/// 714/// \param SuperLoc The location of the "super" keyword in a 715/// superclass message. 716/// 717/// \param Sel The selector to which the message is being sent. 718/// 719/// \param Method The method that this class message is invoking, if 720/// already known. 721/// 722/// \param LBracLoc The location of the opening square bracket ']'. 723/// 724/// \param RBrac The location of the closing square bracket ']'. 725/// 726/// \param Args The message arguments. 727ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, 728 QualType ReceiverType, 729 SourceLocation SuperLoc, 730 Selector Sel, 731 ObjCMethodDecl *Method, 732 SourceLocation LBracLoc, 733 SourceLocation RBracLoc, 734 MultiExprArg ArgsIn) { 735 SourceLocation Loc = SuperLoc.isValid()? SuperLoc 736 : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin(); 737 if (LBracLoc.isInvalid()) { 738 Diag(Loc, diag::err_missing_open_square_message_send) 739 << FixItHint::CreateInsertion(Loc, "["); 740 LBracLoc = Loc; 741 } 742 743 if (ReceiverType->isDependentType()) { 744 // If the receiver type is dependent, we can't type-check anything 745 // at this point. Build a dependent expression. 746 unsigned NumArgs = ArgsIn.size(); 747 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release()); 748 assert(SuperLoc.isInvalid() && "Message to super with dependent type"); 749 return Owned(ObjCMessageExpr::Create(Context, ReceiverType, LBracLoc, 750 ReceiverTypeInfo, Sel, /*Method=*/0, 751 Args, NumArgs, RBracLoc)); 752 } 753 754 // Find the class to which we are sending this message. 755 ObjCInterfaceDecl *Class = 0; 756 const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>(); 757 if (!ClassType || !(Class = ClassType->getInterface())) { 758 Diag(Loc, diag::err_invalid_receiver_class_message) 759 << ReceiverType; 760 return ExprError(); 761 } 762 assert(Class && "We don't know which class we're messaging?"); 763 764 // Find the method we are messaging. 765 if (!Method) { 766 if (Class->isForwardDecl()) { 767 // A forward class used in messaging is treated as a 'Class' 768 Diag(Loc, diag::warn_receiver_forward_class) << Class->getDeclName(); 769 Method = LookupFactoryMethodInGlobalPool(Sel, 770 SourceRange(LBracLoc, RBracLoc)); 771 if (Method) 772 Diag(Method->getLocation(), diag::note_method_sent_forward_class) 773 << Method->getDeclName(); 774 } 775 if (!Method) 776 Method = Class->lookupClassMethod(Sel); 777 778 // If we have an implementation in scope, check "private" methods. 779 if (!Method) 780 Method = LookupPrivateClassMethod(Sel, Class); 781 782 if (Method && DiagnoseUseOfDecl(Method, Loc)) 783 return ExprError(); 784 } 785 786 // Check the argument types and determine the result type. 787 QualType ReturnType; 788 unsigned NumArgs = ArgsIn.size(); 789 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release()); 790 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, true, 791 LBracLoc, RBracLoc, ReturnType)) 792 return ExprError(); 793 794 // Construct the appropriate ObjCMessageExpr. 795 Expr *Result; 796 if (SuperLoc.isValid()) 797 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, 798 SuperLoc, /*IsInstanceSuper=*/false, 799 ReceiverType, Sel, Method, Args, 800 NumArgs, RBracLoc); 801 else 802 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, 803 ReceiverTypeInfo, Sel, Method, Args, 804 NumArgs, RBracLoc); 805 return MaybeBindToTemporary(Result); 806} 807 808// ActOnClassMessage - used for both unary and keyword messages. 809// ArgExprs is optional - if it is present, the number of expressions 810// is obtained from Sel.getNumArgs(). 811ExprResult Sema::ActOnClassMessage(Scope *S, 812 ParsedType Receiver, 813 Selector Sel, 814 SourceLocation LBracLoc, 815 SourceLocation SelectorLoc, 816 SourceLocation RBracLoc, 817 MultiExprArg Args) { 818 TypeSourceInfo *ReceiverTypeInfo; 819 QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo); 820 if (ReceiverType.isNull()) 821 return ExprError(); 822 823 824 if (!ReceiverTypeInfo) 825 ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc); 826 827 return BuildClassMessage(ReceiverTypeInfo, ReceiverType, 828 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0, 829 LBracLoc, RBracLoc, move(Args)); 830} 831 832/// \brief Build an Objective-C instance message expression. 833/// 834/// This routine takes care of both normal instance messages and 835/// instance messages to the superclass instance. 836/// 837/// \param Receiver The expression that computes the object that will 838/// receive this message. This may be empty, in which case we are 839/// sending to the superclass instance and \p SuperLoc must be a valid 840/// source location. 841/// 842/// \param ReceiverType The (static) type of the object receiving the 843/// message. When a \p Receiver expression is provided, this is the 844/// same type as that expression. For a superclass instance send, this 845/// is a pointer to the type of the superclass. 846/// 847/// \param SuperLoc The location of the "super" keyword in a 848/// superclass instance message. 849/// 850/// \param Sel The selector to which the message is being sent. 851/// 852/// \param Method The method that this instance message is invoking, if 853/// already known. 854/// 855/// \param LBracLoc The location of the opening square bracket ']'. 856/// 857/// \param RBrac The location of the closing square bracket ']'. 858/// 859/// \param Args The message arguments. 860ExprResult Sema::BuildInstanceMessage(Expr *Receiver, 861 QualType ReceiverType, 862 SourceLocation SuperLoc, 863 Selector Sel, 864 ObjCMethodDecl *Method, 865 SourceLocation LBracLoc, 866 SourceLocation RBracLoc, 867 MultiExprArg ArgsIn) { 868 // The location of the receiver. 869 SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart(); 870 871 if (LBracLoc.isInvalid()) { 872 Diag(Loc, diag::err_missing_open_square_message_send) 873 << FixItHint::CreateInsertion(Loc, "["); 874 LBracLoc = Loc; 875 } 876 877 // If we have a receiver expression, perform appropriate promotions 878 // and determine receiver type. 879 if (Receiver) { 880 if (Receiver->isTypeDependent()) { 881 // If the receiver is type-dependent, we can't type-check anything 882 // at this point. Build a dependent expression. 883 unsigned NumArgs = ArgsIn.size(); 884 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release()); 885 assert(SuperLoc.isInvalid() && "Message to super with dependent type"); 886 return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy, 887 LBracLoc, Receiver, Sel, 888 /*Method=*/0, Args, NumArgs, 889 RBracLoc)); 890 } 891 892 // If necessary, apply function/array conversion to the receiver. 893 // C99 6.7.5.3p[7,8]. 894 DefaultFunctionArrayLvalueConversion(Receiver); 895 ReceiverType = Receiver->getType(); 896 } 897 898 if (!Method) { 899 // Handle messages to id. 900 bool receiverIsId = ReceiverType->isObjCIdType(); 901 if (receiverIsId || ReceiverType->isBlockPointerType() || 902 (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) { 903 Method = LookupInstanceMethodInGlobalPool(Sel, 904 SourceRange(LBracLoc, RBracLoc), 905 receiverIsId); 906 if (!Method) 907 Method = LookupFactoryMethodInGlobalPool(Sel, 908 SourceRange(LBracLoc, RBracLoc), 909 receiverIsId); 910 } else if (ReceiverType->isObjCClassType() || 911 ReceiverType->isObjCQualifiedClassType()) { 912 // Handle messages to Class. 913 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { 914 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) { 915 // First check the public methods in the class interface. 916 Method = ClassDecl->lookupClassMethod(Sel); 917 918 if (!Method) 919 Method = LookupPrivateClassMethod(Sel, ClassDecl); 920 921 // FIXME: if we still haven't found a method, we need to look in 922 // protocols (if we have qualifiers). 923 } 924 if (Method && DiagnoseUseOfDecl(Method, Loc)) 925 return ExprError(); 926 } 927 if (!Method) { 928 // If not messaging 'self', look for any factory method named 'Sel'. 929 if (!Receiver || !isSelfExpr(Receiver)) { 930 Method = LookupFactoryMethodInGlobalPool(Sel, 931 SourceRange(LBracLoc, RBracLoc), 932 true); 933 if (!Method) { 934 // If no class (factory) method was found, check if an _instance_ 935 // method of the same name exists in the root class only. 936 Method = LookupInstanceMethodInGlobalPool(Sel, 937 SourceRange(LBracLoc, RBracLoc), 938 true); 939 if (Method) 940 if (const ObjCInterfaceDecl *ID = 941 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) { 942 if (ID->getSuperClass()) 943 Diag(Loc, diag::warn_root_inst_method_not_found) 944 << Sel << SourceRange(LBracLoc, RBracLoc); 945 } 946 } 947 } 948 } 949 } else { 950 ObjCInterfaceDecl* ClassDecl = 0; 951 952 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as 953 // long as one of the protocols implements the selector (if not, warn). 954 if (const ObjCObjectPointerType *QIdTy 955 = ReceiverType->getAsObjCQualifiedIdType()) { 956 // Search protocols for instance methods. 957 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 958 E = QIdTy->qual_end(); I != E; ++I) { 959 ObjCProtocolDecl *PDecl = *I; 960 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel))) 961 break; 962 // Since we aren't supporting "Class<foo>", look for a class method. 963 if (PDecl && (Method = PDecl->lookupClassMethod(Sel))) 964 break; 965 } 966 } else if (const ObjCObjectPointerType *OCIType 967 = ReceiverType->getAsObjCInterfacePointerType()) { 968 // We allow sending a message to a pointer to an interface (an object). 969 ClassDecl = OCIType->getInterfaceDecl(); 970 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be 971 // faster than the following method (which can do *many* linear searches). 972 // The idea is to add class info to MethodPool. 973 Method = ClassDecl->lookupInstanceMethod(Sel); 974 975 if (!Method) { 976 // Search protocol qualifiers. 977 for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(), 978 E = OCIType->qual_end(); QI != E; ++QI) { 979 if ((Method = (*QI)->lookupInstanceMethod(Sel))) 980 break; 981 } 982 } 983 if (!Method) { 984 // If we have implementations in scope, check "private" methods. 985 Method = LookupPrivateInstanceMethod(Sel, ClassDecl); 986 987 if (!Method && (!Receiver || !isSelfExpr(Receiver))) { 988 // If we still haven't found a method, look in the global pool. This 989 // behavior isn't very desirable, however we need it for GCC 990 // compatibility. FIXME: should we deviate?? 991 if (OCIType->qual_empty()) { 992 Method = LookupInstanceMethodInGlobalPool(Sel, 993 SourceRange(LBracLoc, RBracLoc)); 994 if (Method && !OCIType->getInterfaceDecl()->isForwardDecl()) 995 Diag(Loc, diag::warn_maynot_respond) 996 << OCIType->getInterfaceDecl()->getIdentifier() << Sel; 997 } 998 } 999 } 1000 if (Method && DiagnoseUseOfDecl(Method, Loc)) 1001 return ExprError(); 1002 } else if (!Context.getObjCIdType().isNull() && 1003 (ReceiverType->isPointerType() || 1004 ReceiverType->isIntegerType())) { 1005 // Implicitly convert integers and pointers to 'id' but emit a warning. 1006 Diag(Loc, diag::warn_bad_receiver_type) 1007 << ReceiverType 1008 << Receiver->getSourceRange(); 1009 if (ReceiverType->isPointerType()) 1010 ImpCastExprToType(Receiver, Context.getObjCIdType(), 1011 CK_BitCast); 1012 else 1013 ImpCastExprToType(Receiver, Context.getObjCIdType(), 1014 CK_IntegralToPointer); 1015 ReceiverType = Receiver->getType(); 1016 } 1017 else if (getLangOptions().CPlusPlus && 1018 !PerformContextuallyConvertToObjCId(Receiver)) { 1019 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Receiver)) { 1020 Receiver = ICE->getSubExpr(); 1021 ReceiverType = Receiver->getType(); 1022 } 1023 return BuildInstanceMessage(Receiver, 1024 ReceiverType, 1025 SuperLoc, 1026 Sel, 1027 Method, 1028 LBracLoc, 1029 RBracLoc, 1030 move(ArgsIn)); 1031 } else { 1032 // Reject other random receiver types (e.g. structs). 1033 Diag(Loc, diag::err_bad_receiver_type) 1034 << ReceiverType << Receiver->getSourceRange(); 1035 return ExprError(); 1036 } 1037 } 1038 } 1039 1040 // Check the message arguments. 1041 unsigned NumArgs = ArgsIn.size(); 1042 Expr **Args = reinterpret_cast<Expr **>(ArgsIn.release()); 1043 QualType ReturnType; 1044 if (CheckMessageArgumentTypes(Args, NumArgs, Sel, Method, false, 1045 LBracLoc, RBracLoc, ReturnType)) 1046 return ExprError(); 1047 1048 if (!ReturnType->isVoidType()) { 1049 if (RequireCompleteType(LBracLoc, ReturnType, 1050 diag::err_illegal_message_expr_incomplete_type)) 1051 return ExprError(); 1052 } 1053 1054 // Construct the appropriate ObjCMessageExpr instance. 1055 Expr *Result; 1056 if (SuperLoc.isValid()) 1057 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, 1058 SuperLoc, /*IsInstanceSuper=*/true, 1059 ReceiverType, Sel, Method, 1060 Args, NumArgs, RBracLoc); 1061 else 1062 Result = ObjCMessageExpr::Create(Context, ReturnType, LBracLoc, Receiver, 1063 Sel, Method, Args, NumArgs, RBracLoc); 1064 return MaybeBindToTemporary(Result); 1065} 1066 1067// ActOnInstanceMessage - used for both unary and keyword messages. 1068// ArgExprs is optional - if it is present, the number of expressions 1069// is obtained from Sel.getNumArgs(). 1070ExprResult Sema::ActOnInstanceMessage(Scope *S, 1071 Expr *Receiver, 1072 Selector Sel, 1073 SourceLocation LBracLoc, 1074 SourceLocation SelectorLoc, 1075 SourceLocation RBracLoc, 1076 MultiExprArg Args) { 1077 if (!Receiver) 1078 return ExprError(); 1079 1080 return BuildInstanceMessage(Receiver, Receiver->getType(), 1081 /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0, 1082 LBracLoc, RBracLoc, move(Args)); 1083} 1084 1085