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/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/DataRecursiveASTVisitor.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprObjC.h" 22 #include "clang/Basic/SourceManager.h" 23 #include "clang/Lex/Preprocessor.h" 24 #include "clang/Sema/DeclSpec.h" 25 #include "clang/Sema/ExternalSemaSource.h" 26 #include "clang/Sema/Lookup.h" 27 #include "clang/Sema/Scope.h" 28 #include "clang/Sema/ScopeInfo.h" 29 #include "llvm/ADT/DenseMap.h" 30 #include "llvm/ADT/DenseSet.h" 31 #include "TypeLocBuilder.h" 32 33 using namespace clang; 34 35 /// Check whether the given method, which must be in the 'init' 36 /// family, is a valid member of that family. 37 /// 38 /// \param receiverTypeIfCall - if null, check this as if declaring it; 39 /// if non-null, check this as if making a call to it with the given 40 /// receiver type 41 /// 42 /// \return true to indicate that there was an error and appropriate 43 /// actions were taken 44 bool Sema::checkInitMethod(ObjCMethodDecl *method, 45 QualType receiverTypeIfCall) { 46 if (method->isInvalidDecl()) return true; 47 48 // This castAs is safe: methods that don't return an object 49 // pointer won't be inferred as inits and will reject an explicit 50 // objc_method_family(init). 51 52 // We ignore protocols here. Should we? What about Class? 53 54 const ObjCObjectType *result = 55 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType(); 56 57 if (result->isObjCId()) { 58 return false; 59 } else if (result->isObjCClass()) { 60 // fall through: always an error 61 } else { 62 ObjCInterfaceDecl *resultClass = result->getInterface(); 63 assert(resultClass && "unexpected object type!"); 64 65 // It's okay for the result type to still be a forward declaration 66 // if we're checking an interface declaration. 67 if (!resultClass->hasDefinition()) { 68 if (receiverTypeIfCall.isNull() && 69 !isa<ObjCImplementationDecl>(method->getDeclContext())) 70 return false; 71 72 // Otherwise, we try to compare class types. 73 } else { 74 // If this method was declared in a protocol, we can't check 75 // anything unless we have a receiver type that's an interface. 76 const ObjCInterfaceDecl *receiverClass = nullptr; 77 if (isa<ObjCProtocolDecl>(method->getDeclContext())) { 78 if (receiverTypeIfCall.isNull()) 79 return false; 80 81 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>() 82 ->getInterfaceDecl(); 83 84 // This can be null for calls to e.g. id<Foo>. 85 if (!receiverClass) return false; 86 } else { 87 receiverClass = method->getClassInterface(); 88 assert(receiverClass && "method not associated with a class!"); 89 } 90 91 // If either class is a subclass of the other, it's fine. 92 if (receiverClass->isSuperClassOf(resultClass) || 93 resultClass->isSuperClassOf(receiverClass)) 94 return false; 95 } 96 } 97 98 SourceLocation loc = method->getLocation(); 99 100 // If we're in a system header, and this is not a call, just make 101 // the method unusable. 102 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) { 103 method->addAttr(UnavailableAttr::CreateImplicit(Context, "", 104 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc)); 105 return true; 106 } 107 108 // Otherwise, it's an error. 109 Diag(loc, diag::err_arc_init_method_unrelated_result_type); 110 method->setInvalidDecl(); 111 return true; 112 } 113 114 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 115 const ObjCMethodDecl *Overridden) { 116 if (Overridden->hasRelatedResultType() && 117 !NewMethod->hasRelatedResultType()) { 118 // This can only happen when the method follows a naming convention that 119 // implies a related result type, and the original (overridden) method has 120 // a suitable return type, but the new (overriding) method does not have 121 // a suitable return type. 122 QualType ResultType = NewMethod->getReturnType(); 123 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange(); 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_family) 155 << /*overridden method*/ 0 156 << Family; 157 else 158 Diag(Overridden->getLocation(), 159 diag::note_related_result_type_overridden); 160 } 161 if (getLangOpts().ObjCAutoRefCount) { 162 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() != 163 Overridden->hasAttr<NSReturnsRetainedAttr>())) { 164 Diag(NewMethod->getLocation(), 165 diag::err_nsreturns_retained_attribute_mismatch) << 1; 166 Diag(Overridden->getLocation(), diag::note_previous_decl) 167 << "method"; 168 } 169 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() != 170 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) { 171 Diag(NewMethod->getLocation(), 172 diag::err_nsreturns_retained_attribute_mismatch) << 0; 173 Diag(Overridden->getLocation(), diag::note_previous_decl) 174 << "method"; 175 } 176 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(), 177 oe = Overridden->param_end(); 178 for (ObjCMethodDecl::param_iterator 179 ni = NewMethod->param_begin(), ne = NewMethod->param_end(); 180 ni != ne && oi != oe; ++ni, ++oi) { 181 const ParmVarDecl *oldDecl = (*oi); 182 ParmVarDecl *newDecl = (*ni); 183 if (newDecl->hasAttr<NSConsumedAttr>() != 184 oldDecl->hasAttr<NSConsumedAttr>()) { 185 Diag(newDecl->getLocation(), 186 diag::err_nsconsumed_attribute_mismatch); 187 Diag(oldDecl->getLocation(), diag::note_previous_decl) 188 << "parameter"; 189 } 190 } 191 } 192 } 193 194 /// \brief Check a method declaration for compatibility with the Objective-C 195 /// ARC conventions. 196 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) { 197 ObjCMethodFamily family = method->getMethodFamily(); 198 switch (family) { 199 case OMF_None: 200 case OMF_finalize: 201 case OMF_retain: 202 case OMF_release: 203 case OMF_autorelease: 204 case OMF_retainCount: 205 case OMF_self: 206 case OMF_initialize: 207 case OMF_performSelector: 208 return false; 209 210 case OMF_dealloc: 211 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) { 212 SourceRange ResultTypeRange = method->getReturnTypeSourceRange(); 213 if (ResultTypeRange.isInvalid()) 214 Diag(method->getLocation(), diag::error_dealloc_bad_result_type) 215 << method->getReturnType() 216 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)"); 217 else 218 Diag(method->getLocation(), diag::error_dealloc_bad_result_type) 219 << method->getReturnType() 220 << FixItHint::CreateReplacement(ResultTypeRange, "void"); 221 return true; 222 } 223 return false; 224 225 case OMF_init: 226 // If the method doesn't obey the init rules, don't bother annotating it. 227 if (checkInitMethod(method, QualType())) 228 return true; 229 230 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context)); 231 232 // Don't add a second copy of this attribute, but otherwise don't 233 // let it be suppressed. 234 if (method->hasAttr<NSReturnsRetainedAttr>()) 235 return false; 236 break; 237 238 case OMF_alloc: 239 case OMF_copy: 240 case OMF_mutableCopy: 241 case OMF_new: 242 if (method->hasAttr<NSReturnsRetainedAttr>() || 243 method->hasAttr<NSReturnsNotRetainedAttr>() || 244 method->hasAttr<NSReturnsAutoreleasedAttr>()) 245 return false; 246 break; 247 } 248 249 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context)); 250 return false; 251 } 252 253 static void DiagnoseObjCImplementedDeprecations(Sema &S, 254 NamedDecl *ND, 255 SourceLocation ImplLoc, 256 int select) { 257 if (ND && ND->isDeprecated()) { 258 S.Diag(ImplLoc, diag::warn_deprecated_def) << select; 259 if (select == 0) 260 S.Diag(ND->getLocation(), diag::note_method_declared_at) 261 << ND->getDeclName(); 262 else 263 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class"; 264 } 265 } 266 267 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global 268 /// pool. 269 void Sema::AddAnyMethodToGlobalPool(Decl *D) { 270 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 271 272 // If we don't have a valid method decl, simply return. 273 if (!MDecl) 274 return; 275 if (MDecl->isInstanceMethod()) 276 AddInstanceMethodToGlobalPool(MDecl, true); 277 else 278 AddFactoryMethodToGlobalPool(MDecl, true); 279 } 280 281 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer 282 /// has explicit ownership attribute; false otherwise. 283 static bool 284 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) { 285 QualType T = Param->getType(); 286 287 if (const PointerType *PT = T->getAs<PointerType>()) { 288 T = PT->getPointeeType(); 289 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) { 290 T = RT->getPointeeType(); 291 } else { 292 return true; 293 } 294 295 // If we have a lifetime qualifier, but it's local, we must have 296 // inferred it. So, it is implicit. 297 return !T.getLocalQualifiers().hasObjCLifetime(); 298 } 299 300 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible 301 /// and user declared, in the method definition's AST. 302 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) { 303 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused"); 304 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D); 305 306 // If we don't have a valid method decl, simply return. 307 if (!MDecl) 308 return; 309 310 // Allow all of Sema to see that we are entering a method definition. 311 PushDeclContext(FnBodyScope, MDecl); 312 PushFunctionScope(); 313 314 // Create Decl objects for each parameter, entrring them in the scope for 315 // binding to their use. 316 317 // Insert the invisible arguments, self and _cmd! 318 MDecl->createImplicitParams(Context, MDecl->getClassInterface()); 319 320 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope); 321 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope); 322 323 // The ObjC parser requires parameter names so there's no need to check. 324 CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(), 325 /*CheckParameterNames=*/false); 326 327 // Introduce all of the other parameters into this scope. 328 for (auto *Param : MDecl->params()) { 329 if (!Param->isInvalidDecl() && 330 getLangOpts().ObjCAutoRefCount && 331 !HasExplicitOwnershipAttr(*this, Param)) 332 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) << 333 Param->getType(); 334 335 if (Param->getIdentifier()) 336 PushOnScopeChains(Param, FnBodyScope); 337 } 338 339 // In ARC, disallow definition of retain/release/autorelease/retainCount 340 if (getLangOpts().ObjCAutoRefCount) { 341 switch (MDecl->getMethodFamily()) { 342 case OMF_retain: 343 case OMF_retainCount: 344 case OMF_release: 345 case OMF_autorelease: 346 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def) 347 << 0 << MDecl->getSelector(); 348 break; 349 350 case OMF_None: 351 case OMF_dealloc: 352 case OMF_finalize: 353 case OMF_alloc: 354 case OMF_init: 355 case OMF_mutableCopy: 356 case OMF_copy: 357 case OMF_new: 358 case OMF_self: 359 case OMF_initialize: 360 case OMF_performSelector: 361 break; 362 } 363 } 364 365 // Warn on deprecated methods under -Wdeprecated-implementations, 366 // and prepare for warning on missing super calls. 367 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) { 368 ObjCMethodDecl *IMD = 369 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()); 370 371 if (IMD) { 372 ObjCImplDecl *ImplDeclOfMethodDef = 373 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext()); 374 ObjCContainerDecl *ContDeclOfMethodDecl = 375 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext()); 376 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr; 377 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl)) 378 ImplDeclOfMethodDecl = OID->getImplementation(); 379 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) { 380 if (CD->IsClassExtension()) { 381 if (ObjCInterfaceDecl *OID = CD->getClassInterface()) 382 ImplDeclOfMethodDecl = OID->getImplementation(); 383 } else 384 ImplDeclOfMethodDecl = CD->getImplementation(); 385 } 386 // No need to issue deprecated warning if deprecated mehod in class/category 387 // is being implemented in its own implementation (no overriding is involved). 388 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef) 389 DiagnoseObjCImplementedDeprecations(*this, 390 dyn_cast<NamedDecl>(IMD), 391 MDecl->getLocation(), 0); 392 } 393 394 if (MDecl->getMethodFamily() == OMF_init) { 395 if (MDecl->isDesignatedInitializerForTheInterface()) { 396 getCurFunction()->ObjCIsDesignatedInit = true; 397 getCurFunction()->ObjCWarnForNoDesignatedInitChain = 398 IC->getSuperClass() != nullptr; 399 } else if (IC->hasDesignatedInitializers()) { 400 getCurFunction()->ObjCIsSecondaryInit = true; 401 getCurFunction()->ObjCWarnForNoInitDelegation = true; 402 } 403 } 404 405 // If this is "dealloc" or "finalize", set some bit here. 406 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false. 407 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set. 408 // Only do this if the current class actually has a superclass. 409 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) { 410 ObjCMethodFamily Family = MDecl->getMethodFamily(); 411 if (Family == OMF_dealloc) { 412 if (!(getLangOpts().ObjCAutoRefCount || 413 getLangOpts().getGC() == LangOptions::GCOnly)) 414 getCurFunction()->ObjCShouldCallSuper = true; 415 416 } else if (Family == OMF_finalize) { 417 if (Context.getLangOpts().getGC() != LangOptions::NonGC) 418 getCurFunction()->ObjCShouldCallSuper = true; 419 420 } else { 421 const ObjCMethodDecl *SuperMethod = 422 SuperClass->lookupMethod(MDecl->getSelector(), 423 MDecl->isInstanceMethod()); 424 getCurFunction()->ObjCShouldCallSuper = 425 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>()); 426 } 427 } 428 } 429 } 430 431 namespace { 432 433 // Callback to only accept typo corrections that are Objective-C classes. 434 // If an ObjCInterfaceDecl* is given to the constructor, then the validation 435 // function will reject corrections to that class. 436 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback { 437 public: 438 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {} 439 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl) 440 : CurrentIDecl(IDecl) {} 441 442 bool ValidateCandidate(const TypoCorrection &candidate) override { 443 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>(); 444 return ID && !declaresSameEntity(ID, CurrentIDecl); 445 } 446 447 private: 448 ObjCInterfaceDecl *CurrentIDecl; 449 }; 450 451 } // end anonymous namespace 452 453 static void diagnoseUseOfProtocols(Sema &TheSema, 454 ObjCContainerDecl *CD, 455 ObjCProtocolDecl *const *ProtoRefs, 456 unsigned NumProtoRefs, 457 const SourceLocation *ProtoLocs) { 458 assert(ProtoRefs); 459 // Diagnose availability in the context of the ObjC container. 460 Sema::ContextRAII SavedContext(TheSema, CD); 461 for (unsigned i = 0; i < NumProtoRefs; ++i) { 462 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i]); 463 } 464 } 465 466 void Sema:: 467 ActOnSuperClassOfClassInterface(Scope *S, 468 SourceLocation AtInterfaceLoc, 469 ObjCInterfaceDecl *IDecl, 470 IdentifierInfo *ClassName, 471 SourceLocation ClassLoc, 472 IdentifierInfo *SuperName, 473 SourceLocation SuperLoc, 474 ArrayRef<ParsedType> SuperTypeArgs, 475 SourceRange SuperTypeArgsRange) { 476 // Check if a different kind of symbol declared in this scope. 477 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc, 478 LookupOrdinaryName); 479 480 if (!PrevDecl) { 481 // Try to correct for a typo in the superclass name without correcting 482 // to the class we're defining. 483 if (TypoCorrection Corrected = CorrectTypo( 484 DeclarationNameInfo(SuperName, SuperLoc), 485 LookupOrdinaryName, TUScope, 486 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl), 487 CTK_ErrorRecovery)) { 488 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest) 489 << SuperName << ClassName); 490 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>(); 491 } 492 } 493 494 if (declaresSameEntity(PrevDecl, IDecl)) { 495 Diag(SuperLoc, diag::err_recursive_superclass) 496 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 497 IDecl->setEndOfDefinitionLoc(ClassLoc); 498 } else { 499 ObjCInterfaceDecl *SuperClassDecl = 500 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 501 QualType SuperClassType; 502 503 // Diagnose classes that inherit from deprecated classes. 504 if (SuperClassDecl) { 505 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc); 506 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl); 507 } 508 509 if (PrevDecl && !SuperClassDecl) { 510 // The previous declaration was not a class decl. Check if we have a 511 // typedef. If we do, get the underlying class type. 512 if (const TypedefNameDecl *TDecl = 513 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 514 QualType T = TDecl->getUnderlyingType(); 515 if (T->isObjCObjectType()) { 516 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) { 517 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl); 518 SuperClassType = Context.getTypeDeclType(TDecl); 519 520 // This handles the following case: 521 // @interface NewI @end 522 // typedef NewI DeprI __attribute__((deprecated("blah"))) 523 // @interface SI : DeprI /* warn here */ @end 524 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc); 525 } 526 } 527 } 528 529 // This handles the following case: 530 // 531 // typedef int SuperClass; 532 // @interface MyClass : SuperClass {} @end 533 // 534 if (!SuperClassDecl) { 535 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName; 536 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 537 } 538 } 539 540 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) { 541 if (!SuperClassDecl) 542 Diag(SuperLoc, diag::err_undef_superclass) 543 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc); 544 else if (RequireCompleteType(SuperLoc, 545 SuperClassType, 546 diag::err_forward_superclass, 547 SuperClassDecl->getDeclName(), 548 ClassName, 549 SourceRange(AtInterfaceLoc, ClassLoc))) { 550 SuperClassDecl = nullptr; 551 SuperClassType = QualType(); 552 } 553 } 554 555 if (SuperClassType.isNull()) { 556 assert(!SuperClassDecl && "Failed to set SuperClassType?"); 557 return; 558 } 559 560 // Handle type arguments on the superclass. 561 TypeSourceInfo *SuperClassTInfo = nullptr; 562 if (!SuperTypeArgs.empty()) { 563 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers( 564 S, 565 SuperLoc, 566 CreateParsedType(SuperClassType, 567 nullptr), 568 SuperTypeArgsRange.getBegin(), 569 SuperTypeArgs, 570 SuperTypeArgsRange.getEnd(), 571 SourceLocation(), 572 { }, 573 { }, 574 SourceLocation()); 575 if (!fullSuperClassType.isUsable()) 576 return; 577 578 SuperClassType = GetTypeFromParser(fullSuperClassType.get(), 579 &SuperClassTInfo); 580 } 581 582 if (!SuperClassTInfo) { 583 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType, 584 SuperLoc); 585 } 586 587 IDecl->setSuperClass(SuperClassTInfo); 588 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getLocEnd()); 589 } 590 } 591 592 DeclResult Sema::actOnObjCTypeParam(Scope *S, 593 ObjCTypeParamVariance variance, 594 SourceLocation varianceLoc, 595 unsigned index, 596 IdentifierInfo *paramName, 597 SourceLocation paramLoc, 598 SourceLocation colonLoc, 599 ParsedType parsedTypeBound) { 600 // If there was an explicitly-provided type bound, check it. 601 TypeSourceInfo *typeBoundInfo = nullptr; 602 if (parsedTypeBound) { 603 // The type bound can be any Objective-C pointer type. 604 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo); 605 if (typeBound->isObjCObjectPointerType()) { 606 // okay 607 } else if (typeBound->isObjCObjectType()) { 608 // The user forgot the * on an Objective-C pointer type, e.g., 609 // "T : NSView". 610 SourceLocation starLoc = PP.getLocForEndOfToken( 611 typeBoundInfo->getTypeLoc().getEndLoc()); 612 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(), 613 diag::err_objc_type_param_bound_missing_pointer) 614 << typeBound << paramName 615 << FixItHint::CreateInsertion(starLoc, " *"); 616 617 // Create a new type location builder so we can update the type 618 // location information we have. 619 TypeLocBuilder builder; 620 builder.pushFullCopy(typeBoundInfo->getTypeLoc()); 621 622 // Create the Objective-C pointer type. 623 typeBound = Context.getObjCObjectPointerType(typeBound); 624 ObjCObjectPointerTypeLoc newT 625 = builder.push<ObjCObjectPointerTypeLoc>(typeBound); 626 newT.setStarLoc(starLoc); 627 628 // Form the new type source information. 629 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound); 630 } else { 631 // Not a valid type bound. 632 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(), 633 diag::err_objc_type_param_bound_nonobject) 634 << typeBound << paramName; 635 636 // Forget the bound; we'll default to id later. 637 typeBoundInfo = nullptr; 638 } 639 640 // Type bounds cannot have qualifiers (even indirectly) or explicit 641 // nullability. 642 if (typeBoundInfo) { 643 QualType typeBound = typeBoundInfo->getType(); 644 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc(); 645 if (qual || typeBound.hasQualifiers()) { 646 bool diagnosed = false; 647 SourceRange rangeToRemove; 648 if (qual) { 649 if (auto attr = qual.getAs<AttributedTypeLoc>()) { 650 rangeToRemove = attr.getLocalSourceRange(); 651 if (attr.getTypePtr()->getImmediateNullability()) { 652 Diag(attr.getLocStart(), 653 diag::err_objc_type_param_bound_explicit_nullability) 654 << paramName << typeBound 655 << FixItHint::CreateRemoval(rangeToRemove); 656 diagnosed = true; 657 } 658 } 659 } 660 661 if (!diagnosed) { 662 Diag(qual ? qual.getLocStart() 663 : typeBoundInfo->getTypeLoc().getLocStart(), 664 diag::err_objc_type_param_bound_qualified) 665 << paramName << typeBound << typeBound.getQualifiers().getAsString() 666 << FixItHint::CreateRemoval(rangeToRemove); 667 } 668 669 // If the type bound has qualifiers other than CVR, we need to strip 670 // them or we'll probably assert later when trying to apply new 671 // qualifiers. 672 Qualifiers quals = typeBound.getQualifiers(); 673 quals.removeCVRQualifiers(); 674 if (!quals.empty()) { 675 typeBoundInfo = 676 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType()); 677 } 678 } 679 } 680 } 681 682 // If there was no explicit type bound (or we removed it due to an error), 683 // use 'id' instead. 684 if (!typeBoundInfo) { 685 colonLoc = SourceLocation(); 686 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType()); 687 } 688 689 // Create the type parameter. 690 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc, 691 index, paramLoc, paramName, colonLoc, 692 typeBoundInfo); 693 } 694 695 ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S, 696 SourceLocation lAngleLoc, 697 ArrayRef<Decl *> typeParamsIn, 698 SourceLocation rAngleLoc) { 699 // We know that the array only contains Objective-C type parameters. 700 ArrayRef<ObjCTypeParamDecl *> 701 typeParams( 702 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()), 703 typeParamsIn.size()); 704 705 // Diagnose redeclarations of type parameters. 706 // We do this now because Objective-C type parameters aren't pushed into 707 // scope until later (after the instance variable block), but we want the 708 // diagnostics to occur right after we parse the type parameter list. 709 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams; 710 for (auto typeParam : typeParams) { 711 auto known = knownParams.find(typeParam->getIdentifier()); 712 if (known != knownParams.end()) { 713 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl) 714 << typeParam->getIdentifier() 715 << SourceRange(known->second->getLocation()); 716 717 typeParam->setInvalidDecl(); 718 } else { 719 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam)); 720 721 // Push the type parameter into scope. 722 PushOnScopeChains(typeParam, S, /*AddToContext=*/false); 723 } 724 } 725 726 // Create the parameter list. 727 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc); 728 } 729 730 void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) { 731 for (auto typeParam : *typeParamList) { 732 if (!typeParam->isInvalidDecl()) { 733 S->RemoveDecl(typeParam); 734 IdResolver.RemoveDecl(typeParam); 735 } 736 } 737 } 738 739 namespace { 740 /// The context in which an Objective-C type parameter list occurs, for use 741 /// in diagnostics. 742 enum class TypeParamListContext { 743 ForwardDeclaration, 744 Definition, 745 Category, 746 Extension 747 }; 748 } // end anonymous namespace 749 750 /// Check consistency between two Objective-C type parameter lists, e.g., 751 /// between a category/extension and an \@interface or between an \@class and an 752 /// \@interface. 753 static bool checkTypeParamListConsistency(Sema &S, 754 ObjCTypeParamList *prevTypeParams, 755 ObjCTypeParamList *newTypeParams, 756 TypeParamListContext newContext) { 757 // If the sizes don't match, complain about that. 758 if (prevTypeParams->size() != newTypeParams->size()) { 759 SourceLocation diagLoc; 760 if (newTypeParams->size() > prevTypeParams->size()) { 761 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation(); 762 } else { 763 diagLoc = S.PP.getLocForEndOfToken(newTypeParams->back()->getLocEnd()); 764 } 765 766 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch) 767 << static_cast<unsigned>(newContext) 768 << (newTypeParams->size() > prevTypeParams->size()) 769 << prevTypeParams->size() 770 << newTypeParams->size(); 771 772 return true; 773 } 774 775 // Match up the type parameters. 776 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) { 777 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i]; 778 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i]; 779 780 // Check for consistency of the variance. 781 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) { 782 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant && 783 newContext != TypeParamListContext::Definition) { 784 // When the new type parameter is invariant and is not part 785 // of the definition, just propagate the variance. 786 newTypeParam->setVariance(prevTypeParam->getVariance()); 787 } else if (prevTypeParam->getVariance() 788 == ObjCTypeParamVariance::Invariant && 789 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) && 790 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) 791 ->getDefinition() == prevTypeParam->getDeclContext())) { 792 // When the old parameter is invariant and was not part of the 793 // definition, just ignore the difference because it doesn't 794 // matter. 795 } else { 796 { 797 // Diagnose the conflict and update the second declaration. 798 SourceLocation diagLoc = newTypeParam->getVarianceLoc(); 799 if (diagLoc.isInvalid()) 800 diagLoc = newTypeParam->getLocStart(); 801 802 auto diag = S.Diag(diagLoc, 803 diag::err_objc_type_param_variance_conflict) 804 << static_cast<unsigned>(newTypeParam->getVariance()) 805 << newTypeParam->getDeclName() 806 << static_cast<unsigned>(prevTypeParam->getVariance()) 807 << prevTypeParam->getDeclName(); 808 switch (prevTypeParam->getVariance()) { 809 case ObjCTypeParamVariance::Invariant: 810 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc()); 811 break; 812 813 case ObjCTypeParamVariance::Covariant: 814 case ObjCTypeParamVariance::Contravariant: { 815 StringRef newVarianceStr 816 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant 817 ? "__covariant" 818 : "__contravariant"; 819 if (newTypeParam->getVariance() 820 == ObjCTypeParamVariance::Invariant) { 821 diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(), 822 (newVarianceStr + " ").str()); 823 } else { 824 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(), 825 newVarianceStr); 826 } 827 } 828 } 829 } 830 831 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here) 832 << prevTypeParam->getDeclName(); 833 834 // Override the variance. 835 newTypeParam->setVariance(prevTypeParam->getVariance()); 836 } 837 } 838 839 // If the bound types match, there's nothing to do. 840 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(), 841 newTypeParam->getUnderlyingType())) 842 continue; 843 844 // If the new type parameter's bound was explicit, complain about it being 845 // different from the original. 846 if (newTypeParam->hasExplicitBound()) { 847 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo() 848 ->getTypeLoc().getSourceRange(); 849 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict) 850 << newTypeParam->getUnderlyingType() 851 << newTypeParam->getDeclName() 852 << prevTypeParam->hasExplicitBound() 853 << prevTypeParam->getUnderlyingType() 854 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName()) 855 << prevTypeParam->getDeclName() 856 << FixItHint::CreateReplacement( 857 newBoundRange, 858 prevTypeParam->getUnderlyingType().getAsString( 859 S.Context.getPrintingPolicy())); 860 861 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here) 862 << prevTypeParam->getDeclName(); 863 864 // Override the new type parameter's bound type with the previous type, 865 // so that it's consistent. 866 newTypeParam->setTypeSourceInfo( 867 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType())); 868 continue; 869 } 870 871 // The new type parameter got the implicit bound of 'id'. That's okay for 872 // categories and extensions (overwrite it later), but not for forward 873 // declarations and @interfaces, because those must be standalone. 874 if (newContext == TypeParamListContext::ForwardDeclaration || 875 newContext == TypeParamListContext::Definition) { 876 // Diagnose this problem for forward declarations and definitions. 877 SourceLocation insertionLoc 878 = S.PP.getLocForEndOfToken(newTypeParam->getLocation()); 879 std::string newCode 880 = " : " + prevTypeParam->getUnderlyingType().getAsString( 881 S.Context.getPrintingPolicy()); 882 S.Diag(newTypeParam->getLocation(), 883 diag::err_objc_type_param_bound_missing) 884 << prevTypeParam->getUnderlyingType() 885 << newTypeParam->getDeclName() 886 << (newContext == TypeParamListContext::ForwardDeclaration) 887 << FixItHint::CreateInsertion(insertionLoc, newCode); 888 889 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here) 890 << prevTypeParam->getDeclName(); 891 } 892 893 // Update the new type parameter's bound to match the previous one. 894 newTypeParam->setTypeSourceInfo( 895 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType())); 896 } 897 898 return false; 899 } 900 901 Decl *Sema:: 902 ActOnStartClassInterface(Scope *S, SourceLocation AtInterfaceLoc, 903 IdentifierInfo *ClassName, SourceLocation ClassLoc, 904 ObjCTypeParamList *typeParamList, 905 IdentifierInfo *SuperName, SourceLocation SuperLoc, 906 ArrayRef<ParsedType> SuperTypeArgs, 907 SourceRange SuperTypeArgsRange, 908 Decl * const *ProtoRefs, unsigned NumProtoRefs, 909 const SourceLocation *ProtoLocs, 910 SourceLocation EndProtoLoc, AttributeList *AttrList) { 911 assert(ClassName && "Missing class identifier"); 912 913 // Check for another declaration kind with the same name. 914 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc, 915 LookupOrdinaryName, ForRedeclaration); 916 917 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 918 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 919 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 920 } 921 922 // Create a declaration to describe this @interface. 923 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 924 925 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 926 // A previous decl with a different name is because of 927 // @compatibility_alias, for example: 928 // \code 929 // @class NewImage; 930 // @compatibility_alias OldImage NewImage; 931 // \endcode 932 // A lookup for 'OldImage' will return the 'NewImage' decl. 933 // 934 // In such a case use the real declaration name, instead of the alias one, 935 // otherwise we will break IdentifierResolver and redecls-chain invariants. 936 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 937 // has been aliased. 938 ClassName = PrevIDecl->getIdentifier(); 939 } 940 941 // If there was a forward declaration with type parameters, check 942 // for consistency. 943 if (PrevIDecl) { 944 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) { 945 if (typeParamList) { 946 // Both have type parameter lists; check for consistency. 947 if (checkTypeParamListConsistency(*this, prevTypeParamList, 948 typeParamList, 949 TypeParamListContext::Definition)) { 950 typeParamList = nullptr; 951 } 952 } else { 953 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first) 954 << ClassName; 955 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl) 956 << ClassName; 957 958 // Clone the type parameter list. 959 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams; 960 for (auto typeParam : *prevTypeParamList) { 961 clonedTypeParams.push_back( 962 ObjCTypeParamDecl::Create( 963 Context, 964 CurContext, 965 typeParam->getVariance(), 966 SourceLocation(), 967 typeParam->getIndex(), 968 SourceLocation(), 969 typeParam->getIdentifier(), 970 SourceLocation(), 971 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType()))); 972 } 973 974 typeParamList = ObjCTypeParamList::create(Context, 975 SourceLocation(), 976 clonedTypeParams, 977 SourceLocation()); 978 } 979 } 980 } 981 982 ObjCInterfaceDecl *IDecl 983 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName, 984 typeParamList, PrevIDecl, ClassLoc); 985 if (PrevIDecl) { 986 // Class already seen. Was it a definition? 987 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) { 988 Diag(AtInterfaceLoc, diag::err_duplicate_class_def) 989 << PrevIDecl->getDeclName(); 990 Diag(Def->getLocation(), diag::note_previous_definition); 991 IDecl->setInvalidDecl(); 992 } 993 } 994 995 if (AttrList) 996 ProcessDeclAttributeList(TUScope, IDecl, AttrList); 997 PushOnScopeChains(IDecl, TUScope); 998 999 // Start the definition of this class. If we're in a redefinition case, there 1000 // may already be a definition, so we'll end up adding to it. 1001 if (!IDecl->hasDefinition()) 1002 IDecl->startDefinition(); 1003 1004 if (SuperName) { 1005 // Diagnose availability in the context of the @interface. 1006 ContextRAII SavedContext(*this, IDecl); 1007 1008 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl, 1009 ClassName, ClassLoc, 1010 SuperName, SuperLoc, SuperTypeArgs, 1011 SuperTypeArgsRange); 1012 } else { // we have a root class. 1013 IDecl->setEndOfDefinitionLoc(ClassLoc); 1014 } 1015 1016 // Check then save referenced protocols. 1017 if (NumProtoRefs) { 1018 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs, 1019 NumProtoRefs, ProtoLocs); 1020 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 1021 ProtoLocs, Context); 1022 IDecl->setEndOfDefinitionLoc(EndProtoLoc); 1023 } 1024 1025 CheckObjCDeclScope(IDecl); 1026 return ActOnObjCContainerStartDefinition(IDecl); 1027 } 1028 1029 /// ActOnTypedefedProtocols - this action finds protocol list as part of the 1030 /// typedef'ed use for a qualified super class and adds them to the list 1031 /// of the protocols. 1032 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, 1033 IdentifierInfo *SuperName, 1034 SourceLocation SuperLoc) { 1035 if (!SuperName) 1036 return; 1037 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc, 1038 LookupOrdinaryName); 1039 if (!IDecl) 1040 return; 1041 1042 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) { 1043 QualType T = TDecl->getUnderlyingType(); 1044 if (T->isObjCObjectType()) 1045 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) 1046 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end()); 1047 } 1048 } 1049 1050 /// ActOnCompatibilityAlias - this action is called after complete parsing of 1051 /// a \@compatibility_alias declaration. It sets up the alias relationships. 1052 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc, 1053 IdentifierInfo *AliasName, 1054 SourceLocation AliasLocation, 1055 IdentifierInfo *ClassName, 1056 SourceLocation ClassLocation) { 1057 // Look for previous declaration of alias name 1058 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation, 1059 LookupOrdinaryName, ForRedeclaration); 1060 if (ADecl) { 1061 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName; 1062 Diag(ADecl->getLocation(), diag::note_previous_declaration); 1063 return nullptr; 1064 } 1065 // Check for class declaration 1066 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation, 1067 LookupOrdinaryName, ForRedeclaration); 1068 if (const TypedefNameDecl *TDecl = 1069 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) { 1070 QualType T = TDecl->getUnderlyingType(); 1071 if (T->isObjCObjectType()) { 1072 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) { 1073 ClassName = IDecl->getIdentifier(); 1074 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation, 1075 LookupOrdinaryName, ForRedeclaration); 1076 } 1077 } 1078 } 1079 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU); 1080 if (!CDecl) { 1081 Diag(ClassLocation, diag::warn_undef_interface) << ClassName; 1082 if (CDeclU) 1083 Diag(CDeclU->getLocation(), diag::note_previous_declaration); 1084 return nullptr; 1085 } 1086 1087 // Everything checked out, instantiate a new alias declaration AST. 1088 ObjCCompatibleAliasDecl *AliasDecl = 1089 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl); 1090 1091 if (!CheckObjCDeclScope(AliasDecl)) 1092 PushOnScopeChains(AliasDecl, TUScope); 1093 1094 return AliasDecl; 1095 } 1096 1097 bool Sema::CheckForwardProtocolDeclarationForCircularDependency( 1098 IdentifierInfo *PName, 1099 SourceLocation &Ploc, SourceLocation PrevLoc, 1100 const ObjCList<ObjCProtocolDecl> &PList) { 1101 1102 bool res = false; 1103 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(), 1104 E = PList.end(); I != E; ++I) { 1105 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(), 1106 Ploc)) { 1107 if (PDecl->getIdentifier() == PName) { 1108 Diag(Ploc, diag::err_protocol_has_circular_dependency); 1109 Diag(PrevLoc, diag::note_previous_definition); 1110 res = true; 1111 } 1112 1113 if (!PDecl->hasDefinition()) 1114 continue; 1115 1116 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc, 1117 PDecl->getLocation(), PDecl->getReferencedProtocols())) 1118 res = true; 1119 } 1120 } 1121 return res; 1122 } 1123 1124 Decl * 1125 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc, 1126 IdentifierInfo *ProtocolName, 1127 SourceLocation ProtocolLoc, 1128 Decl * const *ProtoRefs, 1129 unsigned NumProtoRefs, 1130 const SourceLocation *ProtoLocs, 1131 SourceLocation EndProtoLoc, 1132 AttributeList *AttrList) { 1133 bool err = false; 1134 // FIXME: Deal with AttrList. 1135 assert(ProtocolName && "Missing protocol identifier"); 1136 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc, 1137 ForRedeclaration); 1138 ObjCProtocolDecl *PDecl = nullptr; 1139 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) { 1140 // If we already have a definition, complain. 1141 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName; 1142 Diag(Def->getLocation(), diag::note_previous_definition); 1143 1144 // Create a new protocol that is completely distinct from previous 1145 // declarations, and do not make this protocol available for name lookup. 1146 // That way, we'll end up completely ignoring the duplicate. 1147 // FIXME: Can we turn this into an error? 1148 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, 1149 ProtocolLoc, AtProtoInterfaceLoc, 1150 /*PrevDecl=*/nullptr); 1151 PDecl->startDefinition(); 1152 } else { 1153 if (PrevDecl) { 1154 // Check for circular dependencies among protocol declarations. This can 1155 // only happen if this protocol was forward-declared. 1156 ObjCList<ObjCProtocolDecl> PList; 1157 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context); 1158 err = CheckForwardProtocolDeclarationForCircularDependency( 1159 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList); 1160 } 1161 1162 // Create the new declaration. 1163 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName, 1164 ProtocolLoc, AtProtoInterfaceLoc, 1165 /*PrevDecl=*/PrevDecl); 1166 1167 PushOnScopeChains(PDecl, TUScope); 1168 PDecl->startDefinition(); 1169 } 1170 1171 if (AttrList) 1172 ProcessDeclAttributeList(TUScope, PDecl, AttrList); 1173 1174 // Merge attributes from previous declarations. 1175 if (PrevDecl) 1176 mergeDeclAttributes(PDecl, PrevDecl); 1177 1178 if (!err && NumProtoRefs ) { 1179 /// Check then save referenced protocols. 1180 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs, 1181 NumProtoRefs, ProtoLocs); 1182 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 1183 ProtoLocs, Context); 1184 } 1185 1186 CheckObjCDeclScope(PDecl); 1187 return ActOnObjCContainerStartDefinition(PDecl); 1188 } 1189 1190 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl, 1191 ObjCProtocolDecl *&UndefinedProtocol) { 1192 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) { 1193 UndefinedProtocol = PDecl; 1194 return true; 1195 } 1196 1197 for (auto *PI : PDecl->protocols()) 1198 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) { 1199 UndefinedProtocol = PI; 1200 return true; 1201 } 1202 return false; 1203 } 1204 1205 /// FindProtocolDeclaration - This routine looks up protocols and 1206 /// issues an error if they are not declared. It returns list of 1207 /// protocol declarations in its 'Protocols' argument. 1208 void 1209 Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, 1210 ArrayRef<IdentifierLocPair> ProtocolId, 1211 SmallVectorImpl<Decl *> &Protocols) { 1212 for (const IdentifierLocPair &Pair : ProtocolId) { 1213 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second); 1214 if (!PDecl) { 1215 TypoCorrection Corrected = CorrectTypo( 1216 DeclarationNameInfo(Pair.first, Pair.second), 1217 LookupObjCProtocolName, TUScope, nullptr, 1218 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(), 1219 CTK_ErrorRecovery); 1220 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) 1221 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest) 1222 << Pair.first); 1223 } 1224 1225 if (!PDecl) { 1226 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first; 1227 continue; 1228 } 1229 // If this is a forward protocol declaration, get its definition. 1230 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition()) 1231 PDecl = PDecl->getDefinition(); 1232 1233 // For an objc container, delay protocol reference checking until after we 1234 // can set the objc decl as the availability context, otherwise check now. 1235 if (!ForObjCContainer) { 1236 (void)DiagnoseUseOfDecl(PDecl, Pair.second); 1237 } 1238 1239 // If this is a forward declaration and we are supposed to warn in this 1240 // case, do it. 1241 // FIXME: Recover nicely in the hidden case. 1242 ObjCProtocolDecl *UndefinedProtocol; 1243 1244 if (WarnOnDeclarations && 1245 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) { 1246 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first; 1247 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined) 1248 << UndefinedProtocol; 1249 } 1250 Protocols.push_back(PDecl); 1251 } 1252 } 1253 1254 namespace { 1255 // Callback to only accept typo corrections that are either 1256 // Objective-C protocols or valid Objective-C type arguments. 1257 class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback { 1258 ASTContext &Context; 1259 Sema::LookupNameKind LookupKind; 1260 public: 1261 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context, 1262 Sema::LookupNameKind lookupKind) 1263 : Context(context), LookupKind(lookupKind) { } 1264 1265 bool ValidateCandidate(const TypoCorrection &candidate) override { 1266 // If we're allowed to find protocols and we have a protocol, accept it. 1267 if (LookupKind != Sema::LookupOrdinaryName) { 1268 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>()) 1269 return true; 1270 } 1271 1272 // If we're allowed to find type names and we have one, accept it. 1273 if (LookupKind != Sema::LookupObjCProtocolName) { 1274 // If we have a type declaration, we might accept this result. 1275 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) { 1276 // If we found a tag declaration outside of C++, skip it. This 1277 // can happy because we look for any name when there is no 1278 // bias to protocol or type names. 1279 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus) 1280 return false; 1281 1282 // Make sure the type is something we would accept as a type 1283 // argument. 1284 auto type = Context.getTypeDeclType(typeDecl); 1285 if (type->isObjCObjectPointerType() || 1286 type->isBlockPointerType() || 1287 type->isDependentType() || 1288 type->isObjCObjectType()) 1289 return true; 1290 1291 return false; 1292 } 1293 1294 // If we have an Objective-C class type, accept it; there will 1295 // be another fix to add the '*'. 1296 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>()) 1297 return true; 1298 1299 return false; 1300 } 1301 1302 return false; 1303 } 1304 }; 1305 } // end anonymous namespace 1306 1307 void Sema::actOnObjCTypeArgsOrProtocolQualifiers( 1308 Scope *S, 1309 ParsedType baseType, 1310 SourceLocation lAngleLoc, 1311 ArrayRef<IdentifierInfo *> identifiers, 1312 ArrayRef<SourceLocation> identifierLocs, 1313 SourceLocation rAngleLoc, 1314 SourceLocation &typeArgsLAngleLoc, 1315 SmallVectorImpl<ParsedType> &typeArgs, 1316 SourceLocation &typeArgsRAngleLoc, 1317 SourceLocation &protocolLAngleLoc, 1318 SmallVectorImpl<Decl *> &protocols, 1319 SourceLocation &protocolRAngleLoc, 1320 bool warnOnIncompleteProtocols) { 1321 // Local function that updates the declaration specifiers with 1322 // protocol information. 1323 unsigned numProtocolsResolved = 0; 1324 auto resolvedAsProtocols = [&] { 1325 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols"); 1326 1327 // Determine whether the base type is a parameterized class, in 1328 // which case we want to warn about typos such as 1329 // "NSArray<NSObject>" (that should be NSArray<NSObject *>). 1330 ObjCInterfaceDecl *baseClass = nullptr; 1331 QualType base = GetTypeFromParser(baseType, nullptr); 1332 bool allAreTypeNames = false; 1333 SourceLocation firstClassNameLoc; 1334 if (!base.isNull()) { 1335 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) { 1336 baseClass = objcObjectType->getInterface(); 1337 if (baseClass) { 1338 if (auto typeParams = baseClass->getTypeParamList()) { 1339 if (typeParams->size() == numProtocolsResolved) { 1340 // Note that we should be looking for type names, too. 1341 allAreTypeNames = true; 1342 } 1343 } 1344 } 1345 } 1346 } 1347 1348 for (unsigned i = 0, n = protocols.size(); i != n; ++i) { 1349 ObjCProtocolDecl *&proto 1350 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]); 1351 // For an objc container, delay protocol reference checking until after we 1352 // can set the objc decl as the availability context, otherwise check now. 1353 if (!warnOnIncompleteProtocols) { 1354 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]); 1355 } 1356 1357 // If this is a forward protocol declaration, get its definition. 1358 if (!proto->isThisDeclarationADefinition() && proto->getDefinition()) 1359 proto = proto->getDefinition(); 1360 1361 // If this is a forward declaration and we are supposed to warn in this 1362 // case, do it. 1363 // FIXME: Recover nicely in the hidden case. 1364 ObjCProtocolDecl *forwardDecl = nullptr; 1365 if (warnOnIncompleteProtocols && 1366 NestedProtocolHasNoDefinition(proto, forwardDecl)) { 1367 Diag(identifierLocs[i], diag::warn_undef_protocolref) 1368 << proto->getDeclName(); 1369 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined) 1370 << forwardDecl; 1371 } 1372 1373 // If everything this far has been a type name (and we care 1374 // about such things), check whether this name refers to a type 1375 // as well. 1376 if (allAreTypeNames) { 1377 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i], 1378 LookupOrdinaryName)) { 1379 if (isa<ObjCInterfaceDecl>(decl)) { 1380 if (firstClassNameLoc.isInvalid()) 1381 firstClassNameLoc = identifierLocs[i]; 1382 } else if (!isa<TypeDecl>(decl)) { 1383 // Not a type. 1384 allAreTypeNames = false; 1385 } 1386 } else { 1387 allAreTypeNames = false; 1388 } 1389 } 1390 } 1391 1392 // All of the protocols listed also have type names, and at least 1393 // one is an Objective-C class name. Check whether all of the 1394 // protocol conformances are declared by the base class itself, in 1395 // which case we warn. 1396 if (allAreTypeNames && firstClassNameLoc.isValid()) { 1397 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols; 1398 Context.CollectInheritedProtocols(baseClass, knownProtocols); 1399 bool allProtocolsDeclared = true; 1400 for (auto proto : protocols) { 1401 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) { 1402 allProtocolsDeclared = false; 1403 break; 1404 } 1405 } 1406 1407 if (allProtocolsDeclared) { 1408 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type) 1409 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc) 1410 << FixItHint::CreateInsertion( 1411 PP.getLocForEndOfToken(firstClassNameLoc), " *"); 1412 } 1413 } 1414 1415 protocolLAngleLoc = lAngleLoc; 1416 protocolRAngleLoc = rAngleLoc; 1417 assert(protocols.size() == identifierLocs.size()); 1418 }; 1419 1420 // Attempt to resolve all of the identifiers as protocols. 1421 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1422 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]); 1423 protocols.push_back(proto); 1424 if (proto) 1425 ++numProtocolsResolved; 1426 } 1427 1428 // If all of the names were protocols, these were protocol qualifiers. 1429 if (numProtocolsResolved == identifiers.size()) 1430 return resolvedAsProtocols(); 1431 1432 // Attempt to resolve all of the identifiers as type names or 1433 // Objective-C class names. The latter is technically ill-formed, 1434 // but is probably something like \c NSArray<NSView *> missing the 1435 // \c*. 1436 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl; 1437 SmallVector<TypeOrClassDecl, 4> typeDecls; 1438 unsigned numTypeDeclsResolved = 0; 1439 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1440 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i], 1441 LookupOrdinaryName); 1442 if (!decl) { 1443 typeDecls.push_back(TypeOrClassDecl()); 1444 continue; 1445 } 1446 1447 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) { 1448 typeDecls.push_back(typeDecl); 1449 ++numTypeDeclsResolved; 1450 continue; 1451 } 1452 1453 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) { 1454 typeDecls.push_back(objcClass); 1455 ++numTypeDeclsResolved; 1456 continue; 1457 } 1458 1459 typeDecls.push_back(TypeOrClassDecl()); 1460 } 1461 1462 AttributeFactory attrFactory; 1463 1464 // Local function that forms a reference to the given type or 1465 // Objective-C class declaration. 1466 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc) 1467 -> TypeResult { 1468 // Form declaration specifiers. They simply refer to the type. 1469 DeclSpec DS(attrFactory); 1470 const char* prevSpec; // unused 1471 unsigned diagID; // unused 1472 QualType type; 1473 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>()) 1474 type = Context.getTypeDeclType(actualTypeDecl); 1475 else 1476 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>()); 1477 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc); 1478 ParsedType parsedType = CreateParsedType(type, parsedTSInfo); 1479 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID, 1480 parsedType, Context.getPrintingPolicy()); 1481 // Use the identifier location for the type source range. 1482 DS.SetRangeStart(loc); 1483 DS.SetRangeEnd(loc); 1484 1485 // Form the declarator. 1486 Declarator D(DS, Declarator::TypeNameContext); 1487 1488 // If we have a typedef of an Objective-C class type that is missing a '*', 1489 // add the '*'. 1490 if (type->getAs<ObjCInterfaceType>()) { 1491 SourceLocation starLoc = PP.getLocForEndOfToken(loc); 1492 ParsedAttributes parsedAttrs(attrFactory); 1493 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc, 1494 SourceLocation(), 1495 SourceLocation(), 1496 SourceLocation(), 1497 SourceLocation()), 1498 parsedAttrs, 1499 starLoc); 1500 1501 // Diagnose the missing '*'. 1502 Diag(loc, diag::err_objc_type_arg_missing_star) 1503 << type 1504 << FixItHint::CreateInsertion(starLoc, " *"); 1505 } 1506 1507 // Convert this to a type. 1508 return ActOnTypeName(S, D); 1509 }; 1510 1511 // Local function that updates the declaration specifiers with 1512 // type argument information. 1513 auto resolvedAsTypeDecls = [&] { 1514 // We did not resolve these as protocols. 1515 protocols.clear(); 1516 1517 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl"); 1518 // Map type declarations to type arguments. 1519 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1520 // Map type reference to a type. 1521 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]); 1522 if (!type.isUsable()) { 1523 typeArgs.clear(); 1524 return; 1525 } 1526 1527 typeArgs.push_back(type.get()); 1528 } 1529 1530 typeArgsLAngleLoc = lAngleLoc; 1531 typeArgsRAngleLoc = rAngleLoc; 1532 }; 1533 1534 // If all of the identifiers can be resolved as type names or 1535 // Objective-C class names, we have type arguments. 1536 if (numTypeDeclsResolved == identifiers.size()) 1537 return resolvedAsTypeDecls(); 1538 1539 // Error recovery: some names weren't found, or we have a mix of 1540 // type and protocol names. Go resolve all of the unresolved names 1541 // and complain if we can't find a consistent answer. 1542 LookupNameKind lookupKind = LookupAnyName; 1543 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) { 1544 // If we already have a protocol or type. Check whether it is the 1545 // right thing. 1546 if (protocols[i] || typeDecls[i]) { 1547 // If we haven't figured out whether we want types or protocols 1548 // yet, try to figure it out from this name. 1549 if (lookupKind == LookupAnyName) { 1550 // If this name refers to both a protocol and a type (e.g., \c 1551 // NSObject), don't conclude anything yet. 1552 if (protocols[i] && typeDecls[i]) 1553 continue; 1554 1555 // Otherwise, let this name decide whether we'll be correcting 1556 // toward types or protocols. 1557 lookupKind = protocols[i] ? LookupObjCProtocolName 1558 : LookupOrdinaryName; 1559 continue; 1560 } 1561 1562 // If we want protocols and we have a protocol, there's nothing 1563 // more to do. 1564 if (lookupKind == LookupObjCProtocolName && protocols[i]) 1565 continue; 1566 1567 // If we want types and we have a type declaration, there's 1568 // nothing more to do. 1569 if (lookupKind == LookupOrdinaryName && typeDecls[i]) 1570 continue; 1571 1572 // We have a conflict: some names refer to protocols and others 1573 // refer to types. 1574 Diag(identifierLocs[i], diag::err_objc_type_args_and_protocols) 1575 << (protocols[i] != nullptr) 1576 << identifiers[i] 1577 << identifiers[0] 1578 << SourceRange(identifierLocs[0]); 1579 1580 protocols.clear(); 1581 typeArgs.clear(); 1582 return; 1583 } 1584 1585 // Perform typo correction on the name. 1586 TypoCorrection corrected = CorrectTypo( 1587 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S, 1588 nullptr, 1589 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context, 1590 lookupKind), 1591 CTK_ErrorRecovery); 1592 if (corrected) { 1593 // Did we find a protocol? 1594 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) { 1595 diagnoseTypo(corrected, 1596 PDiag(diag::err_undeclared_protocol_suggest) 1597 << identifiers[i]); 1598 lookupKind = LookupObjCProtocolName; 1599 protocols[i] = proto; 1600 ++numProtocolsResolved; 1601 continue; 1602 } 1603 1604 // Did we find a type? 1605 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) { 1606 diagnoseTypo(corrected, 1607 PDiag(diag::err_unknown_typename_suggest) 1608 << identifiers[i]); 1609 lookupKind = LookupOrdinaryName; 1610 typeDecls[i] = typeDecl; 1611 ++numTypeDeclsResolved; 1612 continue; 1613 } 1614 1615 // Did we find an Objective-C class? 1616 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { 1617 diagnoseTypo(corrected, 1618 PDiag(diag::err_unknown_type_or_class_name_suggest) 1619 << identifiers[i] << true); 1620 lookupKind = LookupOrdinaryName; 1621 typeDecls[i] = objcClass; 1622 ++numTypeDeclsResolved; 1623 continue; 1624 } 1625 } 1626 1627 // We couldn't find anything. 1628 Diag(identifierLocs[i], 1629 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing 1630 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol 1631 : diag::err_unknown_typename)) 1632 << identifiers[i]; 1633 protocols.clear(); 1634 typeArgs.clear(); 1635 return; 1636 } 1637 1638 // If all of the names were (corrected to) protocols, these were 1639 // protocol qualifiers. 1640 if (numProtocolsResolved == identifiers.size()) 1641 return resolvedAsProtocols(); 1642 1643 // Otherwise, all of the names were (corrected to) types. 1644 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?"); 1645 return resolvedAsTypeDecls(); 1646 } 1647 1648 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of 1649 /// a class method in its extension. 1650 /// 1651 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, 1652 ObjCInterfaceDecl *ID) { 1653 if (!ID) 1654 return; // Possibly due to previous error 1655 1656 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap; 1657 for (auto *MD : ID->methods()) 1658 MethodMap[MD->getSelector()] = MD; 1659 1660 if (MethodMap.empty()) 1661 return; 1662 for (const auto *Method : CAT->methods()) { 1663 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()]; 1664 if (PrevMethod && 1665 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) && 1666 !MatchTwoMethodDeclarations(Method, PrevMethod)) { 1667 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 1668 << Method->getDeclName(); 1669 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 1670 } 1671 } 1672 } 1673 1674 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo; 1675 Sema::DeclGroupPtrTy 1676 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc, 1677 ArrayRef<IdentifierLocPair> IdentList, 1678 AttributeList *attrList) { 1679 SmallVector<Decl *, 8> DeclsInGroup; 1680 for (const IdentifierLocPair &IdentPair : IdentList) { 1681 IdentifierInfo *Ident = IdentPair.first; 1682 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second, 1683 ForRedeclaration); 1684 ObjCProtocolDecl *PDecl 1685 = ObjCProtocolDecl::Create(Context, CurContext, Ident, 1686 IdentPair.second, AtProtocolLoc, 1687 PrevDecl); 1688 1689 PushOnScopeChains(PDecl, TUScope); 1690 CheckObjCDeclScope(PDecl); 1691 1692 if (attrList) 1693 ProcessDeclAttributeList(TUScope, PDecl, attrList); 1694 1695 if (PrevDecl) 1696 mergeDeclAttributes(PDecl, PrevDecl); 1697 1698 DeclsInGroup.push_back(PDecl); 1699 } 1700 1701 return BuildDeclaratorGroup(DeclsInGroup, false); 1702 } 1703 1704 Decl *Sema:: 1705 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, 1706 IdentifierInfo *ClassName, SourceLocation ClassLoc, 1707 ObjCTypeParamList *typeParamList, 1708 IdentifierInfo *CategoryName, 1709 SourceLocation CategoryLoc, 1710 Decl * const *ProtoRefs, 1711 unsigned NumProtoRefs, 1712 const SourceLocation *ProtoLocs, 1713 SourceLocation EndProtoLoc) { 1714 ObjCCategoryDecl *CDecl; 1715 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 1716 1717 /// Check that class of this category is already completely declared. 1718 1719 if (!IDecl 1720 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 1721 diag::err_category_forward_interface, 1722 CategoryName == nullptr)) { 1723 // Create an invalid ObjCCategoryDecl to serve as context for 1724 // the enclosing method declarations. We mark the decl invalid 1725 // to make it clear that this isn't a valid AST. 1726 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 1727 ClassLoc, CategoryLoc, CategoryName, 1728 IDecl, typeParamList); 1729 CDecl->setInvalidDecl(); 1730 CurContext->addDecl(CDecl); 1731 1732 if (!IDecl) 1733 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 1734 return ActOnObjCContainerStartDefinition(CDecl); 1735 } 1736 1737 if (!CategoryName && IDecl->getImplementation()) { 1738 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName; 1739 Diag(IDecl->getImplementation()->getLocation(), 1740 diag::note_implementation_declared); 1741 } 1742 1743 if (CategoryName) { 1744 /// Check for duplicate interface declaration for this category 1745 if (ObjCCategoryDecl *Previous 1746 = IDecl->FindCategoryDeclaration(CategoryName)) { 1747 // Class extensions can be declared multiple times, categories cannot. 1748 Diag(CategoryLoc, diag::warn_dup_category_def) 1749 << ClassName << CategoryName; 1750 Diag(Previous->getLocation(), diag::note_previous_definition); 1751 } 1752 } 1753 1754 // If we have a type parameter list, check it. 1755 if (typeParamList) { 1756 if (auto prevTypeParamList = IDecl->getTypeParamList()) { 1757 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList, 1758 CategoryName 1759 ? TypeParamListContext::Category 1760 : TypeParamListContext::Extension)) 1761 typeParamList = nullptr; 1762 } else { 1763 Diag(typeParamList->getLAngleLoc(), 1764 diag::err_objc_parameterized_category_nonclass) 1765 << (CategoryName != nullptr) 1766 << ClassName 1767 << typeParamList->getSourceRange(); 1768 1769 typeParamList = nullptr; 1770 } 1771 } 1772 1773 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, 1774 ClassLoc, CategoryLoc, CategoryName, IDecl, 1775 typeParamList); 1776 // FIXME: PushOnScopeChains? 1777 CurContext->addDecl(CDecl); 1778 1779 if (NumProtoRefs) { 1780 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs, 1781 NumProtoRefs, ProtoLocs); 1782 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 1783 ProtoLocs, Context); 1784 // Protocols in the class extension belong to the class. 1785 if (CDecl->IsClassExtension()) 1786 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs, 1787 NumProtoRefs, Context); 1788 } 1789 1790 CheckObjCDeclScope(CDecl); 1791 return ActOnObjCContainerStartDefinition(CDecl); 1792 } 1793 1794 /// ActOnStartCategoryImplementation - Perform semantic checks on the 1795 /// category implementation declaration and build an ObjCCategoryImplDecl 1796 /// object. 1797 Decl *Sema::ActOnStartCategoryImplementation( 1798 SourceLocation AtCatImplLoc, 1799 IdentifierInfo *ClassName, SourceLocation ClassLoc, 1800 IdentifierInfo *CatName, SourceLocation CatLoc) { 1801 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true); 1802 ObjCCategoryDecl *CatIDecl = nullptr; 1803 if (IDecl && IDecl->hasDefinition()) { 1804 CatIDecl = IDecl->FindCategoryDeclaration(CatName); 1805 if (!CatIDecl) { 1806 // Category @implementation with no corresponding @interface. 1807 // Create and install one. 1808 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc, 1809 ClassLoc, CatLoc, 1810 CatName, IDecl, 1811 /*typeParamList=*/nullptr); 1812 CatIDecl->setImplicit(); 1813 } 1814 } 1815 1816 ObjCCategoryImplDecl *CDecl = 1817 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl, 1818 ClassLoc, AtCatImplLoc, CatLoc); 1819 /// Check that class of this category is already completely declared. 1820 if (!IDecl) { 1821 Diag(ClassLoc, diag::err_undef_interface) << ClassName; 1822 CDecl->setInvalidDecl(); 1823 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 1824 diag::err_undef_interface)) { 1825 CDecl->setInvalidDecl(); 1826 } 1827 1828 // FIXME: PushOnScopeChains? 1829 CurContext->addDecl(CDecl); 1830 1831 // If the interface is deprecated/unavailable, warn/error about it. 1832 if (IDecl) 1833 DiagnoseUseOfDecl(IDecl, ClassLoc); 1834 1835 /// Check that CatName, category name, is not used in another implementation. 1836 if (CatIDecl) { 1837 if (CatIDecl->getImplementation()) { 1838 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName 1839 << CatName; 1840 Diag(CatIDecl->getImplementation()->getLocation(), 1841 diag::note_previous_definition); 1842 CDecl->setInvalidDecl(); 1843 } else { 1844 CatIDecl->setImplementation(CDecl); 1845 // Warn on implementating category of deprecated class under 1846 // -Wdeprecated-implementations flag. 1847 DiagnoseObjCImplementedDeprecations(*this, 1848 dyn_cast<NamedDecl>(IDecl), 1849 CDecl->getLocation(), 2); 1850 } 1851 } 1852 1853 CheckObjCDeclScope(CDecl); 1854 return ActOnObjCContainerStartDefinition(CDecl); 1855 } 1856 1857 Decl *Sema::ActOnStartClassImplementation( 1858 SourceLocation AtClassImplLoc, 1859 IdentifierInfo *ClassName, SourceLocation ClassLoc, 1860 IdentifierInfo *SuperClassname, 1861 SourceLocation SuperClassLoc) { 1862 ObjCInterfaceDecl *IDecl = nullptr; 1863 // Check for another declaration kind with the same name. 1864 NamedDecl *PrevDecl 1865 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName, 1866 ForRedeclaration); 1867 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 1868 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName; 1869 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1870 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) { 1871 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl), 1872 diag::warn_undef_interface); 1873 } else { 1874 // We did not find anything with the name ClassName; try to correct for 1875 // typos in the class name. 1876 TypoCorrection Corrected = CorrectTypo( 1877 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope, 1878 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError); 1879 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { 1880 // Suggest the (potentially) correct interface name. Don't provide a 1881 // code-modification hint or use the typo name for recovery, because 1882 // this is just a warning. The program may actually be correct. 1883 diagnoseTypo(Corrected, 1884 PDiag(diag::warn_undef_interface_suggest) << ClassName, 1885 /*ErrorRecovery*/false); 1886 } else { 1887 Diag(ClassLoc, diag::warn_undef_interface) << ClassName; 1888 } 1889 } 1890 1891 // Check that super class name is valid class name 1892 ObjCInterfaceDecl *SDecl = nullptr; 1893 if (SuperClassname) { 1894 // Check if a different kind of symbol declared in this scope. 1895 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc, 1896 LookupOrdinaryName); 1897 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 1898 Diag(SuperClassLoc, diag::err_redefinition_different_kind) 1899 << SuperClassname; 1900 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 1901 } else { 1902 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 1903 if (SDecl && !SDecl->hasDefinition()) 1904 SDecl = nullptr; 1905 if (!SDecl) 1906 Diag(SuperClassLoc, diag::err_undef_superclass) 1907 << SuperClassname << ClassName; 1908 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) { 1909 // This implementation and its interface do not have the same 1910 // super class. 1911 Diag(SuperClassLoc, diag::err_conflicting_super_class) 1912 << SDecl->getDeclName(); 1913 Diag(SDecl->getLocation(), diag::note_previous_definition); 1914 } 1915 } 1916 } 1917 1918 if (!IDecl) { 1919 // Legacy case of @implementation with no corresponding @interface. 1920 // Build, chain & install the interface decl into the identifier. 1921 1922 // FIXME: Do we support attributes on the @implementation? If so we should 1923 // copy them over. 1924 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc, 1925 ClassName, /*typeParamList=*/nullptr, 1926 /*PrevDecl=*/nullptr, ClassLoc, 1927 true); 1928 IDecl->startDefinition(); 1929 if (SDecl) { 1930 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo( 1931 Context.getObjCInterfaceType(SDecl), 1932 SuperClassLoc)); 1933 IDecl->setEndOfDefinitionLoc(SuperClassLoc); 1934 } else { 1935 IDecl->setEndOfDefinitionLoc(ClassLoc); 1936 } 1937 1938 PushOnScopeChains(IDecl, TUScope); 1939 } else { 1940 // Mark the interface as being completed, even if it was just as 1941 // @class ....; 1942 // declaration; the user cannot reopen it. 1943 if (!IDecl->hasDefinition()) 1944 IDecl->startDefinition(); 1945 } 1946 1947 ObjCImplementationDecl* IMPDecl = 1948 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl, 1949 ClassLoc, AtClassImplLoc, SuperClassLoc); 1950 1951 if (CheckObjCDeclScope(IMPDecl)) 1952 return ActOnObjCContainerStartDefinition(IMPDecl); 1953 1954 // Check that there is no duplicate implementation of this class. 1955 if (IDecl->getImplementation()) { 1956 // FIXME: Don't leak everything! 1957 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName; 1958 Diag(IDecl->getImplementation()->getLocation(), 1959 diag::note_previous_definition); 1960 IMPDecl->setInvalidDecl(); 1961 } else { // add it to the list. 1962 IDecl->setImplementation(IMPDecl); 1963 PushOnScopeChains(IMPDecl, TUScope); 1964 // Warn on implementating deprecated class under 1965 // -Wdeprecated-implementations flag. 1966 DiagnoseObjCImplementedDeprecations(*this, 1967 dyn_cast<NamedDecl>(IDecl), 1968 IMPDecl->getLocation(), 1); 1969 } 1970 return ActOnObjCContainerStartDefinition(IMPDecl); 1971 } 1972 1973 Sema::DeclGroupPtrTy 1974 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) { 1975 SmallVector<Decl *, 64> DeclsInGroup; 1976 DeclsInGroup.reserve(Decls.size() + 1); 1977 1978 for (unsigned i = 0, e = Decls.size(); i != e; ++i) { 1979 Decl *Dcl = Decls[i]; 1980 if (!Dcl) 1981 continue; 1982 if (Dcl->getDeclContext()->isFileContext()) 1983 Dcl->setTopLevelDeclInObjCContainer(); 1984 DeclsInGroup.push_back(Dcl); 1985 } 1986 1987 DeclsInGroup.push_back(ObjCImpDecl); 1988 1989 return BuildDeclaratorGroup(DeclsInGroup, false); 1990 } 1991 1992 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, 1993 ObjCIvarDecl **ivars, unsigned numIvars, 1994 SourceLocation RBrace) { 1995 assert(ImpDecl && "missing implementation decl"); 1996 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface(); 1997 if (!IDecl) 1998 return; 1999 /// Check case of non-existing \@interface decl. 2000 /// (legacy objective-c \@implementation decl without an \@interface decl). 2001 /// Add implementations's ivar to the synthesize class's ivar list. 2002 if (IDecl->isImplicitInterfaceDecl()) { 2003 IDecl->setEndOfDefinitionLoc(RBrace); 2004 // Add ivar's to class's DeclContext. 2005 for (unsigned i = 0, e = numIvars; i != e; ++i) { 2006 ivars[i]->setLexicalDeclContext(ImpDecl); 2007 IDecl->makeDeclVisibleInContext(ivars[i]); 2008 ImpDecl->addDecl(ivars[i]); 2009 } 2010 2011 return; 2012 } 2013 // If implementation has empty ivar list, just return. 2014 if (numIvars == 0) 2015 return; 2016 2017 assert(ivars && "missing @implementation ivars"); 2018 if (LangOpts.ObjCRuntime.isNonFragile()) { 2019 if (ImpDecl->getSuperClass()) 2020 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use); 2021 for (unsigned i = 0; i < numIvars; i++) { 2022 ObjCIvarDecl* ImplIvar = ivars[i]; 2023 if (const ObjCIvarDecl *ClsIvar = 2024 IDecl->getIvarDecl(ImplIvar->getIdentifier())) { 2025 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 2026 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 2027 continue; 2028 } 2029 // Check class extensions (unnamed categories) for duplicate ivars. 2030 for (const auto *CDecl : IDecl->visible_extensions()) { 2031 if (const ObjCIvarDecl *ClsExtIvar = 2032 CDecl->getIvarDecl(ImplIvar->getIdentifier())) { 2033 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 2034 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition); 2035 continue; 2036 } 2037 } 2038 // Instance ivar to Implementation's DeclContext. 2039 ImplIvar->setLexicalDeclContext(ImpDecl); 2040 IDecl->makeDeclVisibleInContext(ImplIvar); 2041 ImpDecl->addDecl(ImplIvar); 2042 } 2043 return; 2044 } 2045 // Check interface's Ivar list against those in the implementation. 2046 // names and types must match. 2047 // 2048 unsigned j = 0; 2049 ObjCInterfaceDecl::ivar_iterator 2050 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end(); 2051 for (; numIvars > 0 && IVI != IVE; ++IVI) { 2052 ObjCIvarDecl* ImplIvar = ivars[j++]; 2053 ObjCIvarDecl* ClsIvar = *IVI; 2054 assert (ImplIvar && "missing implementation ivar"); 2055 assert (ClsIvar && "missing class ivar"); 2056 2057 // First, make sure the types match. 2058 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) { 2059 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type) 2060 << ImplIvar->getIdentifier() 2061 << ImplIvar->getType() << ClsIvar->getType(); 2062 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 2063 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() && 2064 ImplIvar->getBitWidthValue(Context) != 2065 ClsIvar->getBitWidthValue(Context)) { 2066 Diag(ImplIvar->getBitWidth()->getLocStart(), 2067 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier(); 2068 Diag(ClsIvar->getBitWidth()->getLocStart(), 2069 diag::note_previous_definition); 2070 } 2071 // Make sure the names are identical. 2072 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) { 2073 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name) 2074 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier(); 2075 Diag(ClsIvar->getLocation(), diag::note_previous_definition); 2076 } 2077 --numIvars; 2078 } 2079 2080 if (numIvars > 0) 2081 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count); 2082 else if (IVI != IVE) 2083 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count); 2084 } 2085 2086 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc, 2087 ObjCMethodDecl *method, 2088 bool &IncompleteImpl, 2089 unsigned DiagID, 2090 NamedDecl *NeededFor = nullptr) { 2091 // No point warning no definition of method which is 'unavailable'. 2092 switch (method->getAvailability()) { 2093 case AR_Available: 2094 case AR_Deprecated: 2095 break; 2096 2097 // Don't warn about unavailable or not-yet-introduced methods. 2098 case AR_NotYetIntroduced: 2099 case AR_Unavailable: 2100 return; 2101 } 2102 2103 // FIXME: For now ignore 'IncompleteImpl'. 2104 // Previously we grouped all unimplemented methods under a single 2105 // warning, but some users strongly voiced that they would prefer 2106 // separate warnings. We will give that approach a try, as that 2107 // matches what we do with protocols. 2108 { 2109 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID); 2110 B << method; 2111 if (NeededFor) 2112 B << NeededFor; 2113 } 2114 2115 // Issue a note to the original declaration. 2116 SourceLocation MethodLoc = method->getLocStart(); 2117 if (MethodLoc.isValid()) 2118 S.Diag(MethodLoc, diag::note_method_declared_at) << method; 2119 } 2120 2121 /// Determines if type B can be substituted for type A. Returns true if we can 2122 /// guarantee that anything that the user will do to an object of type A can 2123 /// also be done to an object of type B. This is trivially true if the two 2124 /// types are the same, or if B is a subclass of A. It becomes more complex 2125 /// in cases where protocols are involved. 2126 /// 2127 /// Object types in Objective-C describe the minimum requirements for an 2128 /// object, rather than providing a complete description of a type. For 2129 /// example, if A is a subclass of B, then B* may refer to an instance of A. 2130 /// The principle of substitutability means that we may use an instance of A 2131 /// anywhere that we may use an instance of B - it will implement all of the 2132 /// ivars of B and all of the methods of B. 2133 /// 2134 /// This substitutability is important when type checking methods, because 2135 /// the implementation may have stricter type definitions than the interface. 2136 /// The interface specifies minimum requirements, but the implementation may 2137 /// have more accurate ones. For example, a method may privately accept 2138 /// instances of B, but only publish that it accepts instances of A. Any 2139 /// object passed to it will be type checked against B, and so will implicitly 2140 /// by a valid A*. Similarly, a method may return a subclass of the class that 2141 /// it is declared as returning. 2142 /// 2143 /// This is most important when considering subclassing. A method in a 2144 /// subclass must accept any object as an argument that its superclass's 2145 /// implementation accepts. It may, however, accept a more general type 2146 /// without breaking substitutability (i.e. you can still use the subclass 2147 /// anywhere that you can use the superclass, but not vice versa). The 2148 /// converse requirement applies to return types: the return type for a 2149 /// subclass method must be a valid object of the kind that the superclass 2150 /// advertises, but it may be specified more accurately. This avoids the need 2151 /// for explicit down-casting by callers. 2152 /// 2153 /// Note: This is a stricter requirement than for assignment. 2154 static bool isObjCTypeSubstitutable(ASTContext &Context, 2155 const ObjCObjectPointerType *A, 2156 const ObjCObjectPointerType *B, 2157 bool rejectId) { 2158 // Reject a protocol-unqualified id. 2159 if (rejectId && B->isObjCIdType()) return false; 2160 2161 // If B is a qualified id, then A must also be a qualified id and it must 2162 // implement all of the protocols in B. It may not be a qualified class. 2163 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a 2164 // stricter definition so it is not substitutable for id<A>. 2165 if (B->isObjCQualifiedIdType()) { 2166 return A->isObjCQualifiedIdType() && 2167 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0), 2168 QualType(B,0), 2169 false); 2170 } 2171 2172 /* 2173 // id is a special type that bypasses type checking completely. We want a 2174 // warning when it is used in one place but not another. 2175 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false; 2176 2177 2178 // If B is a qualified id, then A must also be a qualified id (which it isn't 2179 // if we've got this far) 2180 if (B->isObjCQualifiedIdType()) return false; 2181 */ 2182 2183 // Now we know that A and B are (potentially-qualified) class types. The 2184 // normal rules for assignment apply. 2185 return Context.canAssignObjCInterfaces(A, B); 2186 } 2187 2188 static SourceRange getTypeRange(TypeSourceInfo *TSI) { 2189 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange()); 2190 } 2191 2192 /// Determine whether two set of Objective-C declaration qualifiers conflict. 2193 static bool objcModifiersConflict(Decl::ObjCDeclQualifier x, 2194 Decl::ObjCDeclQualifier y) { 2195 return (x & ~Decl::OBJC_TQ_CSNullability) != 2196 (y & ~Decl::OBJC_TQ_CSNullability); 2197 } 2198 2199 static bool CheckMethodOverrideReturn(Sema &S, 2200 ObjCMethodDecl *MethodImpl, 2201 ObjCMethodDecl *MethodDecl, 2202 bool IsProtocolMethodDecl, 2203 bool IsOverridingMode, 2204 bool Warn) { 2205 if (IsProtocolMethodDecl && 2206 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(), 2207 MethodImpl->getObjCDeclQualifier())) { 2208 if (Warn) { 2209 S.Diag(MethodImpl->getLocation(), 2210 (IsOverridingMode 2211 ? diag::warn_conflicting_overriding_ret_type_modifiers 2212 : diag::warn_conflicting_ret_type_modifiers)) 2213 << MethodImpl->getDeclName() 2214 << MethodImpl->getReturnTypeSourceRange(); 2215 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration) 2216 << MethodDecl->getReturnTypeSourceRange(); 2217 } 2218 else 2219 return false; 2220 } 2221 if (Warn && IsOverridingMode && 2222 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) && 2223 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(), 2224 MethodDecl->getReturnType(), 2225 false)) { 2226 auto nullabilityMethodImpl = 2227 *MethodImpl->getReturnType()->getNullability(S.Context); 2228 auto nullabilityMethodDecl = 2229 *MethodDecl->getReturnType()->getNullability(S.Context); 2230 S.Diag(MethodImpl->getLocation(), 2231 diag::warn_conflicting_nullability_attr_overriding_ret_types) 2232 << DiagNullabilityKind( 2233 nullabilityMethodImpl, 2234 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2235 != 0)) 2236 << DiagNullabilityKind( 2237 nullabilityMethodDecl, 2238 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2239 != 0)); 2240 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration); 2241 } 2242 2243 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(), 2244 MethodDecl->getReturnType())) 2245 return true; 2246 if (!Warn) 2247 return false; 2248 2249 unsigned DiagID = 2250 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types 2251 : diag::warn_conflicting_ret_types; 2252 2253 // Mismatches between ObjC pointers go into a different warning 2254 // category, and sometimes they're even completely whitelisted. 2255 if (const ObjCObjectPointerType *ImplPtrTy = 2256 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) { 2257 if (const ObjCObjectPointerType *IfacePtrTy = 2258 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) { 2259 // Allow non-matching return types as long as they don't violate 2260 // the principle of substitutability. Specifically, we permit 2261 // return types that are subclasses of the declared return type, 2262 // or that are more-qualified versions of the declared type. 2263 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false)) 2264 return false; 2265 2266 DiagID = 2267 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types 2268 : diag::warn_non_covariant_ret_types; 2269 } 2270 } 2271 2272 S.Diag(MethodImpl->getLocation(), DiagID) 2273 << MethodImpl->getDeclName() << MethodDecl->getReturnType() 2274 << MethodImpl->getReturnType() 2275 << MethodImpl->getReturnTypeSourceRange(); 2276 S.Diag(MethodDecl->getLocation(), IsOverridingMode 2277 ? diag::note_previous_declaration 2278 : diag::note_previous_definition) 2279 << MethodDecl->getReturnTypeSourceRange(); 2280 return false; 2281 } 2282 2283 static bool CheckMethodOverrideParam(Sema &S, 2284 ObjCMethodDecl *MethodImpl, 2285 ObjCMethodDecl *MethodDecl, 2286 ParmVarDecl *ImplVar, 2287 ParmVarDecl *IfaceVar, 2288 bool IsProtocolMethodDecl, 2289 bool IsOverridingMode, 2290 bool Warn) { 2291 if (IsProtocolMethodDecl && 2292 objcModifiersConflict(ImplVar->getObjCDeclQualifier(), 2293 IfaceVar->getObjCDeclQualifier())) { 2294 if (Warn) { 2295 if (IsOverridingMode) 2296 S.Diag(ImplVar->getLocation(), 2297 diag::warn_conflicting_overriding_param_modifiers) 2298 << getTypeRange(ImplVar->getTypeSourceInfo()) 2299 << MethodImpl->getDeclName(); 2300 else S.Diag(ImplVar->getLocation(), 2301 diag::warn_conflicting_param_modifiers) 2302 << getTypeRange(ImplVar->getTypeSourceInfo()) 2303 << MethodImpl->getDeclName(); 2304 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration) 2305 << getTypeRange(IfaceVar->getTypeSourceInfo()); 2306 } 2307 else 2308 return false; 2309 } 2310 2311 QualType ImplTy = ImplVar->getType(); 2312 QualType IfaceTy = IfaceVar->getType(); 2313 if (Warn && IsOverridingMode && 2314 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) && 2315 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) { 2316 S.Diag(ImplVar->getLocation(), 2317 diag::warn_conflicting_nullability_attr_overriding_param_types) 2318 << DiagNullabilityKind( 2319 *ImplTy->getNullability(S.Context), 2320 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2321 != 0)) 2322 << DiagNullabilityKind( 2323 *IfaceTy->getNullability(S.Context), 2324 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability) 2325 != 0)); 2326 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration); 2327 } 2328 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy)) 2329 return true; 2330 2331 if (!Warn) 2332 return false; 2333 unsigned DiagID = 2334 IsOverridingMode ? diag::warn_conflicting_overriding_param_types 2335 : diag::warn_conflicting_param_types; 2336 2337 // Mismatches between ObjC pointers go into a different warning 2338 // category, and sometimes they're even completely whitelisted. 2339 if (const ObjCObjectPointerType *ImplPtrTy = 2340 ImplTy->getAs<ObjCObjectPointerType>()) { 2341 if (const ObjCObjectPointerType *IfacePtrTy = 2342 IfaceTy->getAs<ObjCObjectPointerType>()) { 2343 // Allow non-matching argument types as long as they don't 2344 // violate the principle of substitutability. Specifically, the 2345 // implementation must accept any objects that the superclass 2346 // accepts, however it may also accept others. 2347 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true)) 2348 return false; 2349 2350 DiagID = 2351 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types 2352 : diag::warn_non_contravariant_param_types; 2353 } 2354 } 2355 2356 S.Diag(ImplVar->getLocation(), DiagID) 2357 << getTypeRange(ImplVar->getTypeSourceInfo()) 2358 << MethodImpl->getDeclName() << IfaceTy << ImplTy; 2359 S.Diag(IfaceVar->getLocation(), 2360 (IsOverridingMode ? diag::note_previous_declaration 2361 : diag::note_previous_definition)) 2362 << getTypeRange(IfaceVar->getTypeSourceInfo()); 2363 return false; 2364 } 2365 2366 /// In ARC, check whether the conventional meanings of the two methods 2367 /// match. If they don't, it's a hard error. 2368 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl, 2369 ObjCMethodDecl *decl) { 2370 ObjCMethodFamily implFamily = impl->getMethodFamily(); 2371 ObjCMethodFamily declFamily = decl->getMethodFamily(); 2372 if (implFamily == declFamily) return false; 2373 2374 // Since conventions are sorted by selector, the only possibility is 2375 // that the types differ enough to cause one selector or the other 2376 // to fall out of the family. 2377 assert(implFamily == OMF_None || declFamily == OMF_None); 2378 2379 // No further diagnostics required on invalid declarations. 2380 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true; 2381 2382 const ObjCMethodDecl *unmatched = impl; 2383 ObjCMethodFamily family = declFamily; 2384 unsigned errorID = diag::err_arc_lost_method_convention; 2385 unsigned noteID = diag::note_arc_lost_method_convention; 2386 if (declFamily == OMF_None) { 2387 unmatched = decl; 2388 family = implFamily; 2389 errorID = diag::err_arc_gained_method_convention; 2390 noteID = diag::note_arc_gained_method_convention; 2391 } 2392 2393 // Indexes into a %select clause in the diagnostic. 2394 enum FamilySelector { 2395 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new 2396 }; 2397 FamilySelector familySelector = FamilySelector(); 2398 2399 switch (family) { 2400 case OMF_None: llvm_unreachable("logic error, no method convention"); 2401 case OMF_retain: 2402 case OMF_release: 2403 case OMF_autorelease: 2404 case OMF_dealloc: 2405 case OMF_finalize: 2406 case OMF_retainCount: 2407 case OMF_self: 2408 case OMF_initialize: 2409 case OMF_performSelector: 2410 // Mismatches for these methods don't change ownership 2411 // conventions, so we don't care. 2412 return false; 2413 2414 case OMF_init: familySelector = F_init; break; 2415 case OMF_alloc: familySelector = F_alloc; break; 2416 case OMF_copy: familySelector = F_copy; break; 2417 case OMF_mutableCopy: familySelector = F_mutableCopy; break; 2418 case OMF_new: familySelector = F_new; break; 2419 } 2420 2421 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn }; 2422 ReasonSelector reasonSelector; 2423 2424 // The only reason these methods don't fall within their families is 2425 // due to unusual result types. 2426 if (unmatched->getReturnType()->isObjCObjectPointerType()) { 2427 reasonSelector = R_UnrelatedReturn; 2428 } else { 2429 reasonSelector = R_NonObjectReturn; 2430 } 2431 2432 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector); 2433 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector); 2434 2435 return true; 2436 } 2437 2438 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl, 2439 ObjCMethodDecl *MethodDecl, 2440 bool IsProtocolMethodDecl) { 2441 if (getLangOpts().ObjCAutoRefCount && 2442 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl)) 2443 return; 2444 2445 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 2446 IsProtocolMethodDecl, false, 2447 true); 2448 2449 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 2450 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 2451 EF = MethodDecl->param_end(); 2452 IM != EM && IF != EF; ++IM, ++IF) { 2453 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF, 2454 IsProtocolMethodDecl, false, true); 2455 } 2456 2457 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) { 2458 Diag(ImpMethodDecl->getLocation(), 2459 diag::warn_conflicting_variadic); 2460 Diag(MethodDecl->getLocation(), diag::note_previous_declaration); 2461 } 2462 } 2463 2464 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method, 2465 ObjCMethodDecl *Overridden, 2466 bool IsProtocolMethodDecl) { 2467 2468 CheckMethodOverrideReturn(*this, Method, Overridden, 2469 IsProtocolMethodDecl, true, 2470 true); 2471 2472 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(), 2473 IF = Overridden->param_begin(), EM = Method->param_end(), 2474 EF = Overridden->param_end(); 2475 IM != EM && IF != EF; ++IM, ++IF) { 2476 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF, 2477 IsProtocolMethodDecl, true, true); 2478 } 2479 2480 if (Method->isVariadic() != Overridden->isVariadic()) { 2481 Diag(Method->getLocation(), 2482 diag::warn_conflicting_overriding_variadic); 2483 Diag(Overridden->getLocation(), diag::note_previous_declaration); 2484 } 2485 } 2486 2487 /// WarnExactTypedMethods - This routine issues a warning if method 2488 /// implementation declaration matches exactly that of its declaration. 2489 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl, 2490 ObjCMethodDecl *MethodDecl, 2491 bool IsProtocolMethodDecl) { 2492 // don't issue warning when protocol method is optional because primary 2493 // class is not required to implement it and it is safe for protocol 2494 // to implement it. 2495 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional) 2496 return; 2497 // don't issue warning when primary class's method is 2498 // depecated/unavailable. 2499 if (MethodDecl->hasAttr<UnavailableAttr>() || 2500 MethodDecl->hasAttr<DeprecatedAttr>()) 2501 return; 2502 2503 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 2504 IsProtocolMethodDecl, false, false); 2505 if (match) 2506 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(), 2507 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(), 2508 EF = MethodDecl->param_end(); 2509 IM != EM && IF != EF; ++IM, ++IF) { 2510 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, 2511 *IM, *IF, 2512 IsProtocolMethodDecl, false, false); 2513 if (!match) 2514 break; 2515 } 2516 if (match) 2517 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic()); 2518 if (match) 2519 match = !(MethodDecl->isClassMethod() && 2520 MethodDecl->getSelector() == GetNullarySelector("load", Context)); 2521 2522 if (match) { 2523 Diag(ImpMethodDecl->getLocation(), 2524 diag::warn_category_method_impl_match); 2525 Diag(MethodDecl->getLocation(), diag::note_method_declared_at) 2526 << MethodDecl->getDeclName(); 2527 } 2528 } 2529 2530 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely 2531 /// improve the efficiency of selector lookups and type checking by associating 2532 /// with each protocol / interface / category the flattened instance tables. If 2533 /// we used an immutable set to keep the table then it wouldn't add significant 2534 /// memory cost and it would be handy for lookups. 2535 2536 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet; 2537 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet; 2538 2539 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl, 2540 ProtocolNameSet &PNS) { 2541 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) 2542 PNS.insert(PDecl->getIdentifier()); 2543 for (const auto *PI : PDecl->protocols()) 2544 findProtocolsWithExplicitImpls(PI, PNS); 2545 } 2546 2547 /// Recursively populates a set with all conformed protocols in a class 2548 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation' 2549 /// attribute. 2550 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super, 2551 ProtocolNameSet &PNS) { 2552 if (!Super) 2553 return; 2554 2555 for (const auto *I : Super->all_referenced_protocols()) 2556 findProtocolsWithExplicitImpls(I, PNS); 2557 2558 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS); 2559 } 2560 2561 /// CheckProtocolMethodDefs - This routine checks unimplemented methods 2562 /// Declared in protocol, and those referenced by it. 2563 static void CheckProtocolMethodDefs(Sema &S, 2564 SourceLocation ImpLoc, 2565 ObjCProtocolDecl *PDecl, 2566 bool& IncompleteImpl, 2567 const Sema::SelectorSet &InsMap, 2568 const Sema::SelectorSet &ClsMap, 2569 ObjCContainerDecl *CDecl, 2570 LazyProtocolNameSet &ProtocolsExplictImpl) { 2571 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl); 2572 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface() 2573 : dyn_cast<ObjCInterfaceDecl>(CDecl); 2574 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null"); 2575 2576 ObjCInterfaceDecl *Super = IDecl->getSuperClass(); 2577 ObjCInterfaceDecl *NSIDecl = nullptr; 2578 2579 // If this protocol is marked 'objc_protocol_requires_explicit_implementation' 2580 // then we should check if any class in the super class hierarchy also 2581 // conforms to this protocol, either directly or via protocol inheritance. 2582 // If so, we can skip checking this protocol completely because we 2583 // know that a parent class already satisfies this protocol. 2584 // 2585 // Note: we could generalize this logic for all protocols, and merely 2586 // add the limit on looking at the super class chain for just 2587 // specially marked protocols. This may be a good optimization. This 2588 // change is restricted to 'objc_protocol_requires_explicit_implementation' 2589 // protocols for now for controlled evaluation. 2590 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) { 2591 if (!ProtocolsExplictImpl) { 2592 ProtocolsExplictImpl.reset(new ProtocolNameSet); 2593 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl); 2594 } 2595 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) != 2596 ProtocolsExplictImpl->end()) 2597 return; 2598 2599 // If no super class conforms to the protocol, we should not search 2600 // for methods in the super class to implicitly satisfy the protocol. 2601 Super = nullptr; 2602 } 2603 2604 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) { 2605 // check to see if class implements forwardInvocation method and objects 2606 // of this class are derived from 'NSProxy' so that to forward requests 2607 // from one object to another. 2608 // Under such conditions, which means that every method possible is 2609 // implemented in the class, we should not issue "Method definition not 2610 // found" warnings. 2611 // FIXME: Use a general GetUnarySelector method for this. 2612 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation"); 2613 Selector fISelector = S.Context.Selectors.getSelector(1, &II); 2614 if (InsMap.count(fISelector)) 2615 // Is IDecl derived from 'NSProxy'? If so, no instance methods 2616 // need be implemented in the implementation. 2617 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy")); 2618 } 2619 2620 // If this is a forward protocol declaration, get its definition. 2621 if (!PDecl->isThisDeclarationADefinition() && 2622 PDecl->getDefinition()) 2623 PDecl = PDecl->getDefinition(); 2624 2625 // If a method lookup fails locally we still need to look and see if 2626 // the method was implemented by a base class or an inherited 2627 // protocol. This lookup is slow, but occurs rarely in correct code 2628 // and otherwise would terminate in a warning. 2629 2630 // check unimplemented instance methods. 2631 if (!NSIDecl) 2632 for (auto *method : PDecl->instance_methods()) { 2633 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 2634 !method->isPropertyAccessor() && 2635 !InsMap.count(method->getSelector()) && 2636 (!Super || !Super->lookupMethod(method->getSelector(), 2637 true /* instance */, 2638 false /* shallowCategory */, 2639 true /* followsSuper */, 2640 nullptr /* category */))) { 2641 // If a method is not implemented in the category implementation but 2642 // has been declared in its primary class, superclass, 2643 // or in one of their protocols, no need to issue the warning. 2644 // This is because method will be implemented in the primary class 2645 // or one of its super class implementation. 2646 2647 // Ugly, but necessary. Method declared in protcol might have 2648 // have been synthesized due to a property declared in the class which 2649 // uses the protocol. 2650 if (ObjCMethodDecl *MethodInClass = 2651 IDecl->lookupMethod(method->getSelector(), 2652 true /* instance */, 2653 true /* shallowCategoryLookup */, 2654 false /* followSuper */)) 2655 if (C || MethodInClass->isPropertyAccessor()) 2656 continue; 2657 unsigned DIAG = diag::warn_unimplemented_protocol_method; 2658 if (!S.Diags.isIgnored(DIAG, ImpLoc)) { 2659 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, 2660 PDecl); 2661 } 2662 } 2663 } 2664 // check unimplemented class methods 2665 for (auto *method : PDecl->class_methods()) { 2666 if (method->getImplementationControl() != ObjCMethodDecl::Optional && 2667 !ClsMap.count(method->getSelector()) && 2668 (!Super || !Super->lookupMethod(method->getSelector(), 2669 false /* class method */, 2670 false /* shallowCategoryLookup */, 2671 true /* followSuper */, 2672 nullptr /* category */))) { 2673 // See above comment for instance method lookups. 2674 if (C && IDecl->lookupMethod(method->getSelector(), 2675 false /* class */, 2676 true /* shallowCategoryLookup */, 2677 false /* followSuper */)) 2678 continue; 2679 2680 unsigned DIAG = diag::warn_unimplemented_protocol_method; 2681 if (!S.Diags.isIgnored(DIAG, ImpLoc)) { 2682 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl); 2683 } 2684 } 2685 } 2686 // Check on this protocols's referenced protocols, recursively. 2687 for (auto *PI : PDecl->protocols()) 2688 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap, 2689 CDecl, ProtocolsExplictImpl); 2690 } 2691 2692 /// MatchAllMethodDeclarations - Check methods declared in interface 2693 /// or protocol against those declared in their implementations. 2694 /// 2695 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap, 2696 const SelectorSet &ClsMap, 2697 SelectorSet &InsMapSeen, 2698 SelectorSet &ClsMapSeen, 2699 ObjCImplDecl* IMPDecl, 2700 ObjCContainerDecl* CDecl, 2701 bool &IncompleteImpl, 2702 bool ImmediateClass, 2703 bool WarnCategoryMethodImpl) { 2704 // Check and see if instance methods in class interface have been 2705 // implemented in the implementation class. If so, their types match. 2706 for (auto *I : CDecl->instance_methods()) { 2707 if (!InsMapSeen.insert(I->getSelector()).second) 2708 continue; 2709 if (!I->isPropertyAccessor() && 2710 !InsMap.count(I->getSelector())) { 2711 if (ImmediateClass) 2712 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl, 2713 diag::warn_undef_method_impl); 2714 continue; 2715 } else { 2716 ObjCMethodDecl *ImpMethodDecl = 2717 IMPDecl->getInstanceMethod(I->getSelector()); 2718 assert(CDecl->getInstanceMethod(I->getSelector()) && 2719 "Expected to find the method through lookup as well"); 2720 // ImpMethodDecl may be null as in a @dynamic property. 2721 if (ImpMethodDecl) { 2722 if (!WarnCategoryMethodImpl) 2723 WarnConflictingTypedMethods(ImpMethodDecl, I, 2724 isa<ObjCProtocolDecl>(CDecl)); 2725 else if (!I->isPropertyAccessor()) 2726 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl)); 2727 } 2728 } 2729 } 2730 2731 // Check and see if class methods in class interface have been 2732 // implemented in the implementation class. If so, their types match. 2733 for (auto *I : CDecl->class_methods()) { 2734 if (!ClsMapSeen.insert(I->getSelector()).second) 2735 continue; 2736 if (!ClsMap.count(I->getSelector())) { 2737 if (ImmediateClass) 2738 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl, 2739 diag::warn_undef_method_impl); 2740 } else { 2741 ObjCMethodDecl *ImpMethodDecl = 2742 IMPDecl->getClassMethod(I->getSelector()); 2743 assert(CDecl->getClassMethod(I->getSelector()) && 2744 "Expected to find the method through lookup as well"); 2745 if (!WarnCategoryMethodImpl) 2746 WarnConflictingTypedMethods(ImpMethodDecl, I, 2747 isa<ObjCProtocolDecl>(CDecl)); 2748 else 2749 WarnExactTypedMethods(ImpMethodDecl, I, 2750 isa<ObjCProtocolDecl>(CDecl)); 2751 } 2752 } 2753 2754 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) { 2755 // Also, check for methods declared in protocols inherited by 2756 // this protocol. 2757 for (auto *PI : PD->protocols()) 2758 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2759 IMPDecl, PI, IncompleteImpl, false, 2760 WarnCategoryMethodImpl); 2761 } 2762 2763 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 2764 // when checking that methods in implementation match their declaration, 2765 // i.e. when WarnCategoryMethodImpl is false, check declarations in class 2766 // extension; as well as those in categories. 2767 if (!WarnCategoryMethodImpl) { 2768 for (auto *Cat : I->visible_categories()) 2769 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2770 IMPDecl, Cat, IncompleteImpl, 2771 ImmediateClass && Cat->IsClassExtension(), 2772 WarnCategoryMethodImpl); 2773 } else { 2774 // Also methods in class extensions need be looked at next. 2775 for (auto *Ext : I->visible_extensions()) 2776 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2777 IMPDecl, Ext, IncompleteImpl, false, 2778 WarnCategoryMethodImpl); 2779 } 2780 2781 // Check for any implementation of a methods declared in protocol. 2782 for (auto *PI : I->all_referenced_protocols()) 2783 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2784 IMPDecl, PI, IncompleteImpl, false, 2785 WarnCategoryMethodImpl); 2786 2787 // FIXME. For now, we are not checking for extact match of methods 2788 // in category implementation and its primary class's super class. 2789 if (!WarnCategoryMethodImpl && I->getSuperClass()) 2790 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2791 IMPDecl, 2792 I->getSuperClass(), IncompleteImpl, false); 2793 } 2794 } 2795 2796 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in 2797 /// category matches with those implemented in its primary class and 2798 /// warns each time an exact match is found. 2799 void Sema::CheckCategoryVsClassMethodMatches( 2800 ObjCCategoryImplDecl *CatIMPDecl) { 2801 // Get category's primary class. 2802 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl(); 2803 if (!CatDecl) 2804 return; 2805 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface(); 2806 if (!IDecl) 2807 return; 2808 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass(); 2809 SelectorSet InsMap, ClsMap; 2810 2811 for (const auto *I : CatIMPDecl->instance_methods()) { 2812 Selector Sel = I->getSelector(); 2813 // When checking for methods implemented in the category, skip over 2814 // those declared in category class's super class. This is because 2815 // the super class must implement the method. 2816 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true)) 2817 continue; 2818 InsMap.insert(Sel); 2819 } 2820 2821 for (const auto *I : CatIMPDecl->class_methods()) { 2822 Selector Sel = I->getSelector(); 2823 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false)) 2824 continue; 2825 ClsMap.insert(Sel); 2826 } 2827 if (InsMap.empty() && ClsMap.empty()) 2828 return; 2829 2830 SelectorSet InsMapSeen, ClsMapSeen; 2831 bool IncompleteImpl = false; 2832 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2833 CatIMPDecl, IDecl, 2834 IncompleteImpl, false, 2835 true /*WarnCategoryMethodImpl*/); 2836 } 2837 2838 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, 2839 ObjCContainerDecl* CDecl, 2840 bool IncompleteImpl) { 2841 SelectorSet InsMap; 2842 // Check and see if instance methods in class interface have been 2843 // implemented in the implementation class. 2844 for (const auto *I : IMPDecl->instance_methods()) 2845 InsMap.insert(I->getSelector()); 2846 2847 // Add the selectors for getters/setters of @dynamic properties. 2848 for (const auto *PImpl : IMPDecl->property_impls()) { 2849 // We only care about @dynamic implementations. 2850 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic) 2851 continue; 2852 2853 const auto *P = PImpl->getPropertyDecl(); 2854 if (!P) continue; 2855 2856 InsMap.insert(P->getGetterName()); 2857 if (!P->getSetterName().isNull()) 2858 InsMap.insert(P->getSetterName()); 2859 } 2860 2861 // Check and see if properties declared in the interface have either 1) 2862 // an implementation or 2) there is a @synthesize/@dynamic implementation 2863 // of the property in the @implementation. 2864 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2865 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties && 2866 LangOpts.ObjCRuntime.isNonFragile() && 2867 !IDecl->isObjCRequiresPropertyDefs(); 2868 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties); 2869 } 2870 2871 // Diagnose null-resettable synthesized setters. 2872 diagnoseNullResettableSynthesizedSetters(IMPDecl); 2873 2874 SelectorSet ClsMap; 2875 for (const auto *I : IMPDecl->class_methods()) 2876 ClsMap.insert(I->getSelector()); 2877 2878 // Check for type conflict of methods declared in a class/protocol and 2879 // its implementation; if any. 2880 SelectorSet InsMapSeen, ClsMapSeen; 2881 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2882 IMPDecl, CDecl, 2883 IncompleteImpl, true); 2884 2885 // check all methods implemented in category against those declared 2886 // in its primary class. 2887 if (ObjCCategoryImplDecl *CatDecl = 2888 dyn_cast<ObjCCategoryImplDecl>(IMPDecl)) 2889 CheckCategoryVsClassMethodMatches(CatDecl); 2890 2891 // Check the protocol list for unimplemented methods in the @implementation 2892 // class. 2893 // Check and see if class methods in class interface have been 2894 // implemented in the implementation class. 2895 2896 LazyProtocolNameSet ExplicitImplProtocols; 2897 2898 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 2899 for (auto *PI : I->all_referenced_protocols()) 2900 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl, 2901 InsMap, ClsMap, I, ExplicitImplProtocols); 2902 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2903 // For extended class, unimplemented methods in its protocols will 2904 // be reported in the primary class. 2905 if (!C->IsClassExtension()) { 2906 for (auto *P : C->protocols()) 2907 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P, 2908 IncompleteImpl, InsMap, ClsMap, CDecl, 2909 ExplicitImplProtocols); 2910 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, 2911 /*SynthesizeProperties=*/false); 2912 } 2913 } else 2914 llvm_unreachable("invalid ObjCContainerDecl type."); 2915 } 2916 2917 Sema::DeclGroupPtrTy 2918 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, 2919 IdentifierInfo **IdentList, 2920 SourceLocation *IdentLocs, 2921 ArrayRef<ObjCTypeParamList *> TypeParamLists, 2922 unsigned NumElts) { 2923 SmallVector<Decl *, 8> DeclsInGroup; 2924 for (unsigned i = 0; i != NumElts; ++i) { 2925 // Check for another declaration kind with the same name. 2926 NamedDecl *PrevDecl 2927 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], 2928 LookupOrdinaryName, ForRedeclaration); 2929 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 2930 // GCC apparently allows the following idiom: 2931 // 2932 // typedef NSObject < XCElementTogglerP > XCElementToggler; 2933 // @class XCElementToggler; 2934 // 2935 // Here we have chosen to ignore the forward class declaration 2936 // with a warning. Since this is the implied behavior. 2937 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl); 2938 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) { 2939 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i]; 2940 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2941 } else { 2942 // a forward class declaration matching a typedef name of a class refers 2943 // to the underlying class. Just ignore the forward class with a warning 2944 // as this will force the intended behavior which is to lookup the 2945 // typedef name. 2946 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) { 2947 Diag(AtClassLoc, diag::warn_forward_class_redefinition) 2948 << IdentList[i]; 2949 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2950 continue; 2951 } 2952 } 2953 } 2954 2955 // Create a declaration to describe this forward declaration. 2956 ObjCInterfaceDecl *PrevIDecl 2957 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 2958 2959 IdentifierInfo *ClassName = IdentList[i]; 2960 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 2961 // A previous decl with a different name is because of 2962 // @compatibility_alias, for example: 2963 // \code 2964 // @class NewImage; 2965 // @compatibility_alias OldImage NewImage; 2966 // \endcode 2967 // A lookup for 'OldImage' will return the 'NewImage' decl. 2968 // 2969 // In such a case use the real declaration name, instead of the alias one, 2970 // otherwise we will break IdentifierResolver and redecls-chain invariants. 2971 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 2972 // has been aliased. 2973 ClassName = PrevIDecl->getIdentifier(); 2974 } 2975 2976 // If this forward declaration has type parameters, compare them with the 2977 // type parameters of the previous declaration. 2978 ObjCTypeParamList *TypeParams = TypeParamLists[i]; 2979 if (PrevIDecl && TypeParams) { 2980 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) { 2981 // Check for consistency with the previous declaration. 2982 if (checkTypeParamListConsistency( 2983 *this, PrevTypeParams, TypeParams, 2984 TypeParamListContext::ForwardDeclaration)) { 2985 TypeParams = nullptr; 2986 } 2987 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) { 2988 // The @interface does not have type parameters. Complain. 2989 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class) 2990 << ClassName 2991 << TypeParams->getSourceRange(); 2992 Diag(Def->getLocation(), diag::note_defined_here) 2993 << ClassName; 2994 2995 TypeParams = nullptr; 2996 } 2997 } 2998 2999 ObjCInterfaceDecl *IDecl 3000 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc, 3001 ClassName, TypeParams, PrevIDecl, 3002 IdentLocs[i]); 3003 IDecl->setAtEndRange(IdentLocs[i]); 3004 3005 PushOnScopeChains(IDecl, TUScope); 3006 CheckObjCDeclScope(IDecl); 3007 DeclsInGroup.push_back(IDecl); 3008 } 3009 3010 return BuildDeclaratorGroup(DeclsInGroup, false); 3011 } 3012 3013 static bool tryMatchRecordTypes(ASTContext &Context, 3014 Sema::MethodMatchStrategy strategy, 3015 const Type *left, const Type *right); 3016 3017 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy, 3018 QualType leftQT, QualType rightQT) { 3019 const Type *left = 3020 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr(); 3021 const Type *right = 3022 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr(); 3023 3024 if (left == right) return true; 3025 3026 // If we're doing a strict match, the types have to match exactly. 3027 if (strategy == Sema::MMS_strict) return false; 3028 3029 if (left->isIncompleteType() || right->isIncompleteType()) return false; 3030 3031 // Otherwise, use this absurdly complicated algorithm to try to 3032 // validate the basic, low-level compatibility of the two types. 3033 3034 // As a minimum, require the sizes and alignments to match. 3035 TypeInfo LeftTI = Context.getTypeInfo(left); 3036 TypeInfo RightTI = Context.getTypeInfo(right); 3037 if (LeftTI.Width != RightTI.Width) 3038 return false; 3039 3040 if (LeftTI.Align != RightTI.Align) 3041 return false; 3042 3043 // Consider all the kinds of non-dependent canonical types: 3044 // - functions and arrays aren't possible as return and parameter types 3045 3046 // - vector types of equal size can be arbitrarily mixed 3047 if (isa<VectorType>(left)) return isa<VectorType>(right); 3048 if (isa<VectorType>(right)) return false; 3049 3050 // - references should only match references of identical type 3051 // - structs, unions, and Objective-C objects must match more-or-less 3052 // exactly 3053 // - everything else should be a scalar 3054 if (!left->isScalarType() || !right->isScalarType()) 3055 return tryMatchRecordTypes(Context, strategy, left, right); 3056 3057 // Make scalars agree in kind, except count bools as chars, and group 3058 // all non-member pointers together. 3059 Type::ScalarTypeKind leftSK = left->getScalarTypeKind(); 3060 Type::ScalarTypeKind rightSK = right->getScalarTypeKind(); 3061 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral; 3062 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral; 3063 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer) 3064 leftSK = Type::STK_ObjCObjectPointer; 3065 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer) 3066 rightSK = Type::STK_ObjCObjectPointer; 3067 3068 // Note that data member pointers and function member pointers don't 3069 // intermix because of the size differences. 3070 3071 return (leftSK == rightSK); 3072 } 3073 3074 static bool tryMatchRecordTypes(ASTContext &Context, 3075 Sema::MethodMatchStrategy strategy, 3076 const Type *lt, const Type *rt) { 3077 assert(lt && rt && lt != rt); 3078 3079 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false; 3080 RecordDecl *left = cast<RecordType>(lt)->getDecl(); 3081 RecordDecl *right = cast<RecordType>(rt)->getDecl(); 3082 3083 // Require union-hood to match. 3084 if (left->isUnion() != right->isUnion()) return false; 3085 3086 // Require an exact match if either is non-POD. 3087 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) || 3088 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD())) 3089 return false; 3090 3091 // Require size and alignment to match. 3092 TypeInfo LeftTI = Context.getTypeInfo(lt); 3093 TypeInfo RightTI = Context.getTypeInfo(rt); 3094 if (LeftTI.Width != RightTI.Width) 3095 return false; 3096 3097 if (LeftTI.Align != RightTI.Align) 3098 return false; 3099 3100 // Require fields to match. 3101 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end(); 3102 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end(); 3103 for (; li != le && ri != re; ++li, ++ri) { 3104 if (!matchTypes(Context, strategy, li->getType(), ri->getType())) 3105 return false; 3106 } 3107 return (li == le && ri == re); 3108 } 3109 3110 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and 3111 /// returns true, or false, accordingly. 3112 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons 3113 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left, 3114 const ObjCMethodDecl *right, 3115 MethodMatchStrategy strategy) { 3116 if (!matchTypes(Context, strategy, left->getReturnType(), 3117 right->getReturnType())) 3118 return false; 3119 3120 // If either is hidden, it is not considered to match. 3121 if (left->isHidden() || right->isHidden()) 3122 return false; 3123 3124 if (getLangOpts().ObjCAutoRefCount && 3125 (left->hasAttr<NSReturnsRetainedAttr>() 3126 != right->hasAttr<NSReturnsRetainedAttr>() || 3127 left->hasAttr<NSConsumesSelfAttr>() 3128 != right->hasAttr<NSConsumesSelfAttr>())) 3129 return false; 3130 3131 ObjCMethodDecl::param_const_iterator 3132 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(), 3133 re = right->param_end(); 3134 3135 for (; li != le && ri != re; ++li, ++ri) { 3136 assert(ri != right->param_end() && "Param mismatch"); 3137 const ParmVarDecl *lparm = *li, *rparm = *ri; 3138 3139 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType())) 3140 return false; 3141 3142 if (getLangOpts().ObjCAutoRefCount && 3143 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>()) 3144 return false; 3145 } 3146 return true; 3147 } 3148 3149 void Sema::addMethodToGlobalList(ObjCMethodList *List, 3150 ObjCMethodDecl *Method) { 3151 // Record at the head of the list whether there were 0, 1, or >= 2 methods 3152 // inside categories. 3153 if (ObjCCategoryDecl *CD = 3154 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) 3155 if (!CD->IsClassExtension() && List->getBits() < 2) 3156 List->setBits(List->getBits() + 1); 3157 3158 // If the list is empty, make it a singleton list. 3159 if (List->getMethod() == nullptr) { 3160 List->setMethod(Method); 3161 List->setNext(nullptr); 3162 return; 3163 } 3164 3165 // We've seen a method with this name, see if we have already seen this type 3166 // signature. 3167 ObjCMethodList *Previous = List; 3168 for (; List; Previous = List, List = List->getNext()) { 3169 // If we are building a module, keep all of the methods. 3170 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) 3171 continue; 3172 3173 if (!MatchTwoMethodDeclarations(Method, List->getMethod())) { 3174 // Even if two method types do not match, we would like to say 3175 // there is more than one declaration so unavailability/deprecated 3176 // warning is not too noisy. 3177 if (!Method->isDefined()) 3178 List->setHasMoreThanOneDecl(true); 3179 continue; 3180 } 3181 3182 ObjCMethodDecl *PrevObjCMethod = List->getMethod(); 3183 3184 // Propagate the 'defined' bit. 3185 if (Method->isDefined()) 3186 PrevObjCMethod->setDefined(true); 3187 else { 3188 // Objective-C doesn't allow an @interface for a class after its 3189 // @implementation. So if Method is not defined and there already is 3190 // an entry for this type signature, Method has to be for a different 3191 // class than PrevObjCMethod. 3192 List->setHasMoreThanOneDecl(true); 3193 } 3194 3195 // If a method is deprecated, push it in the global pool. 3196 // This is used for better diagnostics. 3197 if (Method->isDeprecated()) { 3198 if (!PrevObjCMethod->isDeprecated()) 3199 List->setMethod(Method); 3200 } 3201 // If the new method is unavailable, push it into global pool 3202 // unless previous one is deprecated. 3203 if (Method->isUnavailable()) { 3204 if (PrevObjCMethod->getAvailability() < AR_Deprecated) 3205 List->setMethod(Method); 3206 } 3207 3208 return; 3209 } 3210 3211 // We have a new signature for an existing method - add it. 3212 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded". 3213 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>(); 3214 Previous->setNext(new (Mem) ObjCMethodList(Method)); 3215 } 3216 3217 /// \brief Read the contents of the method pool for a given selector from 3218 /// external storage. 3219 void Sema::ReadMethodPool(Selector Sel) { 3220 assert(ExternalSource && "We need an external AST source"); 3221 ExternalSource->ReadMethodPool(Sel); 3222 } 3223 3224 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, 3225 bool instance) { 3226 // Ignore methods of invalid containers. 3227 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl()) 3228 return; 3229 3230 if (ExternalSource) 3231 ReadMethodPool(Method->getSelector()); 3232 3233 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector()); 3234 if (Pos == MethodPool.end()) 3235 Pos = MethodPool.insert(std::make_pair(Method->getSelector(), 3236 GlobalMethods())).first; 3237 3238 Method->setDefined(impl); 3239 3240 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second; 3241 addMethodToGlobalList(&Entry, Method); 3242 } 3243 3244 /// Determines if this is an "acceptable" loose mismatch in the global 3245 /// method pool. This exists mostly as a hack to get around certain 3246 /// global mismatches which we can't afford to make warnings / errors. 3247 /// Really, what we want is a way to take a method out of the global 3248 /// method pool. 3249 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen, 3250 ObjCMethodDecl *other) { 3251 if (!chosen->isInstanceMethod()) 3252 return false; 3253 3254 Selector sel = chosen->getSelector(); 3255 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length") 3256 return false; 3257 3258 // Don't complain about mismatches for -length if the method we 3259 // chose has an integral result type. 3260 return (chosen->getReturnType()->isIntegerType()); 3261 } 3262 3263 bool Sema::CollectMultipleMethodsInGlobalPool( 3264 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, bool instance) { 3265 if (ExternalSource) 3266 ReadMethodPool(Sel); 3267 3268 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3269 if (Pos == MethodPool.end()) 3270 return false; 3271 // Gather the non-hidden methods. 3272 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 3273 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) 3274 if (M->getMethod() && !M->getMethod()->isHidden()) 3275 Methods.push_back(M->getMethod()); 3276 return Methods.size() > 1; 3277 } 3278 3279 bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, 3280 SourceRange R, 3281 bool receiverIdOrClass) { 3282 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3283 // Test for no method in the pool which should not trigger any warning by 3284 // caller. 3285 if (Pos == MethodPool.end()) 3286 return true; 3287 ObjCMethodList &MethList = 3288 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second; 3289 3290 // Diagnose finding more than one method in global pool 3291 SmallVector<ObjCMethodDecl *, 4> Methods; 3292 Methods.push_back(BestMethod); 3293 for (ObjCMethodList *ML = &MethList; ML; ML = ML->getNext()) 3294 if (ObjCMethodDecl *M = ML->getMethod()) 3295 if (!M->isHidden() && M != BestMethod && !M->hasAttr<UnavailableAttr>()) 3296 Methods.push_back(M); 3297 if (Methods.size() > 1) 3298 DiagnoseMultipleMethodInGlobalPool(Methods, Sel, R, receiverIdOrClass); 3299 3300 return MethList.hasMoreThanOneDecl(); 3301 } 3302 3303 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R, 3304 bool receiverIdOrClass, 3305 bool instance) { 3306 if (ExternalSource) 3307 ReadMethodPool(Sel); 3308 3309 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3310 if (Pos == MethodPool.end()) 3311 return nullptr; 3312 3313 // Gather the non-hidden methods. 3314 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 3315 SmallVector<ObjCMethodDecl *, 4> Methods; 3316 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) { 3317 if (M->getMethod() && !M->getMethod()->isHidden()) 3318 return M->getMethod(); 3319 } 3320 return nullptr; 3321 } 3322 3323 void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, 3324 Selector Sel, SourceRange R, 3325 bool receiverIdOrClass) { 3326 // We found multiple methods, so we may have to complain. 3327 bool issueDiagnostic = false, issueError = false; 3328 3329 // We support a warning which complains about *any* difference in 3330 // method signature. 3331 bool strictSelectorMatch = 3332 receiverIdOrClass && 3333 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin()); 3334 if (strictSelectorMatch) { 3335 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3336 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) { 3337 issueDiagnostic = true; 3338 break; 3339 } 3340 } 3341 } 3342 3343 // If we didn't see any strict differences, we won't see any loose 3344 // differences. In ARC, however, we also need to check for loose 3345 // mismatches, because most of them are errors. 3346 if (!strictSelectorMatch || 3347 (issueDiagnostic && getLangOpts().ObjCAutoRefCount)) 3348 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3349 // This checks if the methods differ in type mismatch. 3350 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) && 3351 !isAcceptableMethodMismatch(Methods[0], Methods[I])) { 3352 issueDiagnostic = true; 3353 if (getLangOpts().ObjCAutoRefCount) 3354 issueError = true; 3355 break; 3356 } 3357 } 3358 3359 if (issueDiagnostic) { 3360 if (issueError) 3361 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R; 3362 else if (strictSelectorMatch) 3363 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R; 3364 else 3365 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R; 3366 3367 Diag(Methods[0]->getLocStart(), 3368 issueError ? diag::note_possibility : diag::note_using) 3369 << Methods[0]->getSourceRange(); 3370 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3371 Diag(Methods[I]->getLocStart(), diag::note_also_found) 3372 << Methods[I]->getSourceRange(); 3373 } 3374 } 3375 } 3376 3377 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) { 3378 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3379 if (Pos == MethodPool.end()) 3380 return nullptr; 3381 3382 GlobalMethods &Methods = Pos->second; 3383 for (const ObjCMethodList *Method = &Methods.first; Method; 3384 Method = Method->getNext()) 3385 if (Method->getMethod() && 3386 (Method->getMethod()->isDefined() || 3387 Method->getMethod()->isPropertyAccessor())) 3388 return Method->getMethod(); 3389 3390 for (const ObjCMethodList *Method = &Methods.second; Method; 3391 Method = Method->getNext()) 3392 if (Method->getMethod() && 3393 (Method->getMethod()->isDefined() || 3394 Method->getMethod()->isPropertyAccessor())) 3395 return Method->getMethod(); 3396 return nullptr; 3397 } 3398 3399 static void 3400 HelperSelectorsForTypoCorrection( 3401 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod, 3402 StringRef Typo, const ObjCMethodDecl * Method) { 3403 const unsigned MaxEditDistance = 1; 3404 unsigned BestEditDistance = MaxEditDistance + 1; 3405 std::string MethodName = Method->getSelector().getAsString(); 3406 3407 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size()); 3408 if (MinPossibleEditDistance > 0 && 3409 Typo.size() / MinPossibleEditDistance < 1) 3410 return; 3411 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance); 3412 if (EditDistance > MaxEditDistance) 3413 return; 3414 if (EditDistance == BestEditDistance) 3415 BestMethod.push_back(Method); 3416 else if (EditDistance < BestEditDistance) { 3417 BestMethod.clear(); 3418 BestMethod.push_back(Method); 3419 } 3420 } 3421 3422 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel, 3423 QualType ObjectType) { 3424 if (ObjectType.isNull()) 3425 return true; 3426 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/)) 3427 return true; 3428 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) != 3429 nullptr; 3430 } 3431 3432 const ObjCMethodDecl * 3433 Sema::SelectorsForTypoCorrection(Selector Sel, 3434 QualType ObjectType) { 3435 unsigned NumArgs = Sel.getNumArgs(); 3436 SmallVector<const ObjCMethodDecl *, 8> Methods; 3437 bool ObjectIsId = true, ObjectIsClass = true; 3438 if (ObjectType.isNull()) 3439 ObjectIsId = ObjectIsClass = false; 3440 else if (!ObjectType->isObjCObjectPointerType()) 3441 return nullptr; 3442 else if (const ObjCObjectPointerType *ObjCPtr = 3443 ObjectType->getAsObjCInterfacePointerType()) { 3444 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0); 3445 ObjectIsId = ObjectIsClass = false; 3446 } 3447 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType()) 3448 ObjectIsClass = false; 3449 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType()) 3450 ObjectIsId = false; 3451 else 3452 return nullptr; 3453 3454 for (GlobalMethodPool::iterator b = MethodPool.begin(), 3455 e = MethodPool.end(); b != e; b++) { 3456 // instance methods 3457 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext()) 3458 if (M->getMethod() && 3459 (M->getMethod()->getSelector().getNumArgs() == NumArgs) && 3460 (M->getMethod()->getSelector() != Sel)) { 3461 if (ObjectIsId) 3462 Methods.push_back(M->getMethod()); 3463 else if (!ObjectIsClass && 3464 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(), 3465 ObjectType)) 3466 Methods.push_back(M->getMethod()); 3467 } 3468 // class methods 3469 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext()) 3470 if (M->getMethod() && 3471 (M->getMethod()->getSelector().getNumArgs() == NumArgs) && 3472 (M->getMethod()->getSelector() != Sel)) { 3473 if (ObjectIsClass) 3474 Methods.push_back(M->getMethod()); 3475 else if (!ObjectIsId && 3476 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(), 3477 ObjectType)) 3478 Methods.push_back(M->getMethod()); 3479 } 3480 } 3481 3482 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods; 3483 for (unsigned i = 0, e = Methods.size(); i < e; i++) { 3484 HelperSelectorsForTypoCorrection(SelectedMethods, 3485 Sel.getAsString(), Methods[i]); 3486 } 3487 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr; 3488 } 3489 3490 /// DiagnoseDuplicateIvars - 3491 /// Check for duplicate ivars in the entire class at the start of 3492 /// \@implementation. This becomes necesssary because class extension can 3493 /// add ivars to a class in random order which will not be known until 3494 /// class's \@implementation is seen. 3495 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, 3496 ObjCInterfaceDecl *SID) { 3497 for (auto *Ivar : ID->ivars()) { 3498 if (Ivar->isInvalidDecl()) 3499 continue; 3500 if (IdentifierInfo *II = Ivar->getIdentifier()) { 3501 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II); 3502 if (prevIvar) { 3503 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 3504 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 3505 Ivar->setInvalidDecl(); 3506 } 3507 } 3508 } 3509 } 3510 3511 /// Diagnose attempts to define ARC-__weak ivars when __weak is disabled. 3512 static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) { 3513 if (S.getLangOpts().ObjCWeak) return; 3514 3515 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin(); 3516 ivar; ivar = ivar->getNextIvar()) { 3517 if (ivar->isInvalidDecl()) continue; 3518 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 3519 if (S.getLangOpts().ObjCWeakRuntime) { 3520 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled); 3521 } else { 3522 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime); 3523 } 3524 } 3525 } 3526 } 3527 3528 Sema::ObjCContainerKind Sema::getObjCContainerKind() const { 3529 switch (CurContext->getDeclKind()) { 3530 case Decl::ObjCInterface: 3531 return Sema::OCK_Interface; 3532 case Decl::ObjCProtocol: 3533 return Sema::OCK_Protocol; 3534 case Decl::ObjCCategory: 3535 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension()) 3536 return Sema::OCK_ClassExtension; 3537 return Sema::OCK_Category; 3538 case Decl::ObjCImplementation: 3539 return Sema::OCK_Implementation; 3540 case Decl::ObjCCategoryImpl: 3541 return Sema::OCK_CategoryImplementation; 3542 3543 default: 3544 return Sema::OCK_None; 3545 } 3546 } 3547 3548 // Note: For class/category implementations, allMethods is always null. 3549 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods, 3550 ArrayRef<DeclGroupPtrTy> allTUVars) { 3551 if (getObjCContainerKind() == Sema::OCK_None) 3552 return nullptr; 3553 3554 assert(AtEnd.isValid() && "Invalid location for '@end'"); 3555 3556 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 3557 Decl *ClassDecl = cast<Decl>(OCD); 3558 3559 bool isInterfaceDeclKind = 3560 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl) 3561 || isa<ObjCProtocolDecl>(ClassDecl); 3562 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl); 3563 3564 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext. 3565 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap; 3566 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap; 3567 3568 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) { 3569 ObjCMethodDecl *Method = 3570 cast_or_null<ObjCMethodDecl>(allMethods[i]); 3571 3572 if (!Method) continue; // Already issued a diagnostic. 3573 if (Method->isInstanceMethod()) { 3574 /// Check for instance method of the same name with incompatible types 3575 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()]; 3576 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 3577 : false; 3578 if ((isInterfaceDeclKind && PrevMethod && !match) 3579 || (checkIdenticalMethods && match)) { 3580 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 3581 << Method->getDeclName(); 3582 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3583 Method->setInvalidDecl(); 3584 } else { 3585 if (PrevMethod) { 3586 Method->setAsRedeclaration(PrevMethod); 3587 if (!Context.getSourceManager().isInSystemHeader( 3588 Method->getLocation())) 3589 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 3590 << Method->getDeclName(); 3591 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3592 } 3593 InsMap[Method->getSelector()] = Method; 3594 /// The following allows us to typecheck messages to "id". 3595 AddInstanceMethodToGlobalPool(Method); 3596 } 3597 } else { 3598 /// Check for class method of the same name with incompatible types 3599 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()]; 3600 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 3601 : false; 3602 if ((isInterfaceDeclKind && PrevMethod && !match) 3603 || (checkIdenticalMethods && match)) { 3604 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 3605 << Method->getDeclName(); 3606 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3607 Method->setInvalidDecl(); 3608 } else { 3609 if (PrevMethod) { 3610 Method->setAsRedeclaration(PrevMethod); 3611 if (!Context.getSourceManager().isInSystemHeader( 3612 Method->getLocation())) 3613 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 3614 << Method->getDeclName(); 3615 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3616 } 3617 ClsMap[Method->getSelector()] = Method; 3618 AddFactoryMethodToGlobalPool(Method); 3619 } 3620 } 3621 } 3622 if (isa<ObjCInterfaceDecl>(ClassDecl)) { 3623 // Nothing to do here. 3624 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 3625 // Categories are used to extend the class by declaring new methods. 3626 // By the same token, they are also used to add new properties. No 3627 // need to compare the added property to those in the class. 3628 3629 if (C->IsClassExtension()) { 3630 ObjCInterfaceDecl *CCPrimary = C->getClassInterface(); 3631 DiagnoseClassExtensionDupMethods(C, CCPrimary); 3632 } 3633 } 3634 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) { 3635 if (CDecl->getIdentifier()) 3636 // ProcessPropertyDecl is responsible for diagnosing conflicts with any 3637 // user-defined setter/getter. It also synthesizes setter/getter methods 3638 // and adds them to the DeclContext and global method pools. 3639 for (auto *I : CDecl->properties()) 3640 ProcessPropertyDecl(I); 3641 CDecl->setAtEndRange(AtEnd); 3642 } 3643 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) { 3644 IC->setAtEndRange(AtEnd); 3645 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) { 3646 // Any property declared in a class extension might have user 3647 // declared setter or getter in current class extension or one 3648 // of the other class extensions. Mark them as synthesized as 3649 // property will be synthesized when property with same name is 3650 // seen in the @implementation. 3651 for (const auto *Ext : IDecl->visible_extensions()) { 3652 for (const auto *Property : Ext->properties()) { 3653 // Skip over properties declared @dynamic 3654 if (const ObjCPropertyImplDecl *PIDecl 3655 = IC->FindPropertyImplDecl(Property->getIdentifier())) 3656 if (PIDecl->getPropertyImplementation() 3657 == ObjCPropertyImplDecl::Dynamic) 3658 continue; 3659 3660 for (const auto *Ext : IDecl->visible_extensions()) { 3661 if (ObjCMethodDecl *GetterMethod 3662 = Ext->getInstanceMethod(Property->getGetterName())) 3663 GetterMethod->setPropertyAccessor(true); 3664 if (!Property->isReadOnly()) 3665 if (ObjCMethodDecl *SetterMethod 3666 = Ext->getInstanceMethod(Property->getSetterName())) 3667 SetterMethod->setPropertyAccessor(true); 3668 } 3669 } 3670 } 3671 ImplMethodsVsClassMethods(S, IC, IDecl); 3672 AtomicPropertySetterGetterRules(IC, IDecl); 3673 DiagnoseOwningPropertyGetterSynthesis(IC); 3674 DiagnoseUnusedBackingIvarInAccessor(S, IC); 3675 if (IDecl->hasDesignatedInitializers()) 3676 DiagnoseMissingDesignatedInitOverrides(IC, IDecl); 3677 DiagnoseWeakIvars(*this, IC); 3678 3679 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>(); 3680 if (IDecl->getSuperClass() == nullptr) { 3681 // This class has no superclass, so check that it has been marked with 3682 // __attribute((objc_root_class)). 3683 if (!HasRootClassAttr) { 3684 SourceLocation DeclLoc(IDecl->getLocation()); 3685 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc)); 3686 Diag(DeclLoc, diag::warn_objc_root_class_missing) 3687 << IDecl->getIdentifier(); 3688 // See if NSObject is in the current scope, and if it is, suggest 3689 // adding " : NSObject " to the class declaration. 3690 NamedDecl *IF = LookupSingleName(TUScope, 3691 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject), 3692 DeclLoc, LookupOrdinaryName); 3693 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 3694 if (NSObjectDecl && NSObjectDecl->getDefinition()) { 3695 Diag(SuperClassLoc, diag::note_objc_needs_superclass) 3696 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject "); 3697 } else { 3698 Diag(SuperClassLoc, diag::note_objc_needs_superclass); 3699 } 3700 } 3701 } else if (HasRootClassAttr) { 3702 // Complain that only root classes may have this attribute. 3703 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass); 3704 } 3705 3706 if (LangOpts.ObjCRuntime.isNonFragile()) { 3707 while (IDecl->getSuperClass()) { 3708 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass()); 3709 IDecl = IDecl->getSuperClass(); 3710 } 3711 } 3712 } 3713 SetIvarInitializers(IC); 3714 } else if (ObjCCategoryImplDecl* CatImplClass = 3715 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) { 3716 CatImplClass->setAtEndRange(AtEnd); 3717 3718 // Find category interface decl and then check that all methods declared 3719 // in this interface are implemented in the category @implementation. 3720 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) { 3721 if (ObjCCategoryDecl *Cat 3722 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) { 3723 ImplMethodsVsClassMethods(S, CatImplClass, Cat); 3724 } 3725 } 3726 } 3727 if (isInterfaceDeclKind) { 3728 // Reject invalid vardecls. 3729 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 3730 DeclGroupRef DG = allTUVars[i].get(); 3731 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 3732 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) { 3733 if (!VDecl->hasExternalStorage()) 3734 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass); 3735 } 3736 } 3737 } 3738 ActOnObjCContainerFinishDefinition(); 3739 3740 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 3741 DeclGroupRef DG = allTUVars[i].get(); 3742 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 3743 (*I)->setTopLevelDeclInObjCContainer(); 3744 Consumer.HandleTopLevelDeclInObjCContainer(DG); 3745 } 3746 3747 ActOnDocumentableDecl(ClassDecl); 3748 return ClassDecl; 3749 } 3750 3751 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for 3752 /// objective-c's type qualifier from the parser version of the same info. 3753 static Decl::ObjCDeclQualifier 3754 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) { 3755 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal; 3756 } 3757 3758 /// \brief Check whether the declared result type of the given Objective-C 3759 /// method declaration is compatible with the method's class. 3760 /// 3761 static Sema::ResultTypeCompatibilityKind 3762 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, 3763 ObjCInterfaceDecl *CurrentClass) { 3764 QualType ResultType = Method->getReturnType(); 3765 3766 // If an Objective-C method inherits its related result type, then its 3767 // declared result type must be compatible with its own class type. The 3768 // declared result type is compatible if: 3769 if (const ObjCObjectPointerType *ResultObjectType 3770 = ResultType->getAs<ObjCObjectPointerType>()) { 3771 // - it is id or qualified id, or 3772 if (ResultObjectType->isObjCIdType() || 3773 ResultObjectType->isObjCQualifiedIdType()) 3774 return Sema::RTC_Compatible; 3775 3776 if (CurrentClass) { 3777 if (ObjCInterfaceDecl *ResultClass 3778 = ResultObjectType->getInterfaceDecl()) { 3779 // - it is the same as the method's class type, or 3780 if (declaresSameEntity(CurrentClass, ResultClass)) 3781 return Sema::RTC_Compatible; 3782 3783 // - it is a superclass of the method's class type 3784 if (ResultClass->isSuperClassOf(CurrentClass)) 3785 return Sema::RTC_Compatible; 3786 } 3787 } else { 3788 // Any Objective-C pointer type might be acceptable for a protocol 3789 // method; we just don't know. 3790 return Sema::RTC_Unknown; 3791 } 3792 } 3793 3794 return Sema::RTC_Incompatible; 3795 } 3796 3797 namespace { 3798 /// A helper class for searching for methods which a particular method 3799 /// overrides. 3800 class OverrideSearch { 3801 public: 3802 Sema &S; 3803 ObjCMethodDecl *Method; 3804 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden; 3805 bool Recursive; 3806 3807 public: 3808 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) { 3809 Selector selector = method->getSelector(); 3810 3811 // Bypass this search if we've never seen an instance/class method 3812 // with this selector before. 3813 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector); 3814 if (it == S.MethodPool.end()) { 3815 if (!S.getExternalSource()) return; 3816 S.ReadMethodPool(selector); 3817 3818 it = S.MethodPool.find(selector); 3819 if (it == S.MethodPool.end()) 3820 return; 3821 } 3822 ObjCMethodList &list = 3823 method->isInstanceMethod() ? it->second.first : it->second.second; 3824 if (!list.getMethod()) return; 3825 3826 ObjCContainerDecl *container 3827 = cast<ObjCContainerDecl>(method->getDeclContext()); 3828 3829 // Prevent the search from reaching this container again. This is 3830 // important with categories, which override methods from the 3831 // interface and each other. 3832 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) { 3833 searchFromContainer(container); 3834 if (ObjCInterfaceDecl *Interface = Category->getClassInterface()) 3835 searchFromContainer(Interface); 3836 } else { 3837 searchFromContainer(container); 3838 } 3839 } 3840 3841 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator; 3842 iterator begin() const { return Overridden.begin(); } 3843 iterator end() const { return Overridden.end(); } 3844 3845 private: 3846 void searchFromContainer(ObjCContainerDecl *container) { 3847 if (container->isInvalidDecl()) return; 3848 3849 switch (container->getDeclKind()) { 3850 #define OBJCCONTAINER(type, base) \ 3851 case Decl::type: \ 3852 searchFrom(cast<type##Decl>(container)); \ 3853 break; 3854 #define ABSTRACT_DECL(expansion) 3855 #define DECL(type, base) \ 3856 case Decl::type: 3857 #include "clang/AST/DeclNodes.inc" 3858 llvm_unreachable("not an ObjC container!"); 3859 } 3860 } 3861 3862 void searchFrom(ObjCProtocolDecl *protocol) { 3863 if (!protocol->hasDefinition()) 3864 return; 3865 3866 // A method in a protocol declaration overrides declarations from 3867 // referenced ("parent") protocols. 3868 search(protocol->getReferencedProtocols()); 3869 } 3870 3871 void searchFrom(ObjCCategoryDecl *category) { 3872 // A method in a category declaration overrides declarations from 3873 // the main class and from protocols the category references. 3874 // The main class is handled in the constructor. 3875 search(category->getReferencedProtocols()); 3876 } 3877 3878 void searchFrom(ObjCCategoryImplDecl *impl) { 3879 // A method in a category definition that has a category 3880 // declaration overrides declarations from the category 3881 // declaration. 3882 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) { 3883 search(category); 3884 if (ObjCInterfaceDecl *Interface = category->getClassInterface()) 3885 search(Interface); 3886 3887 // Otherwise it overrides declarations from the class. 3888 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) { 3889 search(Interface); 3890 } 3891 } 3892 3893 void searchFrom(ObjCInterfaceDecl *iface) { 3894 // A method in a class declaration overrides declarations from 3895 if (!iface->hasDefinition()) 3896 return; 3897 3898 // - categories, 3899 for (auto *Cat : iface->known_categories()) 3900 search(Cat); 3901 3902 // - the super class, and 3903 if (ObjCInterfaceDecl *super = iface->getSuperClass()) 3904 search(super); 3905 3906 // - any referenced protocols. 3907 search(iface->getReferencedProtocols()); 3908 } 3909 3910 void searchFrom(ObjCImplementationDecl *impl) { 3911 // A method in a class implementation overrides declarations from 3912 // the class interface. 3913 if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) 3914 search(Interface); 3915 } 3916 3917 void search(const ObjCProtocolList &protocols) { 3918 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end(); 3919 i != e; ++i) 3920 search(*i); 3921 } 3922 3923 void search(ObjCContainerDecl *container) { 3924 // Check for a method in this container which matches this selector. 3925 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(), 3926 Method->isInstanceMethod(), 3927 /*AllowHidden=*/true); 3928 3929 // If we find one, record it and bail out. 3930 if (meth) { 3931 Overridden.insert(meth); 3932 return; 3933 } 3934 3935 // Otherwise, search for methods that a hypothetical method here 3936 // would have overridden. 3937 3938 // Note that we're now in a recursive case. 3939 Recursive = true; 3940 3941 searchFromContainer(container); 3942 } 3943 }; 3944 } // end anonymous namespace 3945 3946 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 3947 ObjCInterfaceDecl *CurrentClass, 3948 ResultTypeCompatibilityKind RTC) { 3949 // Search for overridden methods and merge information down from them. 3950 OverrideSearch overrides(*this, ObjCMethod); 3951 // Keep track if the method overrides any method in the class's base classes, 3952 // its protocols, or its categories' protocols; we will keep that info 3953 // in the ObjCMethodDecl. 3954 // For this info, a method in an implementation is not considered as 3955 // overriding the same method in the interface or its categories. 3956 bool hasOverriddenMethodsInBaseOrProtocol = false; 3957 for (OverrideSearch::iterator 3958 i = overrides.begin(), e = overrides.end(); i != e; ++i) { 3959 ObjCMethodDecl *overridden = *i; 3960 3961 if (!hasOverriddenMethodsInBaseOrProtocol) { 3962 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) || 3963 CurrentClass != overridden->getClassInterface() || 3964 overridden->isOverriding()) { 3965 hasOverriddenMethodsInBaseOrProtocol = true; 3966 3967 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) { 3968 // OverrideSearch will return as "overridden" the same method in the 3969 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to 3970 // check whether a category of a base class introduced a method with the 3971 // same selector, after the interface method declaration. 3972 // To avoid unnecessary lookups in the majority of cases, we use the 3973 // extra info bits in GlobalMethodPool to check whether there were any 3974 // category methods with this selector. 3975 GlobalMethodPool::iterator It = 3976 MethodPool.find(ObjCMethod->getSelector()); 3977 if (It != MethodPool.end()) { 3978 ObjCMethodList &List = 3979 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second; 3980 unsigned CategCount = List.getBits(); 3981 if (CategCount > 0) { 3982 // If the method is in a category we'll do lookup if there were at 3983 // least 2 category methods recorded, otherwise only one will do. 3984 if (CategCount > 1 || 3985 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) { 3986 OverrideSearch overrides(*this, overridden); 3987 for (OverrideSearch::iterator 3988 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) { 3989 ObjCMethodDecl *SuperOverridden = *OI; 3990 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) || 3991 CurrentClass != SuperOverridden->getClassInterface()) { 3992 hasOverriddenMethodsInBaseOrProtocol = true; 3993 overridden->setOverriding(true); 3994 break; 3995 } 3996 } 3997 } 3998 } 3999 } 4000 } 4001 } 4002 4003 // Propagate down the 'related result type' bit from overridden methods. 4004 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType()) 4005 ObjCMethod->SetRelatedResultType(); 4006 4007 // Then merge the declarations. 4008 mergeObjCMethodDecls(ObjCMethod, overridden); 4009 4010 if (ObjCMethod->isImplicit() && overridden->isImplicit()) 4011 continue; // Conflicting properties are detected elsewhere. 4012 4013 // Check for overriding methods 4014 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || 4015 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())) 4016 CheckConflictingOverridingMethod(ObjCMethod, overridden, 4017 isa<ObjCProtocolDecl>(overridden->getDeclContext())); 4018 4019 if (CurrentClass && overridden->getDeclContext() != CurrentClass && 4020 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) && 4021 !overridden->isImplicit() /* not meant for properties */) { 4022 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(), 4023 E = ObjCMethod->param_end(); 4024 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(), 4025 PrevE = overridden->param_end(); 4026 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) { 4027 assert(PrevI != overridden->param_end() && "Param mismatch"); 4028 QualType T1 = Context.getCanonicalType((*ParamI)->getType()); 4029 QualType T2 = Context.getCanonicalType((*PrevI)->getType()); 4030 // If type of argument of method in this class does not match its 4031 // respective argument type in the super class method, issue warning; 4032 if (!Context.typesAreCompatible(T1, T2)) { 4033 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super) 4034 << T1 << T2; 4035 Diag(overridden->getLocation(), diag::note_previous_declaration); 4036 break; 4037 } 4038 } 4039 } 4040 } 4041 4042 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol); 4043 } 4044 4045 /// Merge type nullability from for a redeclaration of the same entity, 4046 /// producing the updated type of the redeclared entity. 4047 static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc, 4048 QualType type, 4049 bool usesCSKeyword, 4050 SourceLocation prevLoc, 4051 QualType prevType, 4052 bool prevUsesCSKeyword) { 4053 // Determine the nullability of both types. 4054 auto nullability = type->getNullability(S.Context); 4055 auto prevNullability = prevType->getNullability(S.Context); 4056 4057 // Easy case: both have nullability. 4058 if (nullability.hasValue() == prevNullability.hasValue()) { 4059 // Neither has nullability; continue. 4060 if (!nullability) 4061 return type; 4062 4063 // The nullabilities are equivalent; do nothing. 4064 if (*nullability == *prevNullability) 4065 return type; 4066 4067 // Complain about mismatched nullability. 4068 S.Diag(loc, diag::err_nullability_conflicting) 4069 << DiagNullabilityKind(*nullability, usesCSKeyword) 4070 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword); 4071 return type; 4072 } 4073 4074 // If it's the redeclaration that has nullability, don't change anything. 4075 if (nullability) 4076 return type; 4077 4078 // Otherwise, provide the result with the same nullability. 4079 return S.Context.getAttributedType( 4080 AttributedType::getNullabilityAttrKind(*prevNullability), 4081 type, type); 4082 } 4083 4084 /// Merge information from the declaration of a method in the \@interface 4085 /// (or a category/extension) into the corresponding method in the 4086 /// @implementation (for a class or category). 4087 static void mergeInterfaceMethodToImpl(Sema &S, 4088 ObjCMethodDecl *method, 4089 ObjCMethodDecl *prevMethod) { 4090 // Merge the objc_requires_super attribute. 4091 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() && 4092 !method->hasAttr<ObjCRequiresSuperAttr>()) { 4093 // merge the attribute into implementation. 4094 method->addAttr( 4095 ObjCRequiresSuperAttr::CreateImplicit(S.Context, 4096 method->getLocation())); 4097 } 4098 4099 // Merge nullability of the result type. 4100 QualType newReturnType 4101 = mergeTypeNullabilityForRedecl( 4102 S, method->getReturnTypeSourceRange().getBegin(), 4103 method->getReturnType(), 4104 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability, 4105 prevMethod->getReturnTypeSourceRange().getBegin(), 4106 prevMethod->getReturnType(), 4107 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability); 4108 method->setReturnType(newReturnType); 4109 4110 // Handle each of the parameters. 4111 unsigned numParams = method->param_size(); 4112 unsigned numPrevParams = prevMethod->param_size(); 4113 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) { 4114 ParmVarDecl *param = method->param_begin()[i]; 4115 ParmVarDecl *prevParam = prevMethod->param_begin()[i]; 4116 4117 // Merge nullability. 4118 QualType newParamType 4119 = mergeTypeNullabilityForRedecl( 4120 S, param->getLocation(), param->getType(), 4121 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability, 4122 prevParam->getLocation(), prevParam->getType(), 4123 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability); 4124 param->setType(newParamType); 4125 } 4126 } 4127 4128 Decl *Sema::ActOnMethodDeclaration( 4129 Scope *S, 4130 SourceLocation MethodLoc, SourceLocation EndLoc, 4131 tok::TokenKind MethodType, 4132 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 4133 ArrayRef<SourceLocation> SelectorLocs, 4134 Selector Sel, 4135 // optional arguments. The number of types/arguments is obtained 4136 // from the Sel.getNumArgs(). 4137 ObjCArgInfo *ArgInfo, 4138 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 4139 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind, 4140 bool isVariadic, bool MethodDefinition) { 4141 // Make sure we can establish a context for the method. 4142 if (!CurContext->isObjCContainer()) { 4143 Diag(MethodLoc, diag::error_missing_method_context); 4144 return nullptr; 4145 } 4146 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 4147 Decl *ClassDecl = cast<Decl>(OCD); 4148 QualType resultDeclType; 4149 4150 bool HasRelatedResultType = false; 4151 TypeSourceInfo *ReturnTInfo = nullptr; 4152 if (ReturnType) { 4153 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo); 4154 4155 if (CheckFunctionReturnType(resultDeclType, MethodLoc)) 4156 return nullptr; 4157 4158 QualType bareResultType = resultDeclType; 4159 (void)AttributedType::stripOuterNullability(bareResultType); 4160 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType()); 4161 } else { // get the type for "id". 4162 resultDeclType = Context.getObjCIdType(); 4163 Diag(MethodLoc, diag::warn_missing_method_return_type) 4164 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)"); 4165 } 4166 4167 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create( 4168 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext, 4169 MethodType == tok::minus, isVariadic, 4170 /*isPropertyAccessor=*/false, 4171 /*isImplicitlyDeclared=*/false, /*isDefined=*/false, 4172 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional 4173 : ObjCMethodDecl::Required, 4174 HasRelatedResultType); 4175 4176 SmallVector<ParmVarDecl*, 16> Params; 4177 4178 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) { 4179 QualType ArgType; 4180 TypeSourceInfo *DI; 4181 4182 if (!ArgInfo[i].Type) { 4183 ArgType = Context.getObjCIdType(); 4184 DI = nullptr; 4185 } else { 4186 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI); 4187 } 4188 4189 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, 4190 LookupOrdinaryName, ForRedeclaration); 4191 LookupName(R, S); 4192 if (R.isSingleResult()) { 4193 NamedDecl *PrevDecl = R.getFoundDecl(); 4194 if (S->isDeclScope(PrevDecl)) { 4195 Diag(ArgInfo[i].NameLoc, 4196 (MethodDefinition ? diag::warn_method_param_redefinition 4197 : diag::warn_method_param_declaration)) 4198 << ArgInfo[i].Name; 4199 Diag(PrevDecl->getLocation(), 4200 diag::note_previous_declaration); 4201 } 4202 } 4203 4204 SourceLocation StartLoc = DI 4205 ? DI->getTypeLoc().getBeginLoc() 4206 : ArgInfo[i].NameLoc; 4207 4208 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc, 4209 ArgInfo[i].NameLoc, ArgInfo[i].Name, 4210 ArgType, DI, SC_None); 4211 4212 Param->setObjCMethodScopeInfo(i); 4213 4214 Param->setObjCDeclQualifier( 4215 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier())); 4216 4217 // Apply the attributes to the parameter. 4218 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs); 4219 4220 if (Param->hasAttr<BlocksAttr>()) { 4221 Diag(Param->getLocation(), diag::err_block_on_nonlocal); 4222 Param->setInvalidDecl(); 4223 } 4224 S->AddDecl(Param); 4225 IdResolver.AddDecl(Param); 4226 4227 Params.push_back(Param); 4228 } 4229 4230 for (unsigned i = 0, e = CNumArgs; i != e; ++i) { 4231 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param); 4232 QualType ArgType = Param->getType(); 4233 if (ArgType.isNull()) 4234 ArgType = Context.getObjCIdType(); 4235 else 4236 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]). 4237 ArgType = Context.getAdjustedParameterType(ArgType); 4238 4239 Param->setDeclContext(ObjCMethod); 4240 Params.push_back(Param); 4241 } 4242 4243 ObjCMethod->setMethodParams(Context, Params, SelectorLocs); 4244 ObjCMethod->setObjCDeclQualifier( 4245 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier())); 4246 4247 if (AttrList) 4248 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList); 4249 4250 // Add the method now. 4251 const ObjCMethodDecl *PrevMethod = nullptr; 4252 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) { 4253 if (MethodType == tok::minus) { 4254 PrevMethod = ImpDecl->getInstanceMethod(Sel); 4255 ImpDecl->addInstanceMethod(ObjCMethod); 4256 } else { 4257 PrevMethod = ImpDecl->getClassMethod(Sel); 4258 ImpDecl->addClassMethod(ObjCMethod); 4259 } 4260 4261 // Merge information from the @interface declaration into the 4262 // @implementation. 4263 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) { 4264 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(), 4265 ObjCMethod->isInstanceMethod())) { 4266 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD); 4267 4268 // Warn about defining -dealloc in a category. 4269 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() && 4270 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) { 4271 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category) 4272 << ObjCMethod->getDeclName(); 4273 } 4274 } 4275 } 4276 } else { 4277 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod); 4278 } 4279 4280 if (PrevMethod) { 4281 // You can never have two method definitions with the same name. 4282 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl) 4283 << ObjCMethod->getDeclName(); 4284 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 4285 ObjCMethod->setInvalidDecl(); 4286 return ObjCMethod; 4287 } 4288 4289 // If this Objective-C method does not have a related result type, but we 4290 // are allowed to infer related result types, try to do so based on the 4291 // method family. 4292 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl); 4293 if (!CurrentClass) { 4294 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) 4295 CurrentClass = Cat->getClassInterface(); 4296 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl)) 4297 CurrentClass = Impl->getClassInterface(); 4298 else if (ObjCCategoryImplDecl *CatImpl 4299 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) 4300 CurrentClass = CatImpl->getClassInterface(); 4301 } 4302 4303 ResultTypeCompatibilityKind RTC 4304 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass); 4305 4306 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC); 4307 4308 bool ARCError = false; 4309 if (getLangOpts().ObjCAutoRefCount) 4310 ARCError = CheckARCMethodDecl(ObjCMethod); 4311 4312 // Infer the related result type when possible. 4313 if (!ARCError && RTC == Sema::RTC_Compatible && 4314 !ObjCMethod->hasRelatedResultType() && 4315 LangOpts.ObjCInferRelatedResultType) { 4316 bool InferRelatedResultType = false; 4317 switch (ObjCMethod->getMethodFamily()) { 4318 case OMF_None: 4319 case OMF_copy: 4320 case OMF_dealloc: 4321 case OMF_finalize: 4322 case OMF_mutableCopy: 4323 case OMF_release: 4324 case OMF_retainCount: 4325 case OMF_initialize: 4326 case OMF_performSelector: 4327 break; 4328 4329 case OMF_alloc: 4330 case OMF_new: 4331 InferRelatedResultType = ObjCMethod->isClassMethod(); 4332 break; 4333 4334 case OMF_init: 4335 case OMF_autorelease: 4336 case OMF_retain: 4337 case OMF_self: 4338 InferRelatedResultType = ObjCMethod->isInstanceMethod(); 4339 break; 4340 } 4341 4342 if (InferRelatedResultType && 4343 !ObjCMethod->getReturnType()->isObjCIndependentClassType()) 4344 ObjCMethod->SetRelatedResultType(); 4345 } 4346 4347 ActOnDocumentableDecl(ObjCMethod); 4348 4349 return ObjCMethod; 4350 } 4351 4352 bool Sema::CheckObjCDeclScope(Decl *D) { 4353 // Following is also an error. But it is caused by a missing @end 4354 // and diagnostic is issued elsewhere. 4355 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) 4356 return false; 4357 4358 // If we switched context to translation unit while we are still lexically in 4359 // an objc container, it means the parser missed emitting an error. 4360 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext())) 4361 return false; 4362 4363 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope); 4364 D->setInvalidDecl(); 4365 4366 return true; 4367 } 4368 4369 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the 4370 /// instance variables of ClassName into Decls. 4371 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 4372 IdentifierInfo *ClassName, 4373 SmallVectorImpl<Decl*> &Decls) { 4374 // Check that ClassName is a valid class 4375 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart); 4376 if (!Class) { 4377 Diag(DeclStart, diag::err_undef_interface) << ClassName; 4378 return; 4379 } 4380 if (LangOpts.ObjCRuntime.isNonFragile()) { 4381 Diag(DeclStart, diag::err_atdef_nonfragile_interface); 4382 return; 4383 } 4384 4385 // Collect the instance variables 4386 SmallVector<const ObjCIvarDecl*, 32> Ivars; 4387 Context.DeepCollectObjCIvars(Class, true, Ivars); 4388 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 4389 for (unsigned i = 0; i < Ivars.size(); i++) { 4390 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]); 4391 RecordDecl *Record = dyn_cast<RecordDecl>(TagD); 4392 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, 4393 /*FIXME: StartL=*/ID->getLocation(), 4394 ID->getLocation(), 4395 ID->getIdentifier(), ID->getType(), 4396 ID->getBitWidth()); 4397 Decls.push_back(FD); 4398 } 4399 4400 // Introduce all of these fields into the appropriate scope. 4401 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin(); 4402 D != Decls.end(); ++D) { 4403 FieldDecl *FD = cast<FieldDecl>(*D); 4404 if (getLangOpts().CPlusPlus) 4405 PushOnScopeChains(cast<FieldDecl>(FD), S); 4406 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD)) 4407 Record->addDecl(FD); 4408 } 4409 } 4410 4411 /// \brief Build a type-check a new Objective-C exception variable declaration. 4412 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, 4413 SourceLocation StartLoc, 4414 SourceLocation IdLoc, 4415 IdentifierInfo *Id, 4416 bool Invalid) { 4417 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 4418 // duration shall not be qualified by an address-space qualifier." 4419 // Since all parameters have automatic store duration, they can not have 4420 // an address space. 4421 if (T.getAddressSpace() != 0) { 4422 Diag(IdLoc, diag::err_arg_with_address_space); 4423 Invalid = true; 4424 } 4425 4426 // An @catch parameter must be an unqualified object pointer type; 4427 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"? 4428 if (Invalid) { 4429 // Don't do any further checking. 4430 } else if (T->isDependentType()) { 4431 // Okay: we don't know what this type will instantiate to. 4432 } else if (!T->isObjCObjectPointerType()) { 4433 Invalid = true; 4434 Diag(IdLoc ,diag::err_catch_param_not_objc_type); 4435 } else if (T->isObjCQualifiedIdType()) { 4436 Invalid = true; 4437 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm); 4438 } 4439 4440 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id, 4441 T, TInfo, SC_None); 4442 New->setExceptionVariable(true); 4443 4444 // In ARC, infer 'retaining' for variables of retainable type. 4445 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New)) 4446 Invalid = true; 4447 4448 if (Invalid) 4449 New->setInvalidDecl(); 4450 return New; 4451 } 4452 4453 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { 4454 const DeclSpec &DS = D.getDeclSpec(); 4455 4456 // We allow the "register" storage class on exception variables because 4457 // GCC did, but we drop it completely. Any other storage class is an error. 4458 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 4459 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm) 4460 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc())); 4461 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4462 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm) 4463 << DeclSpec::getSpecifierName(SCS); 4464 } 4465 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 4466 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 4467 diag::err_invalid_thread) 4468 << DeclSpec::getSpecifierName(TSCS); 4469 D.getMutableDeclSpec().ClearStorageClassSpecs(); 4470 4471 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4472 4473 // Check that there are no default arguments inside the type of this 4474 // exception object (C++ only). 4475 if (getLangOpts().CPlusPlus) 4476 CheckExtraCXXDefaultArguments(D); 4477 4478 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4479 QualType ExceptionType = TInfo->getType(); 4480 4481 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType, 4482 D.getSourceRange().getBegin(), 4483 D.getIdentifierLoc(), 4484 D.getIdentifier(), 4485 D.isInvalidType()); 4486 4487 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 4488 if (D.getCXXScopeSpec().isSet()) { 4489 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm) 4490 << D.getCXXScopeSpec().getRange(); 4491 New->setInvalidDecl(); 4492 } 4493 4494 // Add the parameter declaration into this scope. 4495 S->AddDecl(New); 4496 if (D.getIdentifier()) 4497 IdResolver.AddDecl(New); 4498 4499 ProcessDeclAttributes(S, New, D); 4500 4501 if (New->hasAttr<BlocksAttr>()) 4502 Diag(New->getLocation(), diag::err_block_on_nonlocal); 4503 return New; 4504 } 4505 4506 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 4507 /// initialization. 4508 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 4509 SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 4510 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; 4511 Iv= Iv->getNextIvar()) { 4512 QualType QT = Context.getBaseElementType(Iv->getType()); 4513 if (QT->isRecordType()) 4514 Ivars.push_back(Iv); 4515 } 4516 } 4517 4518 void Sema::DiagnoseUseOfUnimplementedSelectors() { 4519 // Load referenced selectors from the external source. 4520 if (ExternalSource) { 4521 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels; 4522 ExternalSource->ReadReferencedSelectors(Sels); 4523 for (unsigned I = 0, N = Sels.size(); I != N; ++I) 4524 ReferencedSelectors[Sels[I].first] = Sels[I].second; 4525 } 4526 4527 // Warning will be issued only when selector table is 4528 // generated (which means there is at lease one implementation 4529 // in the TU). This is to match gcc's behavior. 4530 if (ReferencedSelectors.empty() || 4531 !Context.AnyObjCImplementation()) 4532 return; 4533 for (auto &SelectorAndLocation : ReferencedSelectors) { 4534 Selector Sel = SelectorAndLocation.first; 4535 SourceLocation Loc = SelectorAndLocation.second; 4536 if (!LookupImplementedMethodInGlobalPool(Sel)) 4537 Diag(Loc, diag::warn_unimplemented_selector) << Sel; 4538 } 4539 } 4540 4541 ObjCIvarDecl * 4542 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 4543 const ObjCPropertyDecl *&PDecl) const { 4544 if (Method->isClassMethod()) 4545 return nullptr; 4546 const ObjCInterfaceDecl *IDecl = Method->getClassInterface(); 4547 if (!IDecl) 4548 return nullptr; 4549 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true, 4550 /*shallowCategoryLookup=*/false, 4551 /*followSuper=*/false); 4552 if (!Method || !Method->isPropertyAccessor()) 4553 return nullptr; 4554 if ((PDecl = Method->findPropertyDecl())) 4555 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) { 4556 // property backing ivar must belong to property's class 4557 // or be a private ivar in class's implementation. 4558 // FIXME. fix the const-ness issue. 4559 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable( 4560 IV->getIdentifier()); 4561 return IV; 4562 } 4563 return nullptr; 4564 } 4565 4566 namespace { 4567 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property 4568 /// accessor references the backing ivar. 4569 class UnusedBackingIvarChecker : 4570 public DataRecursiveASTVisitor<UnusedBackingIvarChecker> { 4571 public: 4572 Sema &S; 4573 const ObjCMethodDecl *Method; 4574 const ObjCIvarDecl *IvarD; 4575 bool AccessedIvar; 4576 bool InvokedSelfMethod; 4577 4578 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method, 4579 const ObjCIvarDecl *IvarD) 4580 : S(S), Method(Method), IvarD(IvarD), 4581 AccessedIvar(false), InvokedSelfMethod(false) { 4582 assert(IvarD); 4583 } 4584 4585 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 4586 if (E->getDecl() == IvarD) { 4587 AccessedIvar = true; 4588 return false; 4589 } 4590 return true; 4591 } 4592 4593 bool VisitObjCMessageExpr(ObjCMessageExpr *E) { 4594 if (E->getReceiverKind() == ObjCMessageExpr::Instance && 4595 S.isSelfExpr(E->getInstanceReceiver(), Method)) { 4596 InvokedSelfMethod = true; 4597 } 4598 return true; 4599 } 4600 }; 4601 } // end anonymous namespace 4602 4603 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S, 4604 const ObjCImplementationDecl *ImplD) { 4605 if (S->hasUnrecoverableErrorOccurred()) 4606 return; 4607 4608 for (const auto *CurMethod : ImplD->instance_methods()) { 4609 unsigned DIAG = diag::warn_unused_property_backing_ivar; 4610 SourceLocation Loc = CurMethod->getLocation(); 4611 if (Diags.isIgnored(DIAG, Loc)) 4612 continue; 4613 4614 const ObjCPropertyDecl *PDecl; 4615 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl); 4616 if (!IV) 4617 continue; 4618 4619 UnusedBackingIvarChecker Checker(*this, CurMethod, IV); 4620 Checker.TraverseStmt(CurMethod->getBody()); 4621 if (Checker.AccessedIvar) 4622 continue; 4623 4624 // Do not issue this warning if backing ivar is used somewhere and accessor 4625 // implementation makes a self call. This is to prevent false positive in 4626 // cases where the ivar is accessed by another method that the accessor 4627 // delegates to. 4628 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) { 4629 Diag(Loc, DIAG) << IV; 4630 Diag(PDecl->getLocation(), diag::note_property_declare); 4631 } 4632 } 4633 } 4634