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