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