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