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