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