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