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