SemaExprObjC.cpp revision 14108da7f7fc059772711e4ffee1322a27b152a7
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 "Sema.h" 15#include "clang/AST/ASTContext.h" 16#include "clang/AST/DeclObjC.h" 17#include "clang/AST/ExprObjC.h" 18#include "llvm/ADT/SmallString.h" 19#include "clang/Lex/Preprocessor.h" 20 21using namespace clang; 22 23Sema::ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs, 24 ExprTy **strings, 25 unsigned NumStrings) { 26 StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings); 27 28 // Most ObjC strings are formed out of a single piece. However, we *can* 29 // have strings formed out of multiple @ strings with multiple pptokens in 30 // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one 31 // StringLiteral for ObjCStringLiteral to hold onto. 32 StringLiteral *S = Strings[0]; 33 34 // If we have a multi-part string, merge it all together. 35 if (NumStrings != 1) { 36 // Concatenate objc strings. 37 llvm::SmallString<128> StrBuf; 38 llvm::SmallVector<SourceLocation, 8> StrLocs; 39 40 for (unsigned i = 0; i != NumStrings; ++i) { 41 S = Strings[i]; 42 43 // ObjC strings can't be wide. 44 if (S->isWide()) { 45 Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant) 46 << S->getSourceRange(); 47 return true; 48 } 49 50 // Get the string data. 51 StrBuf.append(S->getStrData(), S->getStrData()+S->getByteLength()); 52 53 // Get the locations of the string tokens. 54 StrLocs.append(S->tokloc_begin(), S->tokloc_end()); 55 56 // Free the temporary string. 57 S->Destroy(Context); 58 } 59 60 // Create the aggregate string with the appropriate content and location 61 // information. 62 S = StringLiteral::Create(Context, &StrBuf[0], StrBuf.size(), false, 63 Context.getPointerType(Context.CharTy), 64 &StrLocs[0], StrLocs.size()); 65 } 66 67 // Verify that this composite string is acceptable for ObjC strings. 68 if (CheckObjCString(S)) 69 return true; 70 71 // Initialize the constant string interface lazily. This assumes 72 // the NSString interface is seen in this translation unit. Note: We 73 // don't use NSConstantString, since the runtime team considers this 74 // interface private (even though it appears in the header files). 75 QualType Ty = Context.getObjCConstantStringInterface(); 76 if (!Ty.isNull()) { 77 Ty = Context.getObjCObjectPointerType(Ty); 78 } else { 79 IdentifierInfo *NSIdent = &Context.Idents.get("NSString"); 80 NamedDecl *IF = LookupName(TUScope, NSIdent, LookupOrdinaryName); 81 if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { 82 Context.setObjCConstantStringInterface(StrIF); 83 Ty = Context.getObjCConstantStringInterface(); 84 Ty = Context.getObjCObjectPointerType(Ty); 85 } else { 86 // If there is no NSString interface defined then treat constant 87 // strings as untyped objects and let the runtime figure it out later. 88 Ty = Context.getObjCIdType(); 89 } 90 } 91 92 return new (Context) ObjCStringLiteral(S, Ty, AtLocs[0]); 93} 94 95Expr *Sema::BuildObjCEncodeExpression(SourceLocation AtLoc, 96 QualType EncodedType, 97 SourceLocation RParenLoc) { 98 QualType StrTy; 99 if (EncodedType->isDependentType()) 100 StrTy = Context.DependentTy; 101 else { 102 std::string Str; 103 Context.getObjCEncodingForType(EncodedType, Str); 104 105 // The type of @encode is the same as the type of the corresponding string, 106 // which is an array type. 107 StrTy = Context.CharTy; 108 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). 109 if (getLangOptions().CPlusPlus) 110 StrTy.addConst(); 111 StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1), 112 ArrayType::Normal, 0); 113 } 114 115 return new (Context) ObjCEncodeExpr(StrTy, EncodedType, AtLoc, RParenLoc); 116} 117 118Sema::ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc, 119 SourceLocation EncodeLoc, 120 SourceLocation LParenLoc, 121 TypeTy *ty, 122 SourceLocation RParenLoc) { 123 QualType EncodedType = QualType::getFromOpaquePtr(ty); 124 125 return BuildObjCEncodeExpression(AtLoc, EncodedType, RParenLoc); 126} 127 128Sema::ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, 129 SourceLocation AtLoc, 130 SourceLocation SelLoc, 131 SourceLocation LParenLoc, 132 SourceLocation RParenLoc) { 133 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel, 134 SourceRange(LParenLoc, RParenLoc)); 135 if (!Method) 136 Method = LookupFactoryMethodInGlobalPool(Sel, 137 SourceRange(LParenLoc, RParenLoc)); 138 if (!Method) 139 Diag(SelLoc, diag::warn_undeclared_selector) << Sel; 140 141 QualType Ty = Context.getObjCSelType(); 142 return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc); 143} 144 145Sema::ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId, 146 SourceLocation AtLoc, 147 SourceLocation ProtoLoc, 148 SourceLocation LParenLoc, 149 SourceLocation RParenLoc) { 150 ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId); 151 if (!PDecl) { 152 Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId; 153 return true; 154 } 155 156 QualType Ty = Context.getObjCProtoType(); 157 if (Ty.isNull()) 158 return true; 159 Ty = Context.getObjCObjectPointerType(Ty); 160 return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, RParenLoc); 161} 162 163bool Sema::CheckMessageArgumentTypes(Expr **Args, unsigned NumArgs, 164 Selector Sel, ObjCMethodDecl *Method, 165 bool isClassMessage, 166 SourceLocation lbrac, SourceLocation rbrac, 167 QualType &ReturnType) { 168 if (!Method) { 169 // Apply default argument promotion as for (C99 6.5.2.2p6). 170 for (unsigned i = 0; i != NumArgs; i++) 171 DefaultArgumentPromotion(Args[i]); 172 173 unsigned DiagID = isClassMessage ? diag::warn_class_method_not_found : 174 diag::warn_inst_method_not_found; 175 Diag(lbrac, DiagID) 176 << Sel << isClassMessage << SourceRange(lbrac, rbrac); 177 ReturnType = Context.getObjCIdType(); 178 return false; 179 } 180 181 ReturnType = Method->getResultType(); 182 183 unsigned NumNamedArgs = Sel.getNumArgs(); 184 assert(NumArgs >= NumNamedArgs && "Too few arguments for selector!"); 185 186 bool IsError = false; 187 for (unsigned i = 0; i < NumNamedArgs; i++) { 188 Expr *argExpr = Args[i]; 189 assert(argExpr && "CheckMessageArgumentTypes(): missing expression"); 190 191 QualType lhsType = Method->param_begin()[i]->getType(); 192 QualType rhsType = argExpr->getType(); 193 194 // If necessary, apply function/array conversion. C99 6.7.5.3p[7,8]. 195 if (lhsType->isArrayType()) 196 lhsType = Context.getArrayDecayedType(lhsType); 197 else if (lhsType->isFunctionType()) 198 lhsType = Context.getPointerType(lhsType); 199 200 AssignConvertType Result = 201 CheckSingleAssignmentConstraints(lhsType, argExpr); 202 if (Args[i] != argExpr) // The expression was converted. 203 Args[i] = argExpr; // Make sure we store the converted expression. 204 205 IsError |= 206 DiagnoseAssignmentResult(Result, argExpr->getLocStart(), lhsType, rhsType, 207 argExpr, "sending"); 208 } 209 210 // Promote additional arguments to variadic methods. 211 if (Method->isVariadic()) { 212 for (unsigned i = NumNamedArgs; i < NumArgs; ++i) 213 IsError |= DefaultVariadicArgumentPromotion(Args[i], VariadicMethod); 214 } else { 215 // Check for extra arguments to non-variadic methods. 216 if (NumArgs != NumNamedArgs) { 217 Diag(Args[NumNamedArgs]->getLocStart(), 218 diag::err_typecheck_call_too_many_args) 219 << 2 /*method*/ << Method->getSourceRange() 220 << SourceRange(Args[NumNamedArgs]->getLocStart(), 221 Args[NumArgs-1]->getLocEnd()); 222 } 223 } 224 225 return IsError; 226} 227 228bool Sema::isSelfExpr(Expr *RExpr) { 229 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(RExpr)) 230 if (DRE->getDecl()->getIdentifier() == &Context.Idents.get("self")) 231 return true; 232 return false; 233} 234 235// Helper method for ActOnClassMethod/ActOnInstanceMethod. 236// Will search "local" class/category implementations for a method decl. 237// If failed, then we search in class's root for an instance method. 238// Returns 0 if no method is found. 239ObjCMethodDecl *Sema::LookupPrivateClassMethod(Selector Sel, 240 ObjCInterfaceDecl *ClassDecl) { 241 ObjCMethodDecl *Method = 0; 242 // lookup in class and all superclasses 243 while (ClassDecl && !Method) { 244 if (ObjCImplementationDecl *ImpDecl 245 = LookupObjCImplementation(ClassDecl->getIdentifier())) 246 Method = ImpDecl->getClassMethod(Sel); 247 248 // Look through local category implementations associated with the class. 249 if (!Method) { 250 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Method; i++) { 251 if (ObjCCategoryImpls[i]->getClassInterface() == ClassDecl) 252 Method = ObjCCategoryImpls[i]->getClassMethod(Sel); 253 } 254 } 255 256 // Before we give up, check if the selector is an instance method. 257 // But only in the root. This matches gcc's behaviour and what the 258 // runtime expects. 259 if (!Method && !ClassDecl->getSuperClass()) { 260 Method = ClassDecl->lookupInstanceMethod(Sel); 261 // Look through local category implementations associated 262 // with the root class. 263 if (!Method) 264 Method = LookupPrivateInstanceMethod(Sel, ClassDecl); 265 } 266 267 ClassDecl = ClassDecl->getSuperClass(); 268 } 269 return Method; 270} 271 272ObjCMethodDecl *Sema::LookupPrivateInstanceMethod(Selector Sel, 273 ObjCInterfaceDecl *ClassDecl) { 274 ObjCMethodDecl *Method = 0; 275 while (ClassDecl && !Method) { 276 // If we have implementations in scope, check "private" methods. 277 if (ObjCImplementationDecl *ImpDecl 278 = LookupObjCImplementation(ClassDecl->getIdentifier())) 279 Method = ImpDecl->getInstanceMethod(Sel); 280 281 // Look through local category implementations associated with the class. 282 if (!Method) { 283 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Method; i++) { 284 if (ObjCCategoryImpls[i]->getClassInterface() == ClassDecl) 285 Method = ObjCCategoryImpls[i]->getInstanceMethod(Sel); 286 } 287 } 288 ClassDecl = ClassDecl->getSuperClass(); 289 } 290 return Method; 291} 292 293Action::OwningExprResult Sema::ActOnClassPropertyRefExpr( 294 IdentifierInfo &receiverName, 295 IdentifierInfo &propertyName, 296 SourceLocation &receiverNameLoc, 297 SourceLocation &propertyNameLoc) { 298 299 ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(&receiverName); 300 301 // Search for a declared property first. 302 303 Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName); 304 ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel); 305 306 // If this reference is in an @implementation, check for 'private' methods. 307 if (!Getter) 308 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 309 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 310 if (ObjCImplementationDecl *ImpDecl 311 = LookupObjCImplementation(ClassDecl->getIdentifier())) 312 Getter = ImpDecl->getClassMethod(Sel); 313 314 if (Getter) { 315 // FIXME: refactor/share with ActOnMemberReference(). 316 // Check if we can reference this property. 317 if (DiagnoseUseOfDecl(Getter, propertyNameLoc)) 318 return ExprError(); 319 } 320 321 // Look for the matching setter, in case it is needed. 322 Selector SetterSel = 323 SelectorTable::constructSetterName(PP.getIdentifierTable(), 324 PP.getSelectorTable(), &propertyName); 325 326 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 327 if (!Setter) { 328 // If this reference is in an @implementation, also check for 'private' 329 // methods. 330 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) 331 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 332 if (ObjCImplementationDecl *ImpDecl 333 = LookupObjCImplementation(ClassDecl->getIdentifier())) 334 Setter = ImpDecl->getClassMethod(SetterSel); 335 } 336 // Look through local category implementations associated with the class. 337 if (!Setter) { 338 for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) { 339 if (ObjCCategoryImpls[i]->getClassInterface() == IFace) 340 Setter = ObjCCategoryImpls[i]->getClassMethod(SetterSel); 341 } 342 } 343 344 if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc)) 345 return ExprError(); 346 347 if (Getter || Setter) { 348 QualType PType; 349 350 if (Getter) 351 PType = Getter->getResultType(); 352 else { 353 for (ObjCMethodDecl::param_iterator PI = Setter->param_begin(), 354 E = Setter->param_end(); PI != E; ++PI) 355 PType = (*PI)->getType(); 356 } 357 return Owned(new (Context) ObjCKVCRefExpr(Getter, PType, Setter, 358 propertyNameLoc, IFace, receiverNameLoc)); 359 } 360 return ExprError(Diag(propertyNameLoc, diag::err_property_not_found) 361 << &propertyName << Context.getObjCInterfaceType(IFace)); 362} 363 364 365// ActOnClassMessage - used for both unary and keyword messages. 366// ArgExprs is optional - if it is present, the number of expressions 367// is obtained from Sel.getNumArgs(). 368Sema::ExprResult Sema::ActOnClassMessage( 369 Scope *S, 370 IdentifierInfo *receiverName, Selector Sel, 371 SourceLocation lbrac, SourceLocation receiverLoc, 372 SourceLocation selectorLoc, SourceLocation rbrac, 373 ExprTy **Args, unsigned NumArgs) 374{ 375 assert(receiverName && "missing receiver class name"); 376 377 Expr **ArgExprs = reinterpret_cast<Expr **>(Args); 378 ObjCInterfaceDecl* ClassDecl = 0; 379 bool isSuper = false; 380 381 if (receiverName->isStr("super")) { 382 if (getCurMethodDecl()) { 383 isSuper = true; 384 ObjCInterfaceDecl *OID = getCurMethodDecl()->getClassInterface(); 385 if (!OID) 386 return Diag(lbrac, diag::error_no_super_class_message) 387 << getCurMethodDecl()->getDeclName(); 388 ClassDecl = OID->getSuperClass(); 389 if (!ClassDecl) 390 return Diag(lbrac, diag::error_no_super_class) << OID->getDeclName(); 391 if (getCurMethodDecl()->isInstanceMethod()) { 392 QualType superTy = Context.getObjCInterfaceType(ClassDecl); 393 superTy = Context.getObjCObjectPointerType(superTy); 394 ExprResult ReceiverExpr = new (Context) ObjCSuperExpr(SourceLocation(), 395 superTy); 396 // We are really in an instance method, redirect. 397 return ActOnInstanceMessage(ReceiverExpr.get(), Sel, lbrac, 398 selectorLoc, rbrac, Args, NumArgs); 399 } 400 // We are sending a message to 'super' within a class method. Do nothing, 401 // the receiver will pass through as 'super' (how convenient:-). 402 } else { 403 // 'super' has been used outside a method context. If a variable named 404 // 'super' has been declared, redirect. If not, produce a diagnostic. 405 NamedDecl *SuperDecl = LookupName(S, receiverName, LookupOrdinaryName); 406 ValueDecl *VD = dyn_cast_or_null<ValueDecl>(SuperDecl); 407 if (VD) { 408 ExprResult ReceiverExpr = new (Context) DeclRefExpr(VD, VD->getType(), 409 receiverLoc); 410 // We are really in an instance method, redirect. 411 return ActOnInstanceMessage(ReceiverExpr.get(), Sel, lbrac, 412 selectorLoc, rbrac, Args, NumArgs); 413 } 414 return Diag(receiverLoc, diag::err_undeclared_var_use) << receiverName; 415 } 416 } else 417 ClassDecl = getObjCInterfaceDecl(receiverName); 418 419 // The following code allows for the following GCC-ism: 420 // 421 // typedef XCElementDisplayRect XCElementGraphicsRect; 422 // 423 // @implementation XCRASlice 424 // - whatever { // Note that XCElementGraphicsRect is a typedef name. 425 // _sGraphicsDelegate =[[XCElementGraphicsRect alloc] init]; 426 // } 427 // 428 // If necessary, the following lookup could move to getObjCInterfaceDecl(). 429 if (!ClassDecl) { 430 NamedDecl *IDecl = LookupName(TUScope, receiverName, LookupOrdinaryName); 431 if (TypedefDecl *OCTD = dyn_cast_or_null<TypedefDecl>(IDecl)) { 432 const ObjCInterfaceType *OCIT; 433 OCIT = OCTD->getUnderlyingType()->getAsObjCInterfaceType(); 434 if (!OCIT) { 435 Diag(receiverLoc, diag::err_invalid_receiver_to_message); 436 return true; 437 } 438 ClassDecl = OCIT->getDecl(); 439 } 440 } 441 assert(ClassDecl && "missing interface declaration"); 442 ObjCMethodDecl *Method = 0; 443 QualType returnType; 444 if (ClassDecl->isForwardDecl()) { 445 // A forward class used in messaging is tread as a 'Class' 446 Diag(lbrac, diag::warn_receiver_forward_class) << ClassDecl->getDeclName(); 447 Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(lbrac,rbrac)); 448 if (Method) 449 Diag(Method->getLocation(), diag::note_method_sent_forward_class) 450 << Method->getDeclName(); 451 } 452 if (!Method) 453 Method = ClassDecl->lookupClassMethod(Sel); 454 455 // If we have an implementation in scope, check "private" methods. 456 if (!Method) 457 Method = LookupPrivateClassMethod(Sel, ClassDecl); 458 459 if (Method && DiagnoseUseOfDecl(Method, receiverLoc)) 460 return true; 461 462 if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, true, 463 lbrac, rbrac, returnType)) 464 return true; 465 466 returnType = returnType.getNonReferenceType(); 467 468 // If we have the ObjCInterfaceDecl* for the class that is receiving the 469 // message, use that to construct the ObjCMessageExpr. Otherwise pass on the 470 // IdentifierInfo* for the class. 471 // FIXME: need to do a better job handling 'super' usage within a class. For 472 // now, we simply pass the "super" identifier through (which isn't consistent 473 // with instance methods. 474 if (isSuper) 475 return new (Context) ObjCMessageExpr(receiverName, Sel, returnType, Method, 476 lbrac, rbrac, ArgExprs, NumArgs); 477 else 478 return new (Context) ObjCMessageExpr(ClassDecl, Sel, returnType, Method, 479 lbrac, rbrac, ArgExprs, NumArgs); 480} 481 482// ActOnInstanceMessage - used for both unary and keyword messages. 483// ArgExprs is optional - if it is present, the number of expressions 484// is obtained from Sel.getNumArgs(). 485Sema::ExprResult Sema::ActOnInstanceMessage(ExprTy *receiver, Selector Sel, 486 SourceLocation lbrac, 487 SourceLocation receiverLoc, 488 SourceLocation rbrac, 489 ExprTy **Args, unsigned NumArgs) { 490 assert(receiver && "missing receiver expression"); 491 492 Expr **ArgExprs = reinterpret_cast<Expr **>(Args); 493 Expr *RExpr = static_cast<Expr *>(receiver); 494 495 // If necessary, apply function/array conversion to the receiver. 496 // C99 6.7.5.3p[7,8]. 497 DefaultFunctionArrayConversion(RExpr); 498 499 QualType returnType; 500 QualType ReceiverCType = 501 Context.getCanonicalType(RExpr->getType()).getUnqualifiedType(); 502 503 // Handle messages to 'super'. 504 if (isa<ObjCSuperExpr>(RExpr)) { 505 ObjCMethodDecl *Method = 0; 506 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { 507 // If we have an interface in scope, check 'super' methods. 508 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) 509 if (ObjCInterfaceDecl *SuperDecl = ClassDecl->getSuperClass()) { 510 Method = SuperDecl->lookupInstanceMethod(Sel); 511 512 if (!Method) 513 // If we have implementations in scope, check "private" methods. 514 Method = LookupPrivateInstanceMethod(Sel, SuperDecl); 515 } 516 } 517 518 if (Method && DiagnoseUseOfDecl(Method, receiverLoc)) 519 return true; 520 521 if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false, 522 lbrac, rbrac, returnType)) 523 return true; 524 525 returnType = returnType.getNonReferenceType(); 526 return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, 527 rbrac, ArgExprs, NumArgs); 528 } 529 530 // Handle messages to id. 531 if (ReceiverCType == Context.getCanonicalType(Context.getObjCIdType()) || 532 ReceiverCType->isBlockPointerType() || 533 Context.isObjCNSObjectType(RExpr->getType())) { 534 ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool( 535 Sel, SourceRange(lbrac,rbrac)); 536 if (!Method) 537 Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(lbrac, rbrac)); 538 if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false, 539 lbrac, rbrac, returnType)) 540 return true; 541 returnType = returnType.getNonReferenceType(); 542 return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, 543 rbrac, ArgExprs, NumArgs); 544 } 545 546 // Handle messages to Class. 547 if (ReceiverCType == Context.getCanonicalType(Context.getObjCClassType())) { 548 ObjCMethodDecl *Method = 0; 549 550 if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { 551 if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) { 552 // First check the public methods in the class interface. 553 Method = ClassDecl->lookupClassMethod(Sel); 554 555 if (!Method) 556 Method = LookupPrivateClassMethod(Sel, ClassDecl); 557 } 558 if (Method && DiagnoseUseOfDecl(Method, receiverLoc)) 559 return true; 560 } 561 if (!Method) { 562 // If not messaging 'self', look for any factory method named 'Sel'. 563 if (!isSelfExpr(RExpr)) { 564 Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(lbrac,rbrac)); 565 if (!Method) { 566 // If no class (factory) method was found, check if an _instance_ 567 // method of the same name exists in the root class only. 568 Method = LookupInstanceMethodInGlobalPool( 569 Sel, SourceRange(lbrac,rbrac)); 570 if (Method) 571 if (const ObjCInterfaceDecl *ID = 572 dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) { 573 if (ID->getSuperClass()) 574 Diag(lbrac, diag::warn_root_inst_method_not_found) 575 << Sel << SourceRange(lbrac, rbrac); 576 } 577 } 578 } 579 } 580 if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false, 581 lbrac, rbrac, returnType)) 582 return true; 583 returnType = returnType.getNonReferenceType(); 584 return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, 585 rbrac, ArgExprs, NumArgs); 586 } 587 588 ObjCMethodDecl *Method = 0; 589 ObjCInterfaceDecl* ClassDecl = 0; 590 591 // We allow sending a message to a qualified ID ("id<foo>"), which is ok as 592 // long as one of the protocols implements the selector (if not, warn). 593 if (const ObjCObjectPointerType *QIdTy = 594 ReceiverCType->getAsObjCQualifiedIdType()) { 595 // Search protocols for instance methods. 596 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 597 E = QIdTy->qual_end(); I != E; ++I) { 598 ObjCProtocolDecl *PDecl = *I; 599 if (PDecl && (Method = PDecl->lookupInstanceMethod(Sel))) 600 break; 601 // Since we aren't supporting "Class<foo>", look for a class method. 602 if (PDecl && (Method = PDecl->lookupClassMethod(Sel))) 603 break; 604 } 605 } else if (const ObjCObjectPointerType *OCIType = 606 ReceiverCType->getAsObjCInterfacePointerType()) { 607 // We allow sending a message to a pointer to an interface (an object). 608 609 ClassDecl = OCIType->getInterfaceDecl(); 610 // FIXME: consider using LookupInstanceMethodInGlobalPool, since it will be 611 // faster than the following method (which can do *many* linear searches). 612 // The idea is to add class info to InstanceMethodPool. 613 Method = ClassDecl->lookupInstanceMethod(Sel); 614 615 if (!Method) { 616 // Search protocol qualifiers. 617 for (ObjCObjectPointerType::qual_iterator QI = OCIType->qual_begin(), 618 E = OCIType->qual_end(); QI != E; ++QI) { 619 if ((Method = (*QI)->lookupInstanceMethod(Sel))) 620 break; 621 } 622 } 623 if (!Method) { 624 // If we have implementations in scope, check "private" methods. 625 Method = LookupPrivateInstanceMethod(Sel, ClassDecl); 626 627 if (!Method && !isSelfExpr(RExpr)) { 628 // If we still haven't found a method, look in the global pool. This 629 // behavior isn't very desirable, however we need it for GCC 630 // compatibility. FIXME: should we deviate?? 631 if (OCIType->qual_empty()) { 632 Method = LookupInstanceMethodInGlobalPool( 633 Sel, SourceRange(lbrac,rbrac)); 634 if (Method && !OCIType->getInterfaceDecl()->isForwardDecl()) 635 Diag(lbrac, diag::warn_maynot_respond) 636 << OCIType->getInterfaceDecl()->getIdentifier()->getName() << Sel; 637 } 638 } 639 } 640 if (Method && DiagnoseUseOfDecl(Method, receiverLoc)) 641 return true; 642 } else if (!Context.getObjCIdType().isNull() && 643 (ReceiverCType->isPointerType() || 644 (ReceiverCType->isIntegerType() && 645 ReceiverCType->isScalarType()))) { 646 // Implicitly convert integers and pointers to 'id' but emit a warning. 647 Diag(lbrac, diag::warn_bad_receiver_type) 648 << RExpr->getType() << RExpr->getSourceRange(); 649 ImpCastExprToType(RExpr, Context.getObjCIdType()); 650 } else { 651 // Reject other random receiver types (e.g. structs). 652 Diag(lbrac, diag::err_bad_receiver_type) 653 << RExpr->getType() << RExpr->getSourceRange(); 654 return true; 655 } 656 657 if (Method) 658 DiagnoseSentinelCalls(Method, receiverLoc, ArgExprs, NumArgs); 659 if (CheckMessageArgumentTypes(ArgExprs, NumArgs, Sel, Method, false, 660 lbrac, rbrac, returnType)) 661 return true; 662 returnType = returnType.getNonReferenceType(); 663 return new (Context) ObjCMessageExpr(RExpr, Sel, returnType, Method, lbrac, 664 rbrac, ArgExprs, NumArgs); 665} 666 667//===----------------------------------------------------------------------===// 668// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 669//===----------------------------------------------------------------------===// 670 671/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 672/// inheritance hierarchy of 'rProto'. 673static bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 674 ObjCProtocolDecl *rProto) { 675 if (lProto == rProto) 676 return true; 677 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(), 678 E = rProto->protocol_end(); PI != E; ++PI) 679 if (ProtocolCompatibleWithProtocol(lProto, *PI)) 680 return true; 681 return false; 682} 683 684/// ClassImplementsProtocol - Checks that 'lProto' protocol 685/// has been implemented in IDecl class, its super class or categories (if 686/// lookupCategory is true). 687static bool ClassImplementsProtocol(ObjCProtocolDecl *lProto, 688 ObjCInterfaceDecl *IDecl, 689 bool lookupCategory, 690 bool RHSIsQualifiedID = false) { 691 692 // 1st, look up the class. 693 const ObjCList<ObjCProtocolDecl> &Protocols = 694 IDecl->getReferencedProtocols(); 695 696 for (ObjCList<ObjCProtocolDecl>::iterator PI = Protocols.begin(), 697 E = Protocols.end(); PI != E; ++PI) { 698 if (ProtocolCompatibleWithProtocol(lProto, *PI)) 699 return true; 700 // This is dubious and is added to be compatible with gcc. In gcc, it is 701 // also allowed assigning a protocol-qualified 'id' type to a LHS object 702 // when protocol in qualified LHS is in list of protocols in the rhs 'id' 703 // object. This IMO, should be a bug. 704 // FIXME: Treat this as an extension, and flag this as an error when GCC 705 // extensions are not enabled. 706 if (RHSIsQualifiedID && ProtocolCompatibleWithProtocol(*PI, lProto)) 707 return true; 708 } 709 710 // 2nd, look up the category. 711 if (lookupCategory) 712 for (ObjCCategoryDecl *CDecl = IDecl->getCategoryList(); CDecl; 713 CDecl = CDecl->getNextClassCategory()) { 714 for (ObjCCategoryDecl::protocol_iterator PI = CDecl->protocol_begin(), 715 E = CDecl->protocol_end(); PI != E; ++PI) 716 if (ProtocolCompatibleWithProtocol(lProto, *PI)) 717 return true; 718 } 719 720 // 3rd, look up the super class(s) 721 if (IDecl->getSuperClass()) 722 return 723 ClassImplementsProtocol(lProto, IDecl->getSuperClass(), lookupCategory, 724 RHSIsQualifiedID); 725 726 return false; 727} 728 729/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...> 730/// return true if lhs's protocols conform to rhs's protocol; false 731/// otherwise. 732bool Sema::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) { 733 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType()) 734 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false); 735 return false; 736} 737 738/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 739/// ObjCQualifiedIDType. 740/// FIXME: Move to ASTContext::typesAreCompatible() and friends. 741bool Sema::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 742 bool compare) { 743 // Allow id<P..> and an 'id' or void* type in all cases. 744 if (lhs->isVoidPointerType() || 745 lhs->isObjCIdType() || lhs->isObjCClassType()) 746 return true; 747 else if (rhs->isVoidPointerType() || 748 rhs->isObjCIdType() || rhs->isObjCClassType()) 749 return true; 750 751 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 752 const ObjCObjectPointerType *rhsOPT = rhs->getAsObjCObjectPointerType(); 753 754 if (!rhsOPT) return false; 755 756 if (rhsOPT->qual_empty()) { 757 // If the RHS is a unqualified interface pointer "NSString*", 758 // make sure we check the class hierarchy. 759 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 760 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 761 E = lhsQID->qual_end(); I != E; ++I) { 762 // when comparing an id<P> on lhs with a static type on rhs, 763 // see if static class implements all of id's protocols, directly or 764 // through its super class and categories. 765 if (!ClassImplementsProtocol(*I, rhsID, true)) 766 return false; 767 } 768 return true; 769 } 770 // If there are no qualifiers and no interface, we have an 'id'. 771 return true; 772 } 773 // Both the right and left sides have qualifiers. 774 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 775 E = lhsQID->qual_end(); I != E; ++I) { 776 ObjCProtocolDecl *lhsProto = *I; 777 bool match = false; 778 779 // when comparing an id<P> on lhs with a static type on rhs, 780 // see if static class implements all of id's protocols, directly or 781 // through its super class and categories. 782 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 783 E = rhsOPT->qual_end(); J != E; ++J) { 784 ObjCProtocolDecl *rhsProto = *J; 785 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 786 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 787 match = true; 788 break; 789 } 790 } 791 // If the RHS is a qualified interface pointer "NSString<P>*", 792 // make sure we check the class hierarchy. 793 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 794 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 795 E = lhsQID->qual_end(); I != E; ++I) { 796 // when comparing an id<P> on lhs with a static type on rhs, 797 // see if static class implements all of id's protocols, directly or 798 // through its super class and categories. 799 if (ClassImplementsProtocol(*I, rhsID, true)) { 800 match = true; 801 break; 802 } 803 } 804 } 805 if (!match) 806 return false; 807 } 808 809 return true; 810 } 811 812 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 813 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 814 815 if (const ObjCObjectPointerType *lhsOPT = 816 lhs->getAsObjCInterfacePointerType()) { 817 if (lhsOPT->qual_empty()) { 818 bool match = false; 819 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 820 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(), 821 E = rhsQID->qual_end(); I != E; ++I) { 822 // when comparing an id<P> on lhs with a static type on rhs, 823 // see if static class implements all of id's protocols, directly or 824 // through its super class and categories. 825 if (ClassImplementsProtocol(*I, lhsID, true)) { 826 match = true; 827 break; 828 } 829 } 830 if (!match) 831 return false; 832 } 833 return true; 834 } 835 // Both the right and left sides have qualifiers. 836 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(), 837 E = lhsOPT->qual_end(); I != E; ++I) { 838 ObjCProtocolDecl *lhsProto = *I; 839 bool match = false; 840 841 // when comparing an id<P> on lhs with a static type on rhs, 842 // see if static class implements all of id's protocols, directly or 843 // through its super class and categories. 844 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 845 E = rhsQID->qual_end(); J != E; ++J) { 846 ObjCProtocolDecl *rhsProto = *J; 847 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 848 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 849 match = true; 850 break; 851 } 852 } 853 if (!match) 854 return false; 855 } 856 return true; 857 } 858 // FIXME: The code below will be removed when ObjCQualifiedInterfaceType is 859 // removed. 860 if (!lhs->isPointerType()) 861 return false; 862 863 QualType ltype = lhs->getAsPointerType()->getPointeeType(); 864 if (const ObjCQualifiedInterfaceType *lhsQI = 865 ltype->getAsObjCQualifiedInterfaceType()) { 866 ObjCObjectPointerType::qual_iterator LHSProtoI = lhsQI->qual_begin(); 867 ObjCObjectPointerType::qual_iterator LHSProtoE = lhsQI->qual_end(); 868 for (; LHSProtoI != LHSProtoE; ++LHSProtoI) { 869 bool match = false; 870 ObjCProtocolDecl *lhsProto = *LHSProtoI; 871 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(), 872 E = rhsQID->qual_end(); I != E; ++I) { 873 ObjCProtocolDecl *rhsProto = *I; 874 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 875 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 876 match = true; 877 break; 878 } 879 } 880 if (!match) 881 return false; 882 } 883 return true; 884 } 885 886 return false; 887} 888 889