SemaDeclObjC.cpp revision 58a764940df0cd41767367eb2f4fced6f374176b
1//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===// 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 declarations. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/Sema/SemaInternal.h" 15#include "clang/Sema/Lookup.h" 16#include "clang/Sema/ExternalSemaSource.h" 17#include "clang/Sema/Scope.h" 18#include "clang/Sema/ScopeInfo.h" 19#include "clang/AST/ASTConsumer.h" 20#include "clang/AST/Expr.h" 21#include "clang/AST/ExprObjC.h" 22#include "clang/AST/ASTContext.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/Basic/SourceManager.h" 25#include "clang/Sema/DeclSpec.h" 26#include "llvm/ADT/DenseSet.h" 27 28using namespace clang; 29 30/// Check whether the given method, which must be in the 'init' 31/// family, is a valid member of that family. 32/// 33/// \param receiverTypeIfCall - if null, check this as if declaring it; 34/// if non-null, check this as if making a call to it with the given 35/// receiver type 36/// 37/// \return true to indicate that there was an error and appropriate 38/// actions were taken 39bool Sema::checkInitMethod(ObjCMethodDecl *method, 40 QualType receiverTypeIfCall) { 41 if (method->isInvalidDecl()) return true; 42 43 // This castAs is safe: methods that don't return an object 44 // pointer won't be inferred as inits and will reject an explicit 45 // objc_method_family(init). 46 47 // We ignore protocols here. Should we? What about Class? 48 49 const ObjCObjectType *result = method->getResultType() 50 ->castAs<ObjCObjectPointerType>()->getObjectType(); 51 52 if (result->isObjCId()) { 53 return false; 54 } else if (result->isObjCClass()) { 55 // fall through: always an error 56 } else { 57 ObjCInterfaceDecl *resultClass = result->getInterface(); 58 assert(resultClass && "unexpected object type!"); 59 60 // It's okay for the result type to still be a forward declaration 61 // if we're checking an interface declaration. 62 if (resultClass->isForwardDecl()) { 63 if (receiverTypeIfCall.isNull() && 64 !isa<ObjCImplementationDecl>(method->getDeclContext())) 65 return false; 66 67 // Otherwise, we try to compare class types. 68 } else { 69 // If this method was declared in a protocol, we can't check 70 // anything unless we have a receiver type that's an interface. 71 const ObjCInterfaceDecl *receiverClass = 0; 72 if (isa<ObjCProtocolDecl>(method->getDeclContext())) { 73 if (receiverTypeIfCall.isNull()) 74 return false; 75 76 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>() 77 ->getInterfaceDecl(); 78 79 // This can be null for calls to e.g. id<Foo>. 80 if (!receiverClass) return false; 81 } else { 82 receiverClass = method->getClassInterface(); 83 assert(receiverClass && "method not associated with a class!"); 84 } 85 86 // If either class is a subclass of the other, it's fine. 87 if (receiverClass->isSuperClassOf(resultClass) || 88 resultClass->isSuperClassOf(receiverClass)) 89 return false; 90 } 91 } 92 93 SourceLocation loc = method->getLocation(); 94 95 // If we're in a system header, and this is not a call, just make 96 // the method unusable. 97 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) { 98 method->addAttr(new (Context) UnavailableAttr(loc, Context, 99 "init method returns a type unrelated to its receiver type")); 100 return true; 101 } 102 103 // Otherwise, it's an error. 104 Diag(loc, diag::err_arc_init_method_unrelated_result_type); 105 method->setInvalidDecl(); 106 return true; 107} 108 109bool Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 110 const ObjCMethodDecl *Overridden, 111 bool IsImplementation) { 112 if (Overridden->hasRelatedResultType() && 113 !NewMethod->hasRelatedResultType()) { 114 // This can only happen when the method follows a naming convention that 115 // implies a related result type, and the original (overridden) method has 116 // a suitable return type, but the new (overriding) method does not have 117 // a suitable return type. 118 QualType ResultType = NewMethod->getResultType(); 119 SourceRange ResultTypeRange; 120 if (const TypeSourceInfo *ResultTypeInfo 121 = NewMethod->getResultTypeSourceInfo()) 122 ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange(); 123 124 // Figure out which class this method is part of, if any. 125 ObjCInterfaceDecl *CurrentClass 126 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext()); 127 if (!CurrentClass) { 128 DeclContext *DC = NewMethod->getDeclContext(); 129 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC)) 130 CurrentClass = Cat->getClassInterface(); 131 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC)) 132 CurrentClass = Impl->getClassInterface(); 133 else if (ObjCCategoryImplDecl *CatImpl 134 = dyn_cast<ObjCCategoryImplDecl>(DC)) 135 CurrentClass = CatImpl->getClassInterface(); 136 } 137 138 if (CurrentClass) { 139 Diag(NewMethod->getLocation(), 140 diag::warn_related_result_type_compatibility_class) 141 << Context.getObjCInterfaceType(CurrentClass) 142 << ResultType 143 << ResultTypeRange; 144 } else { 145 Diag(NewMethod->getLocation(), 146 diag::warn_related_result_type_compatibility_protocol) 147 << ResultType 148 << ResultTypeRange; 149 } 150 151 Diag(Overridden->getLocation(), diag::note_related_result_type_overridden) 152 << Overridden->getMethodFamily(); 153 } 154 155 return false; 156} 157 158/// \brief Check a method declaration for compatibility with the Objective-C 159/// ARC conventions. 160static bool CheckARCMethodDecl(Sema &S, ObjCMethodDecl *method) { 161 ObjCMethodFamily family = method->getMethodFamily(); 162 switch (family) { 163 case OMF_None: 164 case OMF_dealloc: 165 case OMF_retain: 166 case OMF_release: 167 case OMF_autorelease: 168 case OMF_retainCount: 169 case OMF_self: 170 case OMF_performSelector: 171 return false; 172 173 case OMF_init: 174 // If the method doesn't obey the init rules, don't bother annotating it. 175 if (S.checkInitMethod(method, QualType())) 176 return true; 177 178 method->addAttr(new (S.Context) NSConsumesSelfAttr(SourceLocation(), 179 S.Context)); 180 181 // Don't add a second copy of this attribute, but otherwise don't 182 // let it be suppressed. 183 if (method->hasAttr<NSReturnsRetainedAttr>()) 184 return false; 185 break; 186 187 case OMF_alloc: 188 case OMF_copy: 189 case OMF_mutableCopy: 190 case OMF_new: 191 if (method->hasAttr<NSReturnsRetainedAttr>() || 192 method->hasAttr<NSReturnsNotRetainedAttr>() || 193 method->hasAttr<NSReturnsAutoreleasedAttr>()) 194 return false; 195 break; 196 } 197 198 method->addAttr(new (S.Context) NSReturnsRetainedAttr(SourceLocation(), 199 S.Context)); 200 return false; 201} 202 203static void DiagnoseObjCImplementedDeprecations(Sema &S, 204 NamedDecl *ND, 205 SourceLocation ImplLoc, 206 int select) { 207 if (ND && ND->isDeprecated()) { 208 S.Diag(ImplLoc, diag::warn_deprecated_def) << select; 209 if (select == 0) 210 S.Diag(ND->getLocation(), diag::note_method_declared_at); 211 else 212 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class"; 213 } 214} 215 216/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible 217/// and user declared, in the method definition's AST. 218void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { 219 assert(getCurMethodDecl() == 0 && "Method parsing confused"); 220 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 221 222 // If we don't have a valid method decl, simply return. 223 if (!MDecl) 224 return; 225 226 // Allow the rest of sema to find private method decl implementations. 227 if (MDecl->isInstanceMethod()) 228 AddInstanceMethodToGlobalPool(MDecl, true); 229 else 230 AddFactoryMethodToGlobalPool(MDecl, true); 231 232 // Allow all of Sema to see that we are entering a method definition. 233 PushDeclContext(FnBodyScope, MDecl); 234 PushFunctionScope(); 235 236 // Create Decl objects for each parameter, entrring them in the scope for 237 // binding to their use. 238 239 // Insert the invisible arguments, self and _cmd! 240 MDecl->createImplicitParams(Context, MDecl->getClassInterface()); 241 242 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope); 243 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope); 244 245 // Introduce all of the other parameters into this scope. 246 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(), 247 E = MDecl->param_end(); PI != E; ++PI) { 248 ParmVarDecl *Param = (*PI); 249 if (!Param->isInvalidDecl() && 250 RequireCompleteType(Param->getLocation(), Param->getType(), 251 diag::err_typecheck_decl_incomplete_type)) 252 Param->setInvalidDecl(); 253 if ((*PI)->getIdentifier()) 254 PushOnScopeChains(*PI, FnBodyScope); 255 } 256 257 // In ARC, disallow definition of retain/release/autorelease/retainCount 258 if (getLangOptions().ObjCAutoRefCount) { 259 switch (MDecl->getMethodFamily()) { 260 case OMF_retain: 261 case OMF_retainCount: 262 case OMF_release: 263 case OMF_autorelease: 264 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def) 265 << MDecl->getSelector(); 266 break; 267 268 case OMF_None: 269 case OMF_dealloc: 270 case OMF_alloc: 271 case OMF_init: 272 case OMF_mutableCopy: 273 case OMF_copy: 274 case OMF_new: 275 case OMF_self: 276 case OMF_performSelector: 277 break; 278 } 279 } 280 281 // Warn on deprecated methods under -Wdeprecated-implementations, 282 // and prepare for warning on missing super calls. 283 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) { 284 if (ObjCMethodDecl *IMD = 285 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod())) 286 DiagnoseObjCImplementedDeprecations(*this, 287 dyn_cast<NamedDecl>(IMD), 288 MDecl->getLocation(), 0); 289 290 // If this is "dealloc", set some bit here. 291 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false. 292 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set. 293 // Only do this if the current class actually has a superclass. 294 if (IC->getSuperClass()) 295 ObjCShouldCallSuperDealloc = MDecl->getMethodFamily() == OMF_dealloc; 296 } 297} 298 299Decl *Sema:: 300ActOnStartClassInterface(SourceLocation AtInterfaceLoc, 301 IdentifierInfo *ClassName, SourceLocation ClassLoc, 302 IdentifierInfo *SuperName, SourceLocation SuperLoc, 303 Decl * const *ProtoRefs, unsigned NumProtoRefs, 304 const SourceLocation *ProtoLocs, 305 SourceLocation EndProtoLoc, AttributeList *AttrList) { 306 assert(ClassName && "Missing class identifier"); 307 308 // Check for another declaration kind with the same name. 309 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc, 310 LookupOrdinaryName, ForRedeclaration); 311 312 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 313 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 314 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 315 } 316 317 ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 318 if (IDecl) { 319 // Class already seen. Is it a forward declaration? 320 if (!IDecl->isForwardDecl()) { 321 IDecl->setInvalidDecl(); 322 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName(); 323 Diag(IDecl->getLocation(), diag::note_previous_definition); 324 325 // Return the previous class interface. 326 // FIXME: don't leak the objects passed in! 327 return IDecl; 328 } else { 329 IDecl->setLocation(AtInterfaceLoc); 330 IDecl->setForwardDecl(false); 331 IDecl->setClassLoc(ClassLoc); 332 // If the forward decl was in a PCH, we need to write it again in a 333 // dependent AST file. 334 IDecl->setChangedSinceDeserialization(true); 335 336 // Since this ObjCInterfaceDecl was created by a forward declaration, 337 // we now add it to the DeclContext since it wasn't added before 338 // (see ActOnForwardClassDeclaration). 339 IDecl->setLexicalDeclContext(CurContext); 340 CurContext->addDecl(IDecl); 341 342 if (AttrList) 343 ProcessDeclAttributeList(TUScope, IDecl, AttrList); 344 } 345 } else { 346 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, 347 ClassName, ClassLoc); 348 if (AttrList) 349 ProcessDeclAttributeList(TUScope, IDecl, AttrList); 350 351 PushOnScopeChains(IDecl, TUScope); 352 } 353 354 if (SuperName) { 355 // Check if a different kind of symbol declared in this scope. 356 PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc, 357 LookupOrdinaryName); 358 359 if (!PrevDecl) { 360 // Try to correct for a typo in the superclass name. 361 TypoCorrection Corrected = CorrectTypo( 362 DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope, 363 NULL, NULL, false, CTC_NoKeywords); 364 if ((PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>())) { 365 Diag(SuperLoc, diag::err_undef_superclass_suggest) 366 << SuperName << ClassName << PrevDecl->getDeclName(); 367 Diag(PrevDecl->getLocation(), diag::note_previous_decl) 368 << PrevDecl->getDeclName(); 369 } 370 } 371 372 if (PrevDecl == IDecl) { 373 Diag(SuperLoc, diag::err_recursive_superclass) 374 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 375 IDecl->setLocEnd(ClassLoc); 376 } else { 377 ObjCInterfaceDecl *SuperClassDecl = 378 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 379 380 // Diagnose classes that inherit from deprecated classes. 381 if (SuperClassDecl) 382 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc); 383 384 if (PrevDecl && SuperClassDecl == 0) { 385 // The previous declaration was not a class decl. Check if we have a 386 // typedef. If we do, get the underlying class type. 387 if (const TypedefNameDecl *TDecl = 388 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 389 QualType T = TDecl->getUnderlyingType(); 390 if (T->isObjCObjectType()) { 391 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) 392 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl); 393 } 394 } 395 396 // This handles the following case: 397 // 398 // typedef int SuperClass; 399 // @interface MyClass : SuperClass {} @end 400 // 401 if (!SuperClassDecl) { 402 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName; 403 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 404 } 405 } 406 407 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 408 if (!SuperClassDecl) 409 Diag(SuperLoc, diag::err_undef_superclass) 410 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 411 else if (SuperClassDecl->isForwardDecl()) { 412 Diag(SuperLoc, diag::err_forward_superclass) 413 << SuperClassDecl->getDeclName() << ClassName 414 << SourceRange(AtInterfaceLoc, ClassLoc); 415 Diag(SuperClassDecl->getLocation(), diag::note_forward_class); 416 SuperClassDecl = 0; 417 } 418 } 419 IDecl->setSuperClass(SuperClassDecl); 420 IDecl->setSuperClassLoc(SuperLoc); 421 IDecl->setLocEnd(SuperLoc); 422 } 423 } else { // we have a root class. 424 IDecl->setLocEnd(ClassLoc); 425 } 426 427 // Check then save referenced protocols. 428 if (NumProtoRefs) { 429 IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs, 430 ProtoLocs, Context); 431 IDecl->setLocEnd(EndProtoLoc); 432 } 433 434 CheckObjCDeclScope(IDecl); 435 return IDecl; 436} 437 438/// ActOnCompatiblityAlias - this action is called after complete parsing of 439/// @compatibility_alias declaration. It sets up the alias relationships. 440Decl *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc, 441 IdentifierInfo *AliasName, 442 SourceLocation AliasLocation, 443 IdentifierInfo *ClassName, 444 SourceLocation ClassLocation) { 445 // Look for previous declaration of alias name 446 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation, 447 LookupOrdinaryName, ForRedeclaration); 448 if (ADecl) { 449 if (isa<ObjCCompatibleAliasDecl>(ADecl)) 450 Diag(AliasLocation, diag::warn_previous_alias_decl); 451 else 452 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName; 453 Diag(ADecl->getLocation(), diag::note_previous_declaration); 454 return 0; 455 } 456 // Check for class declaration 457 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation, 458 LookupOrdinaryName, ForRedeclaration); 459 if (const TypedefNameDecl *TDecl = 460 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) { 461 QualType T = TDecl->getUnderlyingType(); 462 if (T->isObjCObjectType()) { 463 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) { 464 ClassName = IDecl->getIdentifier(); 465 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation, 466 LookupOrdinaryName, ForRedeclaration); 467 } 468 } 469 } 470 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU); 471 if (CDecl == 0) { 472 Diag(ClassLocation, diag::warn_undef_interface) << ClassName; 473 if (CDeclU) 474 Diag(CDeclU->getLocation(), diag::note_previous_declaration); 475 return 0; 476 } 477 478 // Everything checked out, instantiate a new alias declaration AST. 479 ObjCCompatibleAliasDecl *AliasDecl = 480 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl); 481 482 if (!CheckObjCDeclScope(AliasDecl)) 483 PushOnScopeChains(AliasDecl, TUScope); 484 485 return AliasDecl; 486} 487 488bool Sema::CheckForwardProtocolDeclarationForCircularDependency( 489 IdentifierInfo *PName, 490 SourceLocation &Ploc, SourceLocation PrevLoc, 491 const ObjCList<ObjCProtocolDecl> &PList) { 492 493 bool res = false; 494 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(), 495 E = PList.end(); I != E; ++I) { 496 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(), 497 Ploc)) { 498 if (PDecl->getIdentifier() == PName) { 499 Diag(Ploc, diag::err_protocol_has_circular_dependency); 500 Diag(PrevLoc, diag::note_previous_definition); 501 res = true; 502 } 503 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc, 504 PDecl->getLocation(), PDecl->getReferencedProtocols())) 505 res = true; 506 } 507 } 508 return res; 509} 510 511Decl * 512Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc, 513 IdentifierInfo *ProtocolName, 514 SourceLocation ProtocolLoc, 515 Decl * const *ProtoRefs, 516 unsigned NumProtoRefs, 517 const SourceLocation *ProtoLocs, 518 SourceLocation EndProtoLoc, 519 AttributeList *AttrList) { 520 bool err = false; 521 // FIXME: Deal with AttrList. 522 assert(ProtocolName && "Missing protocol identifier"); 523 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolName, ProtocolLoc); 524 if (PDecl) { 525 // Protocol already seen. Better be a forward protocol declaration 526 if (!PDecl->isForwardDecl()) { 527 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName; 528 Diag(PDecl->getLocation(), diag::note_previous_definition); 529 // Just return the protocol we already had. 530 // FIXME: don't leak the objects passed in! 531 return PDecl; 532 } 533 ObjCList<ObjCProtocolDecl> PList; 534 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context); 535 err = CheckForwardProtocolDeclarationForCircularDependency( 536 ProtocolName, ProtocolLoc, PDecl->getLocation(), PList); 537 538 // Make sure the cached decl gets a valid start location. 539 PDecl->setLocation(AtProtoInterfaceLoc); 540 PDecl->setForwardDecl(false); 541 CurContext->addDecl(PDecl); 542 // Repeat in dependent AST files. 543 PDecl->setChangedSinceDeserialization(true); 544 } else { 545 PDecl = ObjCProtocolDecl::Create(Context, CurContext, 546 AtProtoInterfaceLoc,ProtocolName); 547 PushOnScopeChains(PDecl, TUScope); 548 PDecl->setForwardDecl(false); 549 } 550 if (AttrList) 551 ProcessDeclAttributeList(TUScope, PDecl, AttrList); 552 if (!err && NumProtoRefs ) { 553 /// Check then save referenced protocols. 554 PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs, 555 ProtoLocs, Context); 556 PDecl->setLocEnd(EndProtoLoc); 557 } 558 559 CheckObjCDeclScope(PDecl); 560 return PDecl; 561} 562 563/// FindProtocolDeclaration - This routine looks up protocols and 564/// issues an error if they are not declared. It returns list of 565/// protocol declarations in its 'Protocols' argument. 566void 567Sema::FindProtocolDeclaration(bool WarnOnDeclarations, 568 const IdentifierLocPair *ProtocolId, 569 unsigned NumProtocols, 570 SmallVectorImpl<Decl *> &Protocols) { 571 for (unsigned i = 0; i != NumProtocols; ++i) { 572 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first, 573 ProtocolId[i].second); 574 if (!PDecl) { 575 TypoCorrection Corrected = CorrectTypo( 576 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second), 577 LookupObjCProtocolName, TUScope, NULL, NULL, false, CTC_NoKeywords); 578 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) { 579 Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest) 580 << ProtocolId[i].first << Corrected.getCorrection(); 581 Diag(PDecl->getLocation(), diag::note_previous_decl) 582 << PDecl->getDeclName(); 583 } 584 } 585 586 if (!PDecl) { 587 Diag(ProtocolId[i].second, diag::err_undeclared_protocol) 588 << ProtocolId[i].first; 589 continue; 590 } 591 592 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second); 593 594 // If this is a forward declaration and we are supposed to warn in this 595 // case, do it. 596 if (WarnOnDeclarations && PDecl->isForwardDecl()) 597 Diag(ProtocolId[i].second, diag::warn_undef_protocolref) 598 << ProtocolId[i].first; 599 Protocols.push_back(PDecl); 600 } 601} 602 603/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of 604/// a class method in its extension. 605/// 606void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 607 ObjCInterfaceDecl *ID) { 608 if (!ID) 609 return; // Possibly due to previous error 610 611 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap; 612 for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(), 613 e = ID->meth_end(); i != e; ++i) { 614 ObjCMethodDecl *MD = *i; 615 MethodMap[MD->getSelector()] = MD; 616 } 617 618 if (MethodMap.empty()) 619 return; 620 for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(), 621 e = CAT->meth_end(); i != e; ++i) { 622 ObjCMethodDecl *Method = *i; 623 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()]; 624 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) { 625 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 626 << Method->getDeclName(); 627 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 628 } 629 } 630} 631 632/// ActOnForwardProtocolDeclaration - Handle @protocol foo; 633Decl * 634Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc, 635 const IdentifierLocPair *IdentList, 636 unsigned NumElts, 637 AttributeList *attrList) { 638 SmallVector<ObjCProtocolDecl*, 32> Protocols; 639 SmallVector<SourceLocation, 8> ProtoLocs; 640 641 for (unsigned i = 0; i != NumElts; ++i) { 642 IdentifierInfo *Ident = IdentList[i].first; 643 ObjCProtocolDecl *PDecl = LookupProtocol(Ident, IdentList[i].second); 644 bool isNew = false; 645 if (PDecl == 0) { // Not already seen? 646 PDecl = ObjCProtocolDecl::Create(Context, CurContext, 647 IdentList[i].second, Ident); 648 PushOnScopeChains(PDecl, TUScope, false); 649 isNew = true; 650 } 651 if (attrList) { 652 ProcessDeclAttributeList(TUScope, PDecl, attrList); 653 if (!isNew) 654 PDecl->setChangedSinceDeserialization(true); 655 } 656 Protocols.push_back(PDecl); 657 ProtoLocs.push_back(IdentList[i].second); 658 } 659 660 ObjCForwardProtocolDecl *PDecl = 661 ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc, 662 Protocols.data(), Protocols.size(), 663 ProtoLocs.data()); 664 CurContext->addDecl(PDecl); 665 CheckObjCDeclScope(PDecl); 666 return PDecl; 667} 668 669Decl *Sema:: 670ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 671 IdentifierInfo *ClassName, SourceLocation ClassLoc, 672 IdentifierInfo *CategoryName, 673 SourceLocation CategoryLoc, 674 Decl * const *ProtoRefs, 675 unsigned NumProtoRefs, 676 const SourceLocation *ProtoLocs, 677 SourceLocation EndProtoLoc) { 678 ObjCCategoryDecl *CDecl; 679 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 680 681 /// Check that class of this category is already completely declared. 682 if (!IDecl || IDecl->isForwardDecl()) { 683 // Create an invalid ObjCCategoryDecl to serve as context for 684 // the enclosing method declarations. We mark the decl invalid 685 // to make it clear that this isn't a valid AST. 686 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 687 ClassLoc, CategoryLoc, CategoryName); 688 CDecl->setInvalidDecl(); 689 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 690 return CDecl; 691 } 692 693 if (!CategoryName && IDecl->getImplementation()) { 694 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName; 695 Diag(IDecl->getImplementation()->getLocation(), 696 diag::note_implementation_declared); 697 } 698 699 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 700 ClassLoc, CategoryLoc, CategoryName); 701 // FIXME: PushOnScopeChains? 702 CurContext->addDecl(CDecl); 703 704 CDecl->setClassInterface(IDecl); 705 // Insert class extension to the list of class's categories. 706 if (!CategoryName) 707 CDecl->insertNextClassCategory(); 708 709 // If the interface is deprecated, warn about it. 710 (void)DiagnoseUseOfDecl(IDecl, ClassLoc); 711 712 if (CategoryName) { 713 /// Check for duplicate interface declaration for this category 714 ObjCCategoryDecl *CDeclChain; 715 for (CDeclChain = IDecl->getCategoryList(); CDeclChain; 716 CDeclChain = CDeclChain->getNextClassCategory()) { 717 if (CDeclChain->getIdentifier() == CategoryName) { 718 // Class extensions can be declared multiple times. 719 Diag(CategoryLoc, diag::warn_dup_category_def) 720 << ClassName << CategoryName; 721 Diag(CDeclChain->getLocation(), diag::note_previous_definition); 722 break; 723 } 724 } 725 if (!CDeclChain) 726 CDecl->insertNextClassCategory(); 727 } 728 729 if (NumProtoRefs) { 730 CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs, 731 ProtoLocs, Context); 732 // Protocols in the class extension belong to the class. 733 if (CDecl->IsClassExtension()) 734 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs, 735 NumProtoRefs, Context); 736 } 737 738 CheckObjCDeclScope(CDecl); 739 return CDecl; 740} 741 742/// ActOnStartCategoryImplementation - Perform semantic checks on the 743/// category implementation declaration and build an ObjCCategoryImplDecl 744/// object. 745Decl *Sema::ActOnStartCategoryImplementation( 746 SourceLocation AtCatImplLoc, 747 IdentifierInfo *ClassName, SourceLocation ClassLoc, 748 IdentifierInfo *CatName, SourceLocation CatLoc) { 749 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 750 ObjCCategoryDecl *CatIDecl = 0; 751 if (IDecl) { 752 CatIDecl = IDecl->FindCategoryDeclaration(CatName); 753 if (!CatIDecl) { 754 // Category @implementation with no corresponding @interface. 755 // Create and install one. 756 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, SourceLocation(), 757 SourceLocation(), SourceLocation(), 758 CatName); 759 CatIDecl->setClassInterface(IDecl); 760 CatIDecl->insertNextClassCategory(); 761 } 762 } 763 764 ObjCCategoryImplDecl *CDecl = 765 ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName, 766 IDecl); 767 /// Check that class of this category is already completely declared. 768 if (!IDecl || IDecl->isForwardDecl()) { 769 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 770 CDecl->setInvalidDecl(); 771 } 772 773 // FIXME: PushOnScopeChains? 774 CurContext->addDecl(CDecl); 775 776 /// Check that CatName, category name, is not used in another implementation. 777 if (CatIDecl) { 778 if (CatIDecl->getImplementation()) { 779 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName 780 << CatName; 781 Diag(CatIDecl->getImplementation()->getLocation(), 782 diag::note_previous_definition); 783 } else { 784 CatIDecl->setImplementation(CDecl); 785 // Warn on implementating category of deprecated class under 786 // -Wdeprecated-implementations flag. 787 DiagnoseObjCImplementedDeprecations(*this, 788 dyn_cast<NamedDecl>(IDecl), 789 CDecl->getLocation(), 2); 790 } 791 } 792 793 CheckObjCDeclScope(CDecl); 794 return CDecl; 795} 796 797Decl *Sema::ActOnStartClassImplementation( 798 SourceLocation AtClassImplLoc, 799 IdentifierInfo *ClassName, SourceLocation ClassLoc, 800 IdentifierInfo *SuperClassname, 801 SourceLocation SuperClassLoc) { 802 ObjCInterfaceDecl* IDecl = 0; 803 // Check for another declaration kind with the same name. 804 NamedDecl *PrevDecl 805 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName, 806 ForRedeclaration); 807 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 808 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 809 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 810 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) { 811 // If this is a forward declaration of an interface, warn. 812 if (IDecl->isForwardDecl()) { 813 Diag(ClassLoc, diag::warn_undef_interface) << ClassName; 814 IDecl = 0; 815 } 816 } else { 817 // We did not find anything with the name ClassName; try to correct for 818 // typos in the class name. 819 TypoCorrection Corrected = CorrectTypo( 820 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope, 821 NULL, NULL, false, CTC_NoKeywords); 822 if ((IDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>())) { 823 // Suggest the (potentially) correct interface name. However, put the 824 // fix-it hint itself in a separate note, since changing the name in 825 // the warning would make the fix-it change semantics.However, don't 826 // provide a code-modification hint or use the typo name for recovery, 827 // because this is just a warning. The program may actually be correct. 828 DeclarationName CorrectedName = Corrected.getCorrection(); 829 Diag(ClassLoc, diag::warn_undef_interface_suggest) 830 << ClassName << CorrectedName; 831 Diag(IDecl->getLocation(), diag::note_previous_decl) << CorrectedName 832 << FixItHint::CreateReplacement(ClassLoc, CorrectedName.getAsString()); 833 IDecl = 0; 834 } else { 835 Diag(ClassLoc, diag::warn_undef_interface) << ClassName; 836 } 837 } 838 839 // Check that super class name is valid class name 840 ObjCInterfaceDecl* SDecl = 0; 841 if (SuperClassname) { 842 // Check if a different kind of symbol declared in this scope. 843 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc, 844 LookupOrdinaryName); 845 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 846 Diag(SuperClassLoc, diag::err_redefinition_different_kind) 847 << SuperClassname; 848 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 849 } else { 850 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 851 if (!SDecl) 852 Diag(SuperClassLoc, diag::err_undef_superclass) 853 << SuperClassname << ClassName; 854 else if (IDecl && IDecl->getSuperClass() != SDecl) { 855 // This implementation and its interface do not have the same 856 // super class. 857 Diag(SuperClassLoc, diag::err_conflicting_super_class) 858 << SDecl->getDeclName(); 859 Diag(SDecl->getLocation(), diag::note_previous_definition); 860 } 861 } 862 } 863 864 if (!IDecl) { 865 // Legacy case of @implementation with no corresponding @interface. 866 // Build, chain & install the interface decl into the identifier. 867 868 // FIXME: Do we support attributes on the @implementation? If so we should 869 // copy them over. 870 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc, 871 ClassName, ClassLoc, false, true); 872 IDecl->setSuperClass(SDecl); 873 IDecl->setLocEnd(ClassLoc); 874 875 PushOnScopeChains(IDecl, TUScope); 876 } else { 877 // Mark the interface as being completed, even if it was just as 878 // @class ....; 879 // declaration; the user cannot reopen it. 880 IDecl->setForwardDecl(false); 881 } 882 883 ObjCImplementationDecl* IMPDecl = 884 ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc, 885 IDecl, SDecl); 886 887 if (CheckObjCDeclScope(IMPDecl)) 888 return IMPDecl; 889 890 // Check that there is no duplicate implementation of this class. 891 if (IDecl->getImplementation()) { 892 // FIXME: Don't leak everything! 893 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName; 894 Diag(IDecl->getImplementation()->getLocation(), 895 diag::note_previous_definition); 896 } else { // add it to the list. 897 IDecl->setImplementation(IMPDecl); 898 PushOnScopeChains(IMPDecl, TUScope); 899 // Warn on implementating deprecated class under 900 // -Wdeprecated-implementations flag. 901 DiagnoseObjCImplementedDeprecations(*this, 902 dyn_cast<NamedDecl>(IDecl), 903 IMPDecl->getLocation(), 1); 904 } 905 return IMPDecl; 906} 907 908void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 909 ObjCIvarDecl **ivars, unsigned numIvars, 910 SourceLocation RBrace) { 911 assert(ImpDecl && "missing implementation decl"); 912 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface(); 913 if (!IDecl) 914 return; 915 /// Check case of non-existing @interface decl. 916 /// (legacy objective-c @implementation decl without an @interface decl). 917 /// Add implementations's ivar to the synthesize class's ivar list. 918 if (IDecl->isImplicitInterfaceDecl()) { 919 IDecl->setLocEnd(RBrace); 920 // Add ivar's to class's DeclContext. 921 for (unsigned i = 0, e = numIvars; i != e; ++i) { 922 ivars[i]->setLexicalDeclContext(ImpDecl); 923 IDecl->makeDeclVisibleInContext(ivars[i], false); 924 ImpDecl->addDecl(ivars[i]); 925 } 926 927 return; 928 } 929 // If implementation has empty ivar list, just return. 930 if (numIvars == 0) 931 return; 932 933 assert(ivars && "missing @implementation ivars"); 934 if (LangOpts.ObjCNonFragileABI2) { 935 if (ImpDecl->getSuperClass()) 936 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use); 937 for (unsigned i = 0; i < numIvars; i++) { 938 ObjCIvarDecl* ImplIvar = ivars[i]; 939 if (const ObjCIvarDecl *ClsIvar = 940 IDecl->getIvarDecl(ImplIvar->getIdentifier())) { 941 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 942 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 943 continue; 944 } 945 // Instance ivar to Implementation's DeclContext. 946 ImplIvar->setLexicalDeclContext(ImpDecl); 947 IDecl->makeDeclVisibleInContext(ImplIvar, false); 948 ImpDecl->addDecl(ImplIvar); 949 } 950 return; 951 } 952 // Check interface's Ivar list against those in the implementation. 953 // names and types must match. 954 // 955 unsigned j = 0; 956 ObjCInterfaceDecl::ivar_iterator 957 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end(); 958 for (; numIvars > 0 && IVI != IVE; ++IVI) { 959 ObjCIvarDecl* ImplIvar = ivars[j++]; 960 ObjCIvarDecl* ClsIvar = *IVI; 961 assert (ImplIvar && "missing implementation ivar"); 962 assert (ClsIvar && "missing class ivar"); 963 964 // First, make sure the types match. 965 if (Context.getCanonicalType(ImplIvar->getType()) != 966 Context.getCanonicalType(ClsIvar->getType())) { 967 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type) 968 << ImplIvar->getIdentifier() 969 << ImplIvar->getType() << ClsIvar->getType(); 970 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 971 } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) { 972 Expr *ImplBitWidth = ImplIvar->getBitWidth(); 973 Expr *ClsBitWidth = ClsIvar->getBitWidth(); 974 if (ImplBitWidth->EvaluateAsInt(Context).getZExtValue() != 975 ClsBitWidth->EvaluateAsInt(Context).getZExtValue()) { 976 Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth) 977 << ImplIvar->getIdentifier(); 978 Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition); 979 } 980 } 981 // Make sure the names are identical. 982 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) { 983 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name) 984 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier(); 985 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 986 } 987 --numIvars; 988 } 989 990 if (numIvars > 0) 991 Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count); 992 else if (IVI != IVE) 993 Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count); 994} 995 996void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method, 997 bool &IncompleteImpl, unsigned DiagID) { 998 // No point warning no definition of method which is 'unavailable'. 999 if (method->hasAttr<UnavailableAttr>()) 1000 return; 1001 if (!IncompleteImpl) { 1002 Diag(ImpLoc, diag::warn_incomplete_impl); 1003 IncompleteImpl = true; 1004 } 1005 if (DiagID == diag::warn_unimplemented_protocol_method) 1006 Diag(ImpLoc, DiagID) << method->getDeclName(); 1007 else 1008 Diag(method->getLocation(), DiagID) << method->getDeclName(); 1009} 1010 1011/// Determines if type B can be substituted for type A. Returns true if we can 1012/// guarantee that anything that the user will do to an object of type A can 1013/// also be done to an object of type B. This is trivially true if the two 1014/// types are the same, or if B is a subclass of A. It becomes more complex 1015/// in cases where protocols are involved. 1016/// 1017/// Object types in Objective-C describe the minimum requirements for an 1018/// object, rather than providing a complete description of a type. For 1019/// example, if A is a subclass of B, then B* may refer to an instance of A. 1020/// The principle of substitutability means that we may use an instance of A 1021/// anywhere that we may use an instance of B - it will implement all of the 1022/// ivars of B and all of the methods of B. 1023/// 1024/// This substitutability is important when type checking methods, because 1025/// the implementation may have stricter type definitions than the interface. 1026/// The interface specifies minimum requirements, but the implementation may 1027/// have more accurate ones. For example, a method may privately accept 1028/// instances of B, but only publish that it accepts instances of A. Any 1029/// object passed to it will be type checked against B, and so will implicitly 1030/// by a valid A*. Similarly, a method may return a subclass of the class that 1031/// it is declared as returning. 1032/// 1033/// This is most important when considering subclassing. A method in a 1034/// subclass must accept any object as an argument that its superclass's 1035/// implementation accepts. It may, however, accept a more general type 1036/// without breaking substitutability (i.e. you can still use the subclass 1037/// anywhere that you can use the superclass, but not vice versa). The 1038/// converse requirement applies to return types: the return type for a 1039/// subclass method must be a valid object of the kind that the superclass 1040/// advertises, but it may be specified more accurately. This avoids the need 1041/// for explicit down-casting by callers. 1042/// 1043/// Note: This is a stricter requirement than for assignment. 1044static bool isObjCTypeSubstitutable(ASTContext &Context, 1045 const ObjCObjectPointerType *A, 1046 const ObjCObjectPointerType *B, 1047 bool rejectId) { 1048 // Reject a protocol-unqualified id. 1049 if (rejectId && B->isObjCIdType()) return false; 1050 1051 // If B is a qualified id, then A must also be a qualified id and it must 1052 // implement all of the protocols in B. It may not be a qualified class. 1053 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a 1054 // stricter definition so it is not substitutable for id<A>. 1055 if (B->isObjCQualifiedIdType()) { 1056 return A->isObjCQualifiedIdType() && 1057 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0), 1058 QualType(B,0), 1059 false); 1060 } 1061 1062 /* 1063 // id is a special type that bypasses type checking completely. We want a 1064 // warning when it is used in one place but not another. 1065 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false; 1066 1067 1068 // If B is a qualified id, then A must also be a qualified id (which it isn't 1069 // if we've got this far) 1070 if (B->isObjCQualifiedIdType()) return false; 1071 */ 1072 1073 // Now we know that A and B are (potentially-qualified) class types. The 1074 // normal rules for assignment apply. 1075 return Context.canAssignObjCInterfaces(A, B); 1076} 1077 1078static SourceRange getTypeRange(TypeSourceInfo *TSI) { 1079 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange()); 1080} 1081 1082static bool CheckMethodOverrideReturn(Sema &S, 1083 ObjCMethodDecl *MethodImpl, 1084 ObjCMethodDecl *MethodDecl, 1085 bool IsProtocolMethodDecl, 1086 bool IsOverridingMode, 1087 bool Warn) { 1088 if (IsProtocolMethodDecl && 1089 (MethodDecl->getObjCDeclQualifier() != 1090 MethodImpl->getObjCDeclQualifier())) { 1091 if (Warn) { 1092 S.Diag(MethodImpl->getLocation(), 1093 (IsOverridingMode ? 1094 diag::warn_conflicting_overriding_ret_type_modifiers 1095 : diag::warn_conflicting_ret_type_modifiers)) 1096 << MethodImpl->getDeclName() 1097 << getTypeRange(MethodImpl->getResultTypeSourceInfo()); 1098 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration) 1099 << getTypeRange(MethodDecl->getResultTypeSourceInfo()); 1100 } 1101 else 1102 return false; 1103 } 1104 1105 if (S.Context.hasSameUnqualifiedType(MethodImpl->getResultType(), 1106 MethodDecl->getResultType())) 1107 return true; 1108 if (!Warn) 1109 return false; 1110 1111 unsigned DiagID = 1112 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types 1113 : diag::warn_conflicting_ret_types; 1114 1115 // Mismatches between ObjC pointers go into a different warning 1116 // category, and sometimes they're even completely whitelisted. 1117 if (const ObjCObjectPointerType *ImplPtrTy = 1118 MethodImpl->getResultType()->getAs<ObjCObjectPointerType>()) { 1119 if (const ObjCObjectPointerType *IfacePtrTy = 1120 MethodDecl->getResultType()->getAs<ObjCObjectPointerType>()) { 1121 // Allow non-matching return types as long as they don't violate 1122 // the principle of substitutability. Specifically, we permit 1123 // return types that are subclasses of the declared return type, 1124 // or that are more-qualified versions of the declared type. 1125 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false)) 1126 return false; 1127 1128 DiagID = 1129 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types 1130 : diag::warn_non_covariant_ret_types; 1131 } 1132 } 1133 1134 S.Diag(MethodImpl->getLocation(), DiagID) 1135 << MethodImpl->getDeclName() 1136 << MethodDecl->getResultType() 1137 << MethodImpl->getResultType() 1138 << getTypeRange(MethodImpl->getResultTypeSourceInfo()); 1139 S.Diag(MethodDecl->getLocation(), 1140 IsOverridingMode ? diag::note_previous_declaration 1141 : diag::note_previous_definition) 1142 << getTypeRange(MethodDecl->getResultTypeSourceInfo()); 1143 return false; 1144} 1145 1146static bool CheckMethodOverrideParam(Sema &S, 1147 ObjCMethodDecl *MethodImpl, 1148 ObjCMethodDecl *MethodDecl, 1149 ParmVarDecl *ImplVar, 1150 ParmVarDecl *IfaceVar, 1151 bool IsProtocolMethodDecl, 1152 bool IsOverridingMode, 1153 bool Warn) { 1154 if (IsProtocolMethodDecl && 1155 (ImplVar->getObjCDeclQualifier() != 1156 IfaceVar->getObjCDeclQualifier())) { 1157 if (Warn) { 1158 if (IsOverridingMode) 1159 S.Diag(ImplVar->getLocation(), 1160 diag::warn_conflicting_overriding_param_modifiers) 1161 << getTypeRange(ImplVar->getTypeSourceInfo()) 1162 << MethodImpl->getDeclName(); 1163 else S.Diag(ImplVar->getLocation(), 1164 diag::warn_conflicting_param_modifiers) 1165 << getTypeRange(ImplVar->getTypeSourceInfo()) 1166 << MethodImpl->getDeclName(); 1167 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration) 1168 << getTypeRange(IfaceVar->getTypeSourceInfo()); 1169 } 1170 else 1171 return false; 1172 } 1173 1174 QualType ImplTy = ImplVar->getType(); 1175 QualType IfaceTy = IfaceVar->getType(); 1176 1177 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy)) 1178 return true; 1179 1180 if (!Warn) 1181 return false; 1182 unsigned DiagID = 1183 IsOverridingMode ? diag::warn_conflicting_overriding_param_types 1184 : diag::warn_conflicting_param_types; 1185 1186 // Mismatches between ObjC pointers go into a different warning 1187 // category, and sometimes they're even completely whitelisted. 1188 if (const ObjCObjectPointerType *ImplPtrTy = 1189 ImplTy->getAs<ObjCObjectPointerType>()) { 1190 if (const ObjCObjectPointerType *IfacePtrTy = 1191 IfaceTy->getAs<ObjCObjectPointerType>()) { 1192 // Allow non-matching argument types as long as they don't 1193 // violate the principle of substitutability. Specifically, the 1194 // implementation must accept any objects that the superclass 1195 // accepts, however it may also accept others. 1196 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true)) 1197 return false; 1198 1199 DiagID = 1200 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types 1201 : diag::warn_non_contravariant_param_types; 1202 } 1203 } 1204 1205 S.Diag(ImplVar->getLocation(), DiagID) 1206 << getTypeRange(ImplVar->getTypeSourceInfo()) 1207 << MethodImpl->getDeclName() << IfaceTy << ImplTy; 1208 S.Diag(IfaceVar->getLocation(), 1209 (IsOverridingMode ? diag::note_previous_declaration 1210 : diag::note_previous_definition)) 1211 << getTypeRange(IfaceVar->getTypeSourceInfo()); 1212 return false; 1213} 1214 1215/// In ARC, check whether the conventional meanings of the two methods 1216/// match. If they don't, it's a hard error. 1217static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl, 1218 ObjCMethodDecl *decl) { 1219 ObjCMethodFamily implFamily = impl->getMethodFamily(); 1220 ObjCMethodFamily declFamily = decl->getMethodFamily(); 1221 if (implFamily == declFamily) return false; 1222 1223 // Since conventions are sorted by selector, the only possibility is 1224 // that the types differ enough to cause one selector or the other 1225 // to fall out of the family. 1226 assert(implFamily == OMF_None || declFamily == OMF_None); 1227 1228 // No further diagnostics required on invalid declarations. 1229 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true; 1230 1231 const ObjCMethodDecl *unmatched = impl; 1232 ObjCMethodFamily family = declFamily; 1233 unsigned errorID = diag::err_arc_lost_method_convention; 1234 unsigned noteID = diag::note_arc_lost_method_convention; 1235 if (declFamily == OMF_None) { 1236 unmatched = decl; 1237 family = implFamily; 1238 errorID = diag::err_arc_gained_method_convention; 1239 noteID = diag::note_arc_gained_method_convention; 1240 } 1241 1242 // Indexes into a %select clause in the diagnostic. 1243 enum FamilySelector { 1244 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new 1245 }; 1246 FamilySelector familySelector = FamilySelector(); 1247 1248 switch (family) { 1249 case OMF_None: llvm_unreachable("logic error, no method convention"); 1250 case OMF_retain: 1251 case OMF_release: 1252 case OMF_autorelease: 1253 case OMF_dealloc: 1254 case OMF_retainCount: 1255 case OMF_self: 1256 case OMF_performSelector: 1257 // Mismatches for these methods don't change ownership 1258 // conventions, so we don't care. 1259 return false; 1260 1261 case OMF_init: familySelector = F_init; break; 1262 case OMF_alloc: familySelector = F_alloc; break; 1263 case OMF_copy: familySelector = F_copy; break; 1264 case OMF_mutableCopy: familySelector = F_mutableCopy; break; 1265 case OMF_new: familySelector = F_new; break; 1266 } 1267 1268 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn }; 1269 ReasonSelector reasonSelector; 1270 1271 // The only reason these methods don't fall within their families is 1272 // due to unusual result types. 1273 if (unmatched->getResultType()->isObjCObjectPointerType()) { 1274 reasonSelector = R_UnrelatedReturn; 1275 } else { 1276 reasonSelector = R_NonObjectReturn; 1277 } 1278 1279 S.Diag(impl->getLocation(), errorID) << familySelector << reasonSelector; 1280 S.Diag(decl->getLocation(), noteID) << familySelector << reasonSelector; 1281 1282 return true; 1283} 1284 1285void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, 1286 ObjCMethodDecl *MethodDecl, 1287 bool IsProtocolMethodDecl, 1288 bool IsOverridingMode) { 1289 if (getLangOptions().ObjCAutoRefCount && 1290 !IsOverridingMode && 1291 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl)) 1292 return; 1293 1294 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 1295 IsProtocolMethodDecl, IsOverridingMode, 1296 true); 1297 1298 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 1299 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(); 1300 IM != EM; ++IM, ++IF) { 1301 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF, 1302 IsProtocolMethodDecl, IsOverridingMode, true); 1303 } 1304 1305 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) { 1306 if (IsOverridingMode) 1307 Diag(ImpMethodDecl->getLocation(), 1308 diag::warn_conflicting_overriding_variadic); 1309 else 1310 Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_variadic); 1311 Diag(MethodDecl->getLocation(), diag::note_previous_declaration); 1312 } 1313} 1314 1315/// WarnExactTypedMethods - This routine issues a warning if method 1316/// implementation declaration matches exactly that of its declaration. 1317void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl, 1318 ObjCMethodDecl *MethodDecl, 1319 bool IsProtocolMethodDecl) { 1320 // don't issue warning when protocol method is optional because primary 1321 // class is not required to implement it and it is safe for protocol 1322 // to implement it. 1323 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional) 1324 return; 1325 // don't issue warning when primary class's method is 1326 // depecated/unavailable. 1327 if (MethodDecl->hasAttr<UnavailableAttr>() || 1328 MethodDecl->hasAttr<DeprecatedAttr>()) 1329 return; 1330 1331 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 1332 IsProtocolMethodDecl, false, false); 1333 if (match) 1334 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 1335 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(); 1336 IM != EM; ++IM, ++IF) { 1337 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, 1338 *IM, *IF, 1339 IsProtocolMethodDecl, false, false); 1340 if (!match) 1341 break; 1342 } 1343 if (match) 1344 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic()); 1345 if (match) 1346 match = !(MethodDecl->isClassMethod() && 1347 MethodDecl->getSelector() == GetNullarySelector("load", Context)); 1348 1349 if (match) { 1350 Diag(ImpMethodDecl->getLocation(), 1351 diag::warn_category_method_impl_match); 1352 Diag(MethodDecl->getLocation(), diag::note_method_declared_at); 1353 } 1354} 1355 1356/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely 1357/// improve the efficiency of selector lookups and type checking by associating 1358/// with each protocol / interface / category the flattened instance tables. If 1359/// we used an immutable set to keep the table then it wouldn't add significant 1360/// memory cost and it would be handy for lookups. 1361 1362/// CheckProtocolMethodDefs - This routine checks unimplemented methods 1363/// Declared in protocol, and those referenced by it. 1364void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc, 1365 ObjCProtocolDecl *PDecl, 1366 bool& IncompleteImpl, 1367 const llvm::DenseSet<Selector> &InsMap, 1368 const llvm::DenseSet<Selector> &ClsMap, 1369 ObjCContainerDecl *CDecl) { 1370 ObjCInterfaceDecl *IDecl; 1371 if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) 1372 IDecl = C->getClassInterface(); 1373 else 1374 IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl); 1375 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null"); 1376 1377 ObjCInterfaceDecl *Super = IDecl->getSuperClass(); 1378 ObjCInterfaceDecl *NSIDecl = 0; 1379 if (getLangOptions().NeXTRuntime) { 1380 // check to see if class implements forwardInvocation method and objects 1381 // of this class are derived from 'NSProxy' so that to forward requests 1382 // from one object to another. 1383 // Under such conditions, which means that every method possible is 1384 // implemented in the class, we should not issue "Method definition not 1385 // found" warnings. 1386 // FIXME: Use a general GetUnarySelector method for this. 1387 IdentifierInfo* II = &Context.Idents.get("forwardInvocation"); 1388 Selector fISelector = Context.Selectors.getSelector(1, &II); 1389 if (InsMap.count(fISelector)) 1390 // Is IDecl derived from 'NSProxy'? If so, no instance methods 1391 // need be implemented in the implementation. 1392 NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy")); 1393 } 1394 1395 // If a method lookup fails locally we still need to look and see if 1396 // the method was implemented by a base class or an inherited 1397 // protocol. This lookup is slow, but occurs rarely in correct code 1398 // and otherwise would terminate in a warning. 1399 1400 // check unimplemented instance methods. 1401 if (!NSIDecl) 1402 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(), 1403 E = PDecl->instmeth_end(); I != E; ++I) { 1404 ObjCMethodDecl *method = *I; 1405 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 1406 !method->isSynthesized() && !InsMap.count(method->getSelector()) && 1407 (!Super || 1408 !Super->lookupInstanceMethod(method->getSelector()))) { 1409 // Ugly, but necessary. Method declared in protcol might have 1410 // have been synthesized due to a property declared in the class which 1411 // uses the protocol. 1412 ObjCMethodDecl *MethodInClass = 1413 IDecl->lookupInstanceMethod(method->getSelector()); 1414 if (!MethodInClass || !MethodInClass->isSynthesized()) { 1415 unsigned DIAG = diag::warn_unimplemented_protocol_method; 1416 if (Diags.getDiagnosticLevel(DIAG, ImpLoc) 1417 != Diagnostic::Ignored) { 1418 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG); 1419 Diag(method->getLocation(), diag::note_method_declared_at); 1420 Diag(CDecl->getLocation(), diag::note_required_for_protocol_at) 1421 << PDecl->getDeclName(); 1422 } 1423 } 1424 } 1425 } 1426 // check unimplemented class methods 1427 for (ObjCProtocolDecl::classmeth_iterator 1428 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end(); 1429 I != E; ++I) { 1430 ObjCMethodDecl *method = *I; 1431 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 1432 !ClsMap.count(method->getSelector()) && 1433 (!Super || !Super->lookupClassMethod(method->getSelector()))) { 1434 unsigned DIAG = diag::warn_unimplemented_protocol_method; 1435 if (Diags.getDiagnosticLevel(DIAG, ImpLoc) != Diagnostic::Ignored) { 1436 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG); 1437 Diag(method->getLocation(), diag::note_method_declared_at); 1438 Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) << 1439 PDecl->getDeclName(); 1440 } 1441 } 1442 } 1443 // Check on this protocols's referenced protocols, recursively. 1444 for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(), 1445 E = PDecl->protocol_end(); PI != E; ++PI) 1446 CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl); 1447} 1448 1449/// MatchAllMethodDeclarations - Check methods declared in interface 1450/// or protocol against those declared in their implementations. 1451/// 1452void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap, 1453 const llvm::DenseSet<Selector> &ClsMap, 1454 llvm::DenseSet<Selector> &InsMapSeen, 1455 llvm::DenseSet<Selector> &ClsMapSeen, 1456 ObjCImplDecl* IMPDecl, 1457 ObjCContainerDecl* CDecl, 1458 bool &IncompleteImpl, 1459 bool ImmediateClass, 1460 bool WarnExactMatch) { 1461 // Check and see if instance methods in class interface have been 1462 // implemented in the implementation class. If so, their types match. 1463 for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(), 1464 E = CDecl->instmeth_end(); I != E; ++I) { 1465 if (InsMapSeen.count((*I)->getSelector())) 1466 continue; 1467 InsMapSeen.insert((*I)->getSelector()); 1468 if (!(*I)->isSynthesized() && 1469 !InsMap.count((*I)->getSelector())) { 1470 if (ImmediateClass) 1471 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl, 1472 diag::note_undef_method_impl); 1473 continue; 1474 } else { 1475 ObjCMethodDecl *ImpMethodDecl = 1476 IMPDecl->getInstanceMethod((*I)->getSelector()); 1477 ObjCMethodDecl *MethodDecl = 1478 CDecl->getInstanceMethod((*I)->getSelector()); 1479 assert(MethodDecl && 1480 "MethodDecl is null in ImplMethodsVsClassMethods"); 1481 // ImpMethodDecl may be null as in a @dynamic property. 1482 if (ImpMethodDecl) { 1483 if (!WarnExactMatch) 1484 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl, 1485 isa<ObjCProtocolDecl>(CDecl)); 1486 else 1487 WarnExactTypedMethods(ImpMethodDecl, MethodDecl, 1488 isa<ObjCProtocolDecl>(CDecl)); 1489 } 1490 } 1491 } 1492 1493 // Check and see if class methods in class interface have been 1494 // implemented in the implementation class. If so, their types match. 1495 for (ObjCInterfaceDecl::classmeth_iterator 1496 I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) { 1497 if (ClsMapSeen.count((*I)->getSelector())) 1498 continue; 1499 ClsMapSeen.insert((*I)->getSelector()); 1500 if (!ClsMap.count((*I)->getSelector())) { 1501 if (ImmediateClass) 1502 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl, 1503 diag::note_undef_method_impl); 1504 } else { 1505 ObjCMethodDecl *ImpMethodDecl = 1506 IMPDecl->getClassMethod((*I)->getSelector()); 1507 ObjCMethodDecl *MethodDecl = 1508 CDecl->getClassMethod((*I)->getSelector()); 1509 if (!WarnExactMatch) 1510 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl, 1511 isa<ObjCProtocolDecl>(CDecl)); 1512 else 1513 WarnExactTypedMethods(ImpMethodDecl, MethodDecl, 1514 isa<ObjCProtocolDecl>(CDecl)); 1515 } 1516 } 1517 1518 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 1519 // Also methods in class extensions need be looked at next. 1520 for (const ObjCCategoryDecl *ClsExtDecl = I->getFirstClassExtension(); 1521 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) 1522 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1523 IMPDecl, 1524 const_cast<ObjCCategoryDecl *>(ClsExtDecl), 1525 IncompleteImpl, false, WarnExactMatch); 1526 1527 // Check for any implementation of a methods declared in protocol. 1528 for (ObjCInterfaceDecl::all_protocol_iterator 1529 PI = I->all_referenced_protocol_begin(), 1530 E = I->all_referenced_protocol_end(); PI != E; ++PI) 1531 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1532 IMPDecl, 1533 (*PI), IncompleteImpl, false, WarnExactMatch); 1534 1535 // FIXME. For now, we are not checking for extact match of methods 1536 // in category implementation and its primary class's super class. 1537 if (!WarnExactMatch && I->getSuperClass()) 1538 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1539 IMPDecl, 1540 I->getSuperClass(), IncompleteImpl, false); 1541 } 1542} 1543 1544/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 1545/// category matches with those implemented in its primary class and 1546/// warns each time an exact match is found. 1547void Sema::CheckCategoryVsClassMethodMatches( 1548 ObjCCategoryImplDecl *CatIMPDecl) { 1549 llvm::DenseSet<Selector> InsMap, ClsMap; 1550 1551 for (ObjCImplementationDecl::instmeth_iterator 1552 I = CatIMPDecl->instmeth_begin(), 1553 E = CatIMPDecl->instmeth_end(); I!=E; ++I) 1554 InsMap.insert((*I)->getSelector()); 1555 1556 for (ObjCImplementationDecl::classmeth_iterator 1557 I = CatIMPDecl->classmeth_begin(), 1558 E = CatIMPDecl->classmeth_end(); I != E; ++I) 1559 ClsMap.insert((*I)->getSelector()); 1560 if (InsMap.empty() && ClsMap.empty()) 1561 return; 1562 1563 // Get category's primary class. 1564 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl(); 1565 if (!CatDecl) 1566 return; 1567 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface(); 1568 if (!IDecl) 1569 return; 1570 llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen; 1571 bool IncompleteImpl = false; 1572 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1573 CatIMPDecl, IDecl, 1574 IncompleteImpl, false, true /*WarnExactMatch*/); 1575} 1576 1577void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 1578 ObjCContainerDecl* CDecl, 1579 bool IncompleteImpl) { 1580 llvm::DenseSet<Selector> InsMap; 1581 // Check and see if instance methods in class interface have been 1582 // implemented in the implementation class. 1583 for (ObjCImplementationDecl::instmeth_iterator 1584 I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I) 1585 InsMap.insert((*I)->getSelector()); 1586 1587 // Check and see if properties declared in the interface have either 1) 1588 // an implementation or 2) there is a @synthesize/@dynamic implementation 1589 // of the property in the @implementation. 1590 if (isa<ObjCInterfaceDecl>(CDecl) && 1591 !(LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCNonFragileABI2)) 1592 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap); 1593 1594 llvm::DenseSet<Selector> ClsMap; 1595 for (ObjCImplementationDecl::classmeth_iterator 1596 I = IMPDecl->classmeth_begin(), 1597 E = IMPDecl->classmeth_end(); I != E; ++I) 1598 ClsMap.insert((*I)->getSelector()); 1599 1600 // Check for type conflict of methods declared in a class/protocol and 1601 // its implementation; if any. 1602 llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen; 1603 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 1604 IMPDecl, CDecl, 1605 IncompleteImpl, true); 1606 1607 // check all methods implemented in category against those declared 1608 // in its primary class. 1609 if (ObjCCategoryImplDecl *CatDecl = 1610 dyn_cast<ObjCCategoryImplDecl>(IMPDecl)) 1611 CheckCategoryVsClassMethodMatches(CatDecl); 1612 1613 // Check the protocol list for unimplemented methods in the @implementation 1614 // class. 1615 // Check and see if class methods in class interface have been 1616 // implemented in the implementation class. 1617 1618 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 1619 for (ObjCInterfaceDecl::all_protocol_iterator 1620 PI = I->all_referenced_protocol_begin(), 1621 E = I->all_referenced_protocol_end(); PI != E; ++PI) 1622 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl, 1623 InsMap, ClsMap, I); 1624 // Check class extensions (unnamed categories) 1625 for (const ObjCCategoryDecl *Categories = I->getFirstClassExtension(); 1626 Categories; Categories = Categories->getNextClassExtension()) 1627 ImplMethodsVsClassMethods(S, IMPDecl, 1628 const_cast<ObjCCategoryDecl*>(Categories), 1629 IncompleteImpl); 1630 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1631 // For extended class, unimplemented methods in its protocols will 1632 // be reported in the primary class. 1633 if (!C->IsClassExtension()) { 1634 for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(), 1635 E = C->protocol_end(); PI != E; ++PI) 1636 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl, 1637 InsMap, ClsMap, CDecl); 1638 // Report unimplemented properties in the category as well. 1639 // When reporting on missing setter/getters, do not report when 1640 // setter/getter is implemented in category's primary class 1641 // implementation. 1642 if (ObjCInterfaceDecl *ID = C->getClassInterface()) 1643 if (ObjCImplDecl *IMP = ID->getImplementation()) { 1644 for (ObjCImplementationDecl::instmeth_iterator 1645 I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I) 1646 InsMap.insert((*I)->getSelector()); 1647 } 1648 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap); 1649 } 1650 } else 1651 assert(false && "invalid ObjCContainerDecl type."); 1652} 1653 1654/// ActOnForwardClassDeclaration - 1655Decl * 1656Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, 1657 IdentifierInfo **IdentList, 1658 SourceLocation *IdentLocs, 1659 unsigned NumElts) { 1660 SmallVector<ObjCInterfaceDecl*, 32> Interfaces; 1661 1662 for (unsigned i = 0; i != NumElts; ++i) { 1663 // Check for another declaration kind with the same name. 1664 NamedDecl *PrevDecl 1665 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], 1666 LookupOrdinaryName, ForRedeclaration); 1667 if (PrevDecl && PrevDecl->isTemplateParameter()) { 1668 // Maybe we will complain about the shadowed template parameter. 1669 DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl); 1670 // Just pretend that we didn't see the previous declaration. 1671 PrevDecl = 0; 1672 } 1673 1674 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 1675 // GCC apparently allows the following idiom: 1676 // 1677 // typedef NSObject < XCElementTogglerP > XCElementToggler; 1678 // @class XCElementToggler; 1679 // 1680 // FIXME: Make an extension? 1681 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl); 1682 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) { 1683 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i]; 1684 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1685 } else { 1686 // a forward class declaration matching a typedef name of a class refers 1687 // to the underlying class. 1688 if (const ObjCObjectType *OI = 1689 TDD->getUnderlyingType()->getAs<ObjCObjectType>()) 1690 PrevDecl = OI->getInterface(); 1691 } 1692 } 1693 ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 1694 if (!IDecl) { // Not already seen? Make a forward decl. 1695 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc, 1696 IdentList[i], IdentLocs[i], true); 1697 1698 // Push the ObjCInterfaceDecl on the scope chain but do *not* add it to 1699 // the current DeclContext. This prevents clients that walk DeclContext 1700 // from seeing the imaginary ObjCInterfaceDecl until it is actually 1701 // declared later (if at all). We also take care to explicitly make 1702 // sure this declaration is visible for name lookup. 1703 PushOnScopeChains(IDecl, TUScope, false); 1704 CurContext->makeDeclVisibleInContext(IDecl, true); 1705 } 1706 1707 Interfaces.push_back(IDecl); 1708 } 1709 1710 assert(Interfaces.size() == NumElts); 1711 ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc, 1712 Interfaces.data(), IdentLocs, 1713 Interfaces.size()); 1714 CurContext->addDecl(CDecl); 1715 CheckObjCDeclScope(CDecl); 1716 return CDecl; 1717} 1718 1719static bool tryMatchRecordTypes(ASTContext &Context, 1720 Sema::MethodMatchStrategy strategy, 1721 const Type *left, const Type *right); 1722 1723static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy, 1724 QualType leftQT, QualType rightQT) { 1725 const Type *left = 1726 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr(); 1727 const Type *right = 1728 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr(); 1729 1730 if (left == right) return true; 1731 1732 // If we're doing a strict match, the types have to match exactly. 1733 if (strategy == Sema::MMS_strict) return false; 1734 1735 if (left->isIncompleteType() || right->isIncompleteType()) return false; 1736 1737 // Otherwise, use this absurdly complicated algorithm to try to 1738 // validate the basic, low-level compatibility of the two types. 1739 1740 // As a minimum, require the sizes and alignments to match. 1741 if (Context.getTypeInfo(left) != Context.getTypeInfo(right)) 1742 return false; 1743 1744 // Consider all the kinds of non-dependent canonical types: 1745 // - functions and arrays aren't possible as return and parameter types 1746 1747 // - vector types of equal size can be arbitrarily mixed 1748 if (isa<VectorType>(left)) return isa<VectorType>(right); 1749 if (isa<VectorType>(right)) return false; 1750 1751 // - references should only match references of identical type 1752 // - structs, unions, and Objective-C objects must match more-or-less 1753 // exactly 1754 // - everything else should be a scalar 1755 if (!left->isScalarType() || !right->isScalarType()) 1756 return tryMatchRecordTypes(Context, strategy, left, right); 1757 1758 // Make scalars agree in kind, except count bools as chars. 1759 Type::ScalarTypeKind leftSK = left->getScalarTypeKind(); 1760 Type::ScalarTypeKind rightSK = right->getScalarTypeKind(); 1761 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral; 1762 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral; 1763 1764 // Note that data member pointers and function member pointers don't 1765 // intermix because of the size differences. 1766 1767 return (leftSK == rightSK); 1768} 1769 1770static bool tryMatchRecordTypes(ASTContext &Context, 1771 Sema::MethodMatchStrategy strategy, 1772 const Type *lt, const Type *rt) { 1773 assert(lt && rt && lt != rt); 1774 1775 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false; 1776 RecordDecl *left = cast<RecordType>(lt)->getDecl(); 1777 RecordDecl *right = cast<RecordType>(rt)->getDecl(); 1778 1779 // Require union-hood to match. 1780 if (left->isUnion() != right->isUnion()) return false; 1781 1782 // Require an exact match if either is non-POD. 1783 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) || 1784 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD())) 1785 return false; 1786 1787 // Require size and alignment to match. 1788 if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false; 1789 1790 // Require fields to match. 1791 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end(); 1792 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end(); 1793 for (; li != le && ri != re; ++li, ++ri) { 1794 if (!matchTypes(Context, strategy, li->getType(), ri->getType())) 1795 return false; 1796 } 1797 return (li == le && ri == re); 1798} 1799 1800/// MatchTwoMethodDeclarations - Checks that two methods have matching type and 1801/// returns true, or false, accordingly. 1802/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons 1803bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left, 1804 const ObjCMethodDecl *right, 1805 MethodMatchStrategy strategy) { 1806 if (!matchTypes(Context, strategy, 1807 left->getResultType(), right->getResultType())) 1808 return false; 1809 1810 if (getLangOptions().ObjCAutoRefCount && 1811 (left->hasAttr<NSReturnsRetainedAttr>() 1812 != right->hasAttr<NSReturnsRetainedAttr>() || 1813 left->hasAttr<NSConsumesSelfAttr>() 1814 != right->hasAttr<NSConsumesSelfAttr>())) 1815 return false; 1816 1817 ObjCMethodDecl::param_iterator 1818 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(); 1819 1820 for (; li != le; ++li, ++ri) { 1821 assert(ri != right->param_end() && "Param mismatch"); 1822 ParmVarDecl *lparm = *li, *rparm = *ri; 1823 1824 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType())) 1825 return false; 1826 1827 if (getLangOptions().ObjCAutoRefCount && 1828 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>()) 1829 return false; 1830 } 1831 return true; 1832} 1833 1834/// \brief Read the contents of the method pool for a given selector from 1835/// external storage. 1836/// 1837/// This routine should only be called once, when the method pool has no entry 1838/// for this selector. 1839Sema::GlobalMethodPool::iterator Sema::ReadMethodPool(Selector Sel) { 1840 assert(ExternalSource && "We need an external AST source"); 1841 assert(MethodPool.find(Sel) == MethodPool.end() && 1842 "Selector data already loaded into the method pool"); 1843 1844 // Read the method list from the external source. 1845 GlobalMethods Methods = ExternalSource->ReadMethodPool(Sel); 1846 1847 return MethodPool.insert(std::make_pair(Sel, Methods)).first; 1848} 1849 1850void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, 1851 bool instance) { 1852 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector()); 1853 if (Pos == MethodPool.end()) { 1854 if (ExternalSource) 1855 Pos = ReadMethodPool(Method->getSelector()); 1856 else 1857 Pos = MethodPool.insert(std::make_pair(Method->getSelector(), 1858 GlobalMethods())).first; 1859 } 1860 Method->setDefined(impl); 1861 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second; 1862 if (Entry.Method == 0) { 1863 // Haven't seen a method with this selector name yet - add it. 1864 Entry.Method = Method; 1865 Entry.Next = 0; 1866 return; 1867 } 1868 1869 // We've seen a method with this name, see if we have already seen this type 1870 // signature. 1871 for (ObjCMethodList *List = &Entry; List; List = List->Next) { 1872 bool match = MatchTwoMethodDeclarations(Method, List->Method); 1873 1874 if (match) { 1875 ObjCMethodDecl *PrevObjCMethod = List->Method; 1876 PrevObjCMethod->setDefined(impl); 1877 // If a method is deprecated, push it in the global pool. 1878 // This is used for better diagnostics. 1879 if (Method->isDeprecated()) { 1880 if (!PrevObjCMethod->isDeprecated()) 1881 List->Method = Method; 1882 } 1883 // If new method is unavailable, push it into global pool 1884 // unless previous one is deprecated. 1885 if (Method->isUnavailable()) { 1886 if (PrevObjCMethod->getAvailability() < AR_Deprecated) 1887 List->Method = Method; 1888 } 1889 return; 1890 } 1891 } 1892 1893 // We have a new signature for an existing method - add it. 1894 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded". 1895 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>(); 1896 Entry.Next = new (Mem) ObjCMethodList(Method, Entry.Next); 1897} 1898 1899/// Determines if this is an "acceptable" loose mismatch in the global 1900/// method pool. This exists mostly as a hack to get around certain 1901/// global mismatches which we can't afford to make warnings / errors. 1902/// Really, what we want is a way to take a method out of the global 1903/// method pool. 1904static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen, 1905 ObjCMethodDecl *other) { 1906 if (!chosen->isInstanceMethod()) 1907 return false; 1908 1909 Selector sel = chosen->getSelector(); 1910 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length") 1911 return false; 1912 1913 // Don't complain about mismatches for -length if the method we 1914 // chose has an integral result type. 1915 return (chosen->getResultType()->isIntegerType()); 1916} 1917 1918ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R, 1919 bool receiverIdOrClass, 1920 bool warn, bool instance) { 1921 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 1922 if (Pos == MethodPool.end()) { 1923 if (ExternalSource) 1924 Pos = ReadMethodPool(Sel); 1925 else 1926 return 0; 1927 } 1928 1929 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 1930 1931 if (warn && MethList.Method && MethList.Next) { 1932 bool issueDiagnostic = false, issueError = false; 1933 1934 // We support a warning which complains about *any* difference in 1935 // method signature. 1936 bool strictSelectorMatch = 1937 (receiverIdOrClass && warn && 1938 (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl, 1939 R.getBegin()) != 1940 Diagnostic::Ignored)); 1941 if (strictSelectorMatch) 1942 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) { 1943 if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, 1944 MMS_strict)) { 1945 issueDiagnostic = true; 1946 break; 1947 } 1948 } 1949 1950 // If we didn't see any strict differences, we won't see any loose 1951 // differences. In ARC, however, we also need to check for loose 1952 // mismatches, because most of them are errors. 1953 if (!strictSelectorMatch || 1954 (issueDiagnostic && getLangOptions().ObjCAutoRefCount)) 1955 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) { 1956 // This checks if the methods differ in type mismatch. 1957 if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, 1958 MMS_loose) && 1959 !isAcceptableMethodMismatch(MethList.Method, Next->Method)) { 1960 issueDiagnostic = true; 1961 if (getLangOptions().ObjCAutoRefCount) 1962 issueError = true; 1963 break; 1964 } 1965 } 1966 1967 if (issueDiagnostic) { 1968 if (issueError) 1969 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R; 1970 else if (strictSelectorMatch) 1971 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R; 1972 else 1973 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R; 1974 1975 Diag(MethList.Method->getLocStart(), 1976 issueError ? diag::note_possibility : diag::note_using) 1977 << MethList.Method->getSourceRange(); 1978 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) 1979 Diag(Next->Method->getLocStart(), diag::note_also_found) 1980 << Next->Method->getSourceRange(); 1981 } 1982 } 1983 return MethList.Method; 1984} 1985 1986ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) { 1987 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 1988 if (Pos == MethodPool.end()) 1989 return 0; 1990 1991 GlobalMethods &Methods = Pos->second; 1992 1993 if (Methods.first.Method && Methods.first.Method->isDefined()) 1994 return Methods.first.Method; 1995 if (Methods.second.Method && Methods.second.Method->isDefined()) 1996 return Methods.second.Method; 1997 return 0; 1998} 1999 2000/// CompareMethodParamsInBaseAndSuper - This routine compares methods with 2001/// identical selector names in current and its super classes and issues 2002/// a warning if any of their argument types are incompatible. 2003void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl, 2004 ObjCMethodDecl *Method, 2005 bool IsInstance) { 2006 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl); 2007 if (ID == 0) return; 2008 2009 while (ObjCInterfaceDecl *SD = ID->getSuperClass()) { 2010 ObjCMethodDecl *SuperMethodDecl = 2011 SD->lookupMethod(Method->getSelector(), IsInstance); 2012 if (SuperMethodDecl == 0) { 2013 ID = SD; 2014 continue; 2015 } 2016 ObjCMethodDecl::param_iterator ParamI = Method->param_begin(), 2017 E = Method->param_end(); 2018 ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin(); 2019 for (; ParamI != E; ++ParamI, ++PrevI) { 2020 // Number of parameters are the same and is guaranteed by selector match. 2021 assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch"); 2022 QualType T1 = Context.getCanonicalType((*ParamI)->getType()); 2023 QualType T2 = Context.getCanonicalType((*PrevI)->getType()); 2024 // If type of argument of method in this class does not match its 2025 // respective argument type in the super class method, issue warning; 2026 if (!Context.typesAreCompatible(T1, T2)) { 2027 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super) 2028 << T1 << T2; 2029 Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration); 2030 return; 2031 } 2032 } 2033 ID = SD; 2034 } 2035} 2036 2037/// DiagnoseDuplicateIvars - 2038/// Check for duplicate ivars in the entire class at the start of 2039/// @implementation. This becomes necesssary because class extension can 2040/// add ivars to a class in random order which will not be known until 2041/// class's @implementation is seen. 2042void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, 2043 ObjCInterfaceDecl *SID) { 2044 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(), 2045 IVE = ID->ivar_end(); IVI != IVE; ++IVI) { 2046 ObjCIvarDecl* Ivar = (*IVI); 2047 if (Ivar->isInvalidDecl()) 2048 continue; 2049 if (IdentifierInfo *II = Ivar->getIdentifier()) { 2050 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II); 2051 if (prevIvar) { 2052 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 2053 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 2054 Ivar->setInvalidDecl(); 2055 } 2056 } 2057 } 2058} 2059 2060// Note: For class/category implemenations, allMethods/allProperties is 2061// always null. 2062void Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, 2063 Decl **allMethods, unsigned allNum, 2064 Decl **allProperties, unsigned pNum, 2065 DeclGroupPtrTy *allTUVars, unsigned tuvNum) { 2066 2067 if (!CurContext->isObjCContainer()) 2068 return; 2069 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 2070 Decl *ClassDecl = cast<Decl>(OCD); 2071 2072 bool isInterfaceDeclKind = 2073 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl) 2074 || isa<ObjCProtocolDecl>(ClassDecl); 2075 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl); 2076 2077 if (!isInterfaceDeclKind && AtEnd.isInvalid()) { 2078 // FIXME: This is wrong. We shouldn't be pretending that there is 2079 // an '@end' in the declaration. 2080 SourceLocation L = ClassDecl->getLocation(); 2081 AtEnd.setBegin(L); 2082 AtEnd.setEnd(L); 2083 Diag(L, diag::err_missing_atend); 2084 } 2085 2086 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext. 2087 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap; 2088 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap; 2089 2090 for (unsigned i = 0; i < allNum; i++ ) { 2091 ObjCMethodDecl *Method = 2092 cast_or_null<ObjCMethodDecl>(allMethods[i]); 2093 2094 if (!Method) continue; // Already issued a diagnostic. 2095 if (Method->isInstanceMethod()) { 2096 /// Check for instance method of the same name with incompatible types 2097 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()]; 2098 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 2099 : false; 2100 if ((isInterfaceDeclKind && PrevMethod && !match) 2101 || (checkIdenticalMethods && match)) { 2102 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 2103 << Method->getDeclName(); 2104 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2105 Method->setInvalidDecl(); 2106 } else { 2107 InsMap[Method->getSelector()] = Method; 2108 /// The following allows us to typecheck messages to "id". 2109 AddInstanceMethodToGlobalPool(Method); 2110 // verify that the instance method conforms to the same definition of 2111 // parent methods if it shadows one. 2112 CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true); 2113 } 2114 } else { 2115 /// Check for class method of the same name with incompatible types 2116 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()]; 2117 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 2118 : false; 2119 if ((isInterfaceDeclKind && PrevMethod && !match) 2120 || (checkIdenticalMethods && match)) { 2121 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 2122 << Method->getDeclName(); 2123 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2124 Method->setInvalidDecl(); 2125 } else { 2126 ClsMap[Method->getSelector()] = Method; 2127 /// The following allows us to typecheck messages to "Class". 2128 AddFactoryMethodToGlobalPool(Method); 2129 // verify that the class method conforms to the same definition of 2130 // parent methods if it shadows one. 2131 CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false); 2132 } 2133 } 2134 } 2135 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) { 2136 // Compares properties declared in this class to those of its 2137 // super class. 2138 ComparePropertiesInBaseAndSuper(I); 2139 CompareProperties(I, I); 2140 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 2141 // Categories are used to extend the class by declaring new methods. 2142 // By the same token, they are also used to add new properties. No 2143 // need to compare the added property to those in the class. 2144 2145 // Compare protocol properties with those in category 2146 CompareProperties(C, C); 2147 if (C->IsClassExtension()) { 2148 ObjCInterfaceDecl *CCPrimary = C->getClassInterface(); 2149 DiagnoseClassExtensionDupMethods(C, CCPrimary); 2150 } 2151 } 2152 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) { 2153 if (CDecl->getIdentifier()) 2154 // ProcessPropertyDecl is responsible for diagnosing conflicts with any 2155 // user-defined setter/getter. It also synthesizes setter/getter methods 2156 // and adds them to the DeclContext and global method pools. 2157 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(), 2158 E = CDecl->prop_end(); 2159 I != E; ++I) 2160 ProcessPropertyDecl(*I, CDecl); 2161 CDecl->setAtEndRange(AtEnd); 2162 } 2163 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) { 2164 IC->setAtEndRange(AtEnd); 2165 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) { 2166 // Any property declared in a class extension might have user 2167 // declared setter or getter in current class extension or one 2168 // of the other class extensions. Mark them as synthesized as 2169 // property will be synthesized when property with same name is 2170 // seen in the @implementation. 2171 for (const ObjCCategoryDecl *ClsExtDecl = 2172 IDecl->getFirstClassExtension(); 2173 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) { 2174 for (ObjCContainerDecl::prop_iterator I = ClsExtDecl->prop_begin(), 2175 E = ClsExtDecl->prop_end(); I != E; ++I) { 2176 ObjCPropertyDecl *Property = (*I); 2177 // Skip over properties declared @dynamic 2178 if (const ObjCPropertyImplDecl *PIDecl 2179 = IC->FindPropertyImplDecl(Property->getIdentifier())) 2180 if (PIDecl->getPropertyImplementation() 2181 == ObjCPropertyImplDecl::Dynamic) 2182 continue; 2183 2184 for (const ObjCCategoryDecl *CExtDecl = 2185 IDecl->getFirstClassExtension(); 2186 CExtDecl; CExtDecl = CExtDecl->getNextClassExtension()) { 2187 if (ObjCMethodDecl *GetterMethod = 2188 CExtDecl->getInstanceMethod(Property->getGetterName())) 2189 GetterMethod->setSynthesized(true); 2190 if (!Property->isReadOnly()) 2191 if (ObjCMethodDecl *SetterMethod = 2192 CExtDecl->getInstanceMethod(Property->getSetterName())) 2193 SetterMethod->setSynthesized(true); 2194 } 2195 } 2196 } 2197 2198 if (LangOpts.ObjCDefaultSynthProperties && 2199 LangOpts.ObjCNonFragileABI2) 2200 DefaultSynthesizeProperties(S, IC, IDecl); 2201 ImplMethodsVsClassMethods(S, IC, IDecl); 2202 AtomicPropertySetterGetterRules(IC, IDecl); 2203 DiagnoseOwningPropertyGetterSynthesis(IC); 2204 2205 if (LangOpts.ObjCNonFragileABI2) 2206 while (IDecl->getSuperClass()) { 2207 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass()); 2208 IDecl = IDecl->getSuperClass(); 2209 } 2210 } 2211 SetIvarInitializers(IC); 2212 } else if (ObjCCategoryImplDecl* CatImplClass = 2213 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) { 2214 CatImplClass->setAtEndRange(AtEnd); 2215 2216 // Find category interface decl and then check that all methods declared 2217 // in this interface are implemented in the category @implementation. 2218 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) { 2219 for (ObjCCategoryDecl *Categories = IDecl->getCategoryList(); 2220 Categories; Categories = Categories->getNextClassCategory()) { 2221 if (Categories->getIdentifier() == CatImplClass->getIdentifier()) { 2222 ImplMethodsVsClassMethods(S, CatImplClass, Categories); 2223 break; 2224 } 2225 } 2226 } 2227 } 2228 if (isInterfaceDeclKind) { 2229 // Reject invalid vardecls. 2230 for (unsigned i = 0; i != tuvNum; i++) { 2231 DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>(); 2232 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 2233 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) { 2234 if (!VDecl->hasExternalStorage()) 2235 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass); 2236 } 2237 } 2238 } 2239} 2240 2241 2242/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for 2243/// objective-c's type qualifier from the parser version of the same info. 2244static Decl::ObjCDeclQualifier 2245CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) { 2246 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal; 2247} 2248 2249static inline 2250bool containsInvalidMethodImplAttribute(const AttrVec &A) { 2251 // The 'ibaction' attribute is allowed on method definitions because of 2252 // how the IBAction macro is used on both method declarations and definitions. 2253 // If the method definitions contains any other attributes, return true. 2254 for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i) 2255 if ((*i)->getKind() != attr::IBAction) 2256 return true; 2257 return false; 2258} 2259 2260/// \brief Check whether the declared result type of the given Objective-C 2261/// method declaration is compatible with the method's class. 2262/// 2263static bool 2264CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, 2265 ObjCInterfaceDecl *CurrentClass) { 2266 QualType ResultType = Method->getResultType(); 2267 SourceRange ResultTypeRange; 2268 if (const TypeSourceInfo *ResultTypeInfo = Method->getResultTypeSourceInfo()) 2269 ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange(); 2270 2271 // If an Objective-C method inherits its related result type, then its 2272 // declared result type must be compatible with its own class type. The 2273 // declared result type is compatible if: 2274 if (const ObjCObjectPointerType *ResultObjectType 2275 = ResultType->getAs<ObjCObjectPointerType>()) { 2276 // - it is id or qualified id, or 2277 if (ResultObjectType->isObjCIdType() || 2278 ResultObjectType->isObjCQualifiedIdType()) 2279 return false; 2280 2281 if (CurrentClass) { 2282 if (ObjCInterfaceDecl *ResultClass 2283 = ResultObjectType->getInterfaceDecl()) { 2284 // - it is the same as the method's class type, or 2285 if (CurrentClass == ResultClass) 2286 return false; 2287 2288 // - it is a superclass of the method's class type 2289 if (ResultClass->isSuperClassOf(CurrentClass)) 2290 return false; 2291 } 2292 } 2293 } 2294 2295 return true; 2296} 2297 2298namespace { 2299/// A helper class for searching for methods which a particular method 2300/// overrides. 2301class OverrideSearch { 2302 Sema &S; 2303 ObjCMethodDecl *Method; 2304 llvm::SmallPtrSet<ObjCContainerDecl*, 8> Searched; 2305 llvm::SmallPtrSet<ObjCMethodDecl*, 8> Overridden; 2306 bool Recursive; 2307 2308public: 2309 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) { 2310 Selector selector = method->getSelector(); 2311 2312 // Bypass this search if we've never seen an instance/class method 2313 // with this selector before. 2314 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector); 2315 if (it == S.MethodPool.end()) { 2316 if (!S.ExternalSource) return; 2317 it = S.ReadMethodPool(selector); 2318 } 2319 ObjCMethodList &list = 2320 method->isInstanceMethod() ? it->second.first : it->second.second; 2321 if (!list.Method) return; 2322 2323 ObjCContainerDecl *container 2324 = cast<ObjCContainerDecl>(method->getDeclContext()); 2325 2326 // Prevent the search from reaching this container again. This is 2327 // important with categories, which override methods from the 2328 // interface and each other. 2329 Searched.insert(container); 2330 searchFromContainer(container); 2331 } 2332 2333 typedef llvm::SmallPtrSet<ObjCMethodDecl*,8>::iterator iterator; 2334 iterator begin() const { return Overridden.begin(); } 2335 iterator end() const { return Overridden.end(); } 2336 2337private: 2338 void searchFromContainer(ObjCContainerDecl *container) { 2339 if (container->isInvalidDecl()) return; 2340 2341 switch (container->getDeclKind()) { 2342#define OBJCCONTAINER(type, base) \ 2343 case Decl::type: \ 2344 searchFrom(cast<type##Decl>(container)); \ 2345 break; 2346#define ABSTRACT_DECL(expansion) 2347#define DECL(type, base) \ 2348 case Decl::type: 2349#include "clang/AST/DeclNodes.inc" 2350 llvm_unreachable("not an ObjC container!"); 2351 } 2352 } 2353 2354 void searchFrom(ObjCProtocolDecl *protocol) { 2355 // A method in a protocol declaration overrides declarations from 2356 // referenced ("parent") protocols. 2357 search(protocol->getReferencedProtocols()); 2358 } 2359 2360 void searchFrom(ObjCCategoryDecl *category) { 2361 // A method in a category declaration overrides declarations from 2362 // the main class and from protocols the category references. 2363 search(category->getClassInterface()); 2364 search(category->getReferencedProtocols()); 2365 } 2366 2367 void searchFrom(ObjCCategoryImplDecl *impl) { 2368 // A method in a category definition that has a category 2369 // declaration overrides declarations from the category 2370 // declaration. 2371 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) { 2372 search(category); 2373 2374 // Otherwise it overrides declarations from the class. 2375 } else { 2376 search(impl->getClassInterface()); 2377 } 2378 } 2379 2380 void searchFrom(ObjCInterfaceDecl *iface) { 2381 // A method in a class declaration overrides declarations from 2382 2383 // - categories, 2384 for (ObjCCategoryDecl *category = iface->getCategoryList(); 2385 category; category = category->getNextClassCategory()) 2386 search(category); 2387 2388 // - the super class, and 2389 if (ObjCInterfaceDecl *super = iface->getSuperClass()) 2390 search(super); 2391 2392 // - any referenced protocols. 2393 search(iface->getReferencedProtocols()); 2394 } 2395 2396 void searchFrom(ObjCImplementationDecl *impl) { 2397 // A method in a class implementation overrides declarations from 2398 // the class interface. 2399 search(impl->getClassInterface()); 2400 } 2401 2402 2403 void search(const ObjCProtocolList &protocols) { 2404 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end(); 2405 i != e; ++i) 2406 search(*i); 2407 } 2408 2409 void search(ObjCContainerDecl *container) { 2410 // Abort if we've already searched this container. 2411 if (!Searched.insert(container)) return; 2412 2413 // Check for a method in this container which matches this selector. 2414 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(), 2415 Method->isInstanceMethod()); 2416 2417 // If we find one, record it and bail out. 2418 if (meth) { 2419 Overridden.insert(meth); 2420 return; 2421 } 2422 2423 // Otherwise, search for methods that a hypothetical method here 2424 // would have overridden. 2425 2426 // Note that we're now in a recursive case. 2427 Recursive = true; 2428 2429 searchFromContainer(container); 2430 } 2431}; 2432} 2433 2434Decl *Sema::ActOnMethodDeclaration( 2435 Scope *S, 2436 SourceLocation MethodLoc, SourceLocation EndLoc, 2437 tok::TokenKind MethodType, 2438 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 2439 SourceLocation SelectorStartLoc, 2440 Selector Sel, 2441 // optional arguments. The number of types/arguments is obtained 2442 // from the Sel.getNumArgs(). 2443 ObjCArgInfo *ArgInfo, 2444 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 2445 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind, 2446 bool isVariadic, bool MethodDefinition) { 2447 // Make sure we can establish a context for the method. 2448 if (!CurContext->isObjCContainer()) { 2449 Diag(MethodLoc, diag::error_missing_method_context); 2450 return 0; 2451 } 2452 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 2453 Decl *ClassDecl = cast<Decl>(OCD); 2454 QualType resultDeclType; 2455 2456 TypeSourceInfo *ResultTInfo = 0; 2457 if (ReturnType) { 2458 resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo); 2459 2460 // Methods cannot return interface types. All ObjC objects are 2461 // passed by reference. 2462 if (resultDeclType->isObjCObjectType()) { 2463 Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value) 2464 << 0 << resultDeclType; 2465 return 0; 2466 } 2467 } else { // get the type for "id". 2468 resultDeclType = Context.getObjCIdType(); 2469 Diag(MethodLoc, diag::warn_missing_method_return_type) 2470 << FixItHint::CreateInsertion(SelectorStartLoc, "(id)"); 2471 } 2472 2473 ObjCMethodDecl* ObjCMethod = 2474 ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType, 2475 ResultTInfo, 2476 CurContext, 2477 MethodType == tok::minus, isVariadic, 2478 /*isSynthesized=*/false, 2479 /*isImplicitlyDeclared=*/false, /*isDefined=*/false, 2480 MethodDeclKind == tok::objc_optional 2481 ? ObjCMethodDecl::Optional 2482 : ObjCMethodDecl::Required, 2483 false); 2484 2485 SmallVector<ParmVarDecl*, 16> Params; 2486 2487 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) { 2488 QualType ArgType; 2489 TypeSourceInfo *DI; 2490 2491 if (ArgInfo[i].Type == 0) { 2492 ArgType = Context.getObjCIdType(); 2493 DI = 0; 2494 } else { 2495 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI); 2496 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]). 2497 ArgType = Context.getAdjustedParameterType(ArgType); 2498 } 2499 2500 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, 2501 LookupOrdinaryName, ForRedeclaration); 2502 LookupName(R, S); 2503 if (R.isSingleResult()) { 2504 NamedDecl *PrevDecl = R.getFoundDecl(); 2505 if (S->isDeclScope(PrevDecl)) { 2506 Diag(ArgInfo[i].NameLoc, 2507 (MethodDefinition ? diag::warn_method_param_redefinition 2508 : diag::warn_method_param_declaration)) 2509 << ArgInfo[i].Name; 2510 Diag(PrevDecl->getLocation(), 2511 diag::note_previous_declaration); 2512 } 2513 } 2514 2515 SourceLocation StartLoc = DI 2516 ? DI->getTypeLoc().getBeginLoc() 2517 : ArgInfo[i].NameLoc; 2518 2519 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc, 2520 ArgInfo[i].NameLoc, ArgInfo[i].Name, 2521 ArgType, DI, SC_None, SC_None); 2522 2523 Param->setObjCMethodScopeInfo(i); 2524 2525 Param->setObjCDeclQualifier( 2526 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier())); 2527 2528 // Apply the attributes to the parameter. 2529 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs); 2530 2531 S->AddDecl(Param); 2532 IdResolver.AddDecl(Param); 2533 2534 Params.push_back(Param); 2535 } 2536 2537 for (unsigned i = 0, e = CNumArgs; i != e; ++i) { 2538 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param); 2539 QualType ArgType = Param->getType(); 2540 if (ArgType.isNull()) 2541 ArgType = Context.getObjCIdType(); 2542 else 2543 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]). 2544 ArgType = Context.getAdjustedParameterType(ArgType); 2545 if (ArgType->isObjCObjectType()) { 2546 Diag(Param->getLocation(), 2547 diag::err_object_cannot_be_passed_returned_by_value) 2548 << 1 << ArgType; 2549 Param->setInvalidDecl(); 2550 } 2551 Param->setDeclContext(ObjCMethod); 2552 2553 Params.push_back(Param); 2554 } 2555 2556 ObjCMethod->setMethodParams(Context, Params.data(), Params.size(), 2557 Sel.getNumArgs()); 2558 ObjCMethod->setObjCDeclQualifier( 2559 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier())); 2560 2561 if (AttrList) 2562 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList); 2563 2564 // Add the method now. 2565 const ObjCMethodDecl *PrevMethod = 0; 2566 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) { 2567 if (MethodType == tok::minus) { 2568 PrevMethod = ImpDecl->getInstanceMethod(Sel); 2569 ImpDecl->addInstanceMethod(ObjCMethod); 2570 } else { 2571 PrevMethod = ImpDecl->getClassMethod(Sel); 2572 ImpDecl->addClassMethod(ObjCMethod); 2573 } 2574 2575 if (ObjCMethod->hasAttrs() && 2576 containsInvalidMethodImplAttribute(ObjCMethod->getAttrs())) 2577 Diag(EndLoc, diag::warn_attribute_method_def); 2578 } else { 2579 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod); 2580 } 2581 2582 if (PrevMethod) { 2583 // You can never have two method definitions with the same name. 2584 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl) 2585 << ObjCMethod->getDeclName(); 2586 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 2587 } 2588 2589 // If this Objective-C method does not have a related result type, but we 2590 // are allowed to infer related result types, try to do so based on the 2591 // method family. 2592 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl); 2593 if (!CurrentClass) { 2594 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) 2595 CurrentClass = Cat->getClassInterface(); 2596 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl)) 2597 CurrentClass = Impl->getClassInterface(); 2598 else if (ObjCCategoryImplDecl *CatImpl 2599 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) 2600 CurrentClass = CatImpl->getClassInterface(); 2601 } 2602 2603 bool isRelatedResultTypeCompatible = 2604 (getLangOptions().ObjCInferRelatedResultType && 2605 !CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass)); 2606 2607 // Search for overridden methods and merge information down from them. 2608 OverrideSearch overrides(*this, ObjCMethod); 2609 for (OverrideSearch::iterator 2610 i = overrides.begin(), e = overrides.end(); i != e; ++i) { 2611 ObjCMethodDecl *overridden = *i; 2612 2613 // Propagate down the 'related result type' bit from overridden methods. 2614 if (isRelatedResultTypeCompatible && overridden->hasRelatedResultType()) 2615 ObjCMethod->SetRelatedResultType(); 2616 2617 // Then merge the declarations. 2618 mergeObjCMethodDecls(ObjCMethod, overridden); 2619 2620 // Check for overriding methods 2621 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || 2622 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())) { 2623 WarnConflictingTypedMethods(ObjCMethod, overridden, 2624 isa<ObjCProtocolDecl>(overridden->getDeclContext()), true); 2625 } 2626 } 2627 2628 bool ARCError = false; 2629 if (getLangOptions().ObjCAutoRefCount) 2630 ARCError = CheckARCMethodDecl(*this, ObjCMethod); 2631 2632 if (!ARCError && isRelatedResultTypeCompatible && 2633 !ObjCMethod->hasRelatedResultType()) { 2634 bool InferRelatedResultType = false; 2635 switch (ObjCMethod->getMethodFamily()) { 2636 case OMF_None: 2637 case OMF_copy: 2638 case OMF_dealloc: 2639 case OMF_mutableCopy: 2640 case OMF_release: 2641 case OMF_retainCount: 2642 case OMF_performSelector: 2643 break; 2644 2645 case OMF_alloc: 2646 case OMF_new: 2647 InferRelatedResultType = ObjCMethod->isClassMethod(); 2648 break; 2649 2650 case OMF_init: 2651 case OMF_autorelease: 2652 case OMF_retain: 2653 case OMF_self: 2654 InferRelatedResultType = ObjCMethod->isInstanceMethod(); 2655 break; 2656 } 2657 2658 if (InferRelatedResultType) 2659 ObjCMethod->SetRelatedResultType(); 2660 } 2661 2662 return ObjCMethod; 2663} 2664 2665bool Sema::CheckObjCDeclScope(Decl *D) { 2666 if (isa<TranslationUnitDecl>(CurContext->getRedeclContext())) 2667 return false; 2668 // Following is also an error. But it is caused by a missing @end 2669 // and diagnostic is issued elsewhere. 2670 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) { 2671 return false; 2672 } 2673 2674 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope); 2675 D->setInvalidDecl(); 2676 2677 return true; 2678} 2679 2680/// Called whenever @defs(ClassName) is encountered in the source. Inserts the 2681/// instance variables of ClassName into Decls. 2682void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 2683 IdentifierInfo *ClassName, 2684 SmallVectorImpl<Decl*> &Decls) { 2685 // Check that ClassName is a valid class 2686 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart); 2687 if (!Class) { 2688 Diag(DeclStart, diag::err_undef_interface) << ClassName; 2689 return; 2690 } 2691 if (LangOpts.ObjCNonFragileABI) { 2692 Diag(DeclStart, diag::err_atdef_nonfragile_interface); 2693 return; 2694 } 2695 2696 // Collect the instance variables 2697 SmallVector<const ObjCIvarDecl*, 32> Ivars; 2698 Context.DeepCollectObjCIvars(Class, true, Ivars); 2699 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 2700 for (unsigned i = 0; i < Ivars.size(); i++) { 2701 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]); 2702 RecordDecl *Record = dyn_cast<RecordDecl>(TagD); 2703 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, 2704 /*FIXME: StartL=*/ID->getLocation(), 2705 ID->getLocation(), 2706 ID->getIdentifier(), ID->getType(), 2707 ID->getBitWidth()); 2708 Decls.push_back(FD); 2709 } 2710 2711 // Introduce all of these fields into the appropriate scope. 2712 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin(); 2713 D != Decls.end(); ++D) { 2714 FieldDecl *FD = cast<FieldDecl>(*D); 2715 if (getLangOptions().CPlusPlus) 2716 PushOnScopeChains(cast<FieldDecl>(FD), S); 2717 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD)) 2718 Record->addDecl(FD); 2719 } 2720} 2721 2722/// \brief Build a type-check a new Objective-C exception variable declaration. 2723VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, 2724 SourceLocation StartLoc, 2725 SourceLocation IdLoc, 2726 IdentifierInfo *Id, 2727 bool Invalid) { 2728 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 2729 // duration shall not be qualified by an address-space qualifier." 2730 // Since all parameters have automatic store duration, they can not have 2731 // an address space. 2732 if (T.getAddressSpace() != 0) { 2733 Diag(IdLoc, diag::err_arg_with_address_space); 2734 Invalid = true; 2735 } 2736 2737 // An @catch parameter must be an unqualified object pointer type; 2738 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"? 2739 if (Invalid) { 2740 // Don't do any further checking. 2741 } else if (T->isDependentType()) { 2742 // Okay: we don't know what this type will instantiate to. 2743 } else if (!T->isObjCObjectPointerType()) { 2744 Invalid = true; 2745 Diag(IdLoc ,diag::err_catch_param_not_objc_type); 2746 } else if (T->isObjCQualifiedIdType()) { 2747 Invalid = true; 2748 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm); 2749 } 2750 2751 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id, 2752 T, TInfo, SC_None, SC_None); 2753 New->setExceptionVariable(true); 2754 2755 if (Invalid) 2756 New->setInvalidDecl(); 2757 return New; 2758} 2759 2760Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { 2761 const DeclSpec &DS = D.getDeclSpec(); 2762 2763 // We allow the "register" storage class on exception variables because 2764 // GCC did, but we drop it completely. Any other storage class is an error. 2765 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 2766 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm) 2767 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc())); 2768 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) { 2769 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm) 2770 << DS.getStorageClassSpec(); 2771 } 2772 if (D.getDeclSpec().isThreadSpecified()) 2773 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread); 2774 D.getMutableDeclSpec().ClearStorageClassSpecs(); 2775 2776 DiagnoseFunctionSpecifiers(D); 2777 2778 // Check that there are no default arguments inside the type of this 2779 // exception object (C++ only). 2780 if (getLangOptions().CPlusPlus) 2781 CheckExtraCXXDefaultArguments(D); 2782 2783 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 2784 QualType ExceptionType = TInfo->getType(); 2785 2786 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType, 2787 D.getSourceRange().getBegin(), 2788 D.getIdentifierLoc(), 2789 D.getIdentifier(), 2790 D.isInvalidType()); 2791 2792 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 2793 if (D.getCXXScopeSpec().isSet()) { 2794 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm) 2795 << D.getCXXScopeSpec().getRange(); 2796 New->setInvalidDecl(); 2797 } 2798 2799 // Add the parameter declaration into this scope. 2800 S->AddDecl(New); 2801 if (D.getIdentifier()) 2802 IdResolver.AddDecl(New); 2803 2804 ProcessDeclAttributes(S, New, D); 2805 2806 if (New->hasAttr<BlocksAttr>()) 2807 Diag(New->getLocation(), diag::err_block_on_nonlocal); 2808 return New; 2809} 2810 2811/// CollectIvarsToConstructOrDestruct - Collect those ivars which require 2812/// initialization. 2813void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 2814 SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 2815 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; 2816 Iv= Iv->getNextIvar()) { 2817 QualType QT = Context.getBaseElementType(Iv->getType()); 2818 if (QT->isRecordType()) 2819 Ivars.push_back(Iv); 2820 } 2821} 2822 2823void Sema::DiagnoseUseOfUnimplementedSelectors() { 2824 // Load referenced selectors from the external source. 2825 if (ExternalSource) { 2826 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels; 2827 ExternalSource->ReadReferencedSelectors(Sels); 2828 for (unsigned I = 0, N = Sels.size(); I != N; ++I) 2829 ReferencedSelectors[Sels[I].first] = Sels[I].second; 2830 } 2831 2832 // Warning will be issued only when selector table is 2833 // generated (which means there is at lease one implementation 2834 // in the TU). This is to match gcc's behavior. 2835 if (ReferencedSelectors.empty() || 2836 !Context.AnyObjCImplementation()) 2837 return; 2838 for (llvm::DenseMap<Selector, SourceLocation>::iterator S = 2839 ReferencedSelectors.begin(), 2840 E = ReferencedSelectors.end(); S != E; ++S) { 2841 Selector Sel = (*S).first; 2842 if (!LookupImplementedMethodInGlobalPool(Sel)) 2843 Diag((*S).second, diag::warn_unimplemented_selector) << Sel; 2844 } 2845 return; 2846} 2847