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