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