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 // Check and see if properties declared in the interface have either 1) 2848 // an implementation or 2) there is a @synthesize/@dynamic implementation 2849 // of the property in the @implementation. 2850 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 2851 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties && 2852 LangOpts.ObjCRuntime.isNonFragile() && 2853 !IDecl->isObjCRequiresPropertyDefs(); 2854 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties); 2855 } 2856 2857 // Diagnose null-resettable synthesized setters. 2858 diagnoseNullResettableSynthesizedSetters(IMPDecl); 2859 2860 SelectorSet ClsMap; 2861 for (const auto *I : IMPDecl->class_methods()) 2862 ClsMap.insert(I->getSelector()); 2863 2864 // Check for type conflict of methods declared in a class/protocol and 2865 // its implementation; if any. 2866 SelectorSet InsMapSeen, ClsMapSeen; 2867 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen, 2868 IMPDecl, CDecl, 2869 IncompleteImpl, true); 2870 2871 // check all methods implemented in category against those declared 2872 // in its primary class. 2873 if (ObjCCategoryImplDecl *CatDecl = 2874 dyn_cast<ObjCCategoryImplDecl>(IMPDecl)) 2875 CheckCategoryVsClassMethodMatches(CatDecl); 2876 2877 // Check the protocol list for unimplemented methods in the @implementation 2878 // class. 2879 // Check and see if class methods in class interface have been 2880 // implemented in the implementation class. 2881 2882 LazyProtocolNameSet ExplicitImplProtocols; 2883 2884 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) { 2885 for (auto *PI : I->all_referenced_protocols()) 2886 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl, 2887 InsMap, ClsMap, I, ExplicitImplProtocols); 2888 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) { 2889 // For extended class, unimplemented methods in its protocols will 2890 // be reported in the primary class. 2891 if (!C->IsClassExtension()) { 2892 for (auto *P : C->protocols()) 2893 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P, 2894 IncompleteImpl, InsMap, ClsMap, CDecl, 2895 ExplicitImplProtocols); 2896 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, 2897 /*SynthesizeProperties=*/false); 2898 } 2899 } else 2900 llvm_unreachable("invalid ObjCContainerDecl type."); 2901 } 2902 2903 Sema::DeclGroupPtrTy 2904 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc, 2905 IdentifierInfo **IdentList, 2906 SourceLocation *IdentLocs, 2907 ArrayRef<ObjCTypeParamList *> TypeParamLists, 2908 unsigned NumElts) { 2909 SmallVector<Decl *, 8> DeclsInGroup; 2910 for (unsigned i = 0; i != NumElts; ++i) { 2911 // Check for another declaration kind with the same name. 2912 NamedDecl *PrevDecl 2913 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], 2914 LookupOrdinaryName, ForRedeclaration); 2915 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) { 2916 // GCC apparently allows the following idiom: 2917 // 2918 // typedef NSObject < XCElementTogglerP > XCElementToggler; 2919 // @class XCElementToggler; 2920 // 2921 // Here we have chosen to ignore the forward class declaration 2922 // with a warning. Since this is the implied behavior. 2923 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl); 2924 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) { 2925 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i]; 2926 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2927 } else { 2928 // a forward class declaration matching a typedef name of a class refers 2929 // to the underlying class. Just ignore the forward class with a warning 2930 // as this will force the intended behavior which is to lookup the 2931 // typedef name. 2932 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) { 2933 Diag(AtClassLoc, diag::warn_forward_class_redefinition) 2934 << IdentList[i]; 2935 Diag(PrevDecl->getLocation(), diag::note_previous_definition); 2936 continue; 2937 } 2938 } 2939 } 2940 2941 // Create a declaration to describe this forward declaration. 2942 ObjCInterfaceDecl *PrevIDecl 2943 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl); 2944 2945 IdentifierInfo *ClassName = IdentList[i]; 2946 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) { 2947 // A previous decl with a different name is because of 2948 // @compatibility_alias, for example: 2949 // \code 2950 // @class NewImage; 2951 // @compatibility_alias OldImage NewImage; 2952 // \endcode 2953 // A lookup for 'OldImage' will return the 'NewImage' decl. 2954 // 2955 // In such a case use the real declaration name, instead of the alias one, 2956 // otherwise we will break IdentifierResolver and redecls-chain invariants. 2957 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl 2958 // has been aliased. 2959 ClassName = PrevIDecl->getIdentifier(); 2960 } 2961 2962 // If this forward declaration has type parameters, compare them with the 2963 // type parameters of the previous declaration. 2964 ObjCTypeParamList *TypeParams = TypeParamLists[i]; 2965 if (PrevIDecl && TypeParams) { 2966 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) { 2967 // Check for consistency with the previous declaration. 2968 if (checkTypeParamListConsistency( 2969 *this, PrevTypeParams, TypeParams, 2970 TypeParamListContext::ForwardDeclaration)) { 2971 TypeParams = nullptr; 2972 } 2973 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) { 2974 // The @interface does not have type parameters. Complain. 2975 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class) 2976 << ClassName 2977 << TypeParams->getSourceRange(); 2978 Diag(Def->getLocation(), diag::note_defined_here) 2979 << ClassName; 2980 2981 TypeParams = nullptr; 2982 } 2983 } 2984 2985 ObjCInterfaceDecl *IDecl 2986 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc, 2987 ClassName, TypeParams, PrevIDecl, 2988 IdentLocs[i]); 2989 IDecl->setAtEndRange(IdentLocs[i]); 2990 2991 PushOnScopeChains(IDecl, TUScope); 2992 CheckObjCDeclScope(IDecl); 2993 DeclsInGroup.push_back(IDecl); 2994 } 2995 2996 return BuildDeclaratorGroup(DeclsInGroup, false); 2997 } 2998 2999 static bool tryMatchRecordTypes(ASTContext &Context, 3000 Sema::MethodMatchStrategy strategy, 3001 const Type *left, const Type *right); 3002 3003 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy, 3004 QualType leftQT, QualType rightQT) { 3005 const Type *left = 3006 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr(); 3007 const Type *right = 3008 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr(); 3009 3010 if (left == right) return true; 3011 3012 // If we're doing a strict match, the types have to match exactly. 3013 if (strategy == Sema::MMS_strict) return false; 3014 3015 if (left->isIncompleteType() || right->isIncompleteType()) return false; 3016 3017 // Otherwise, use this absurdly complicated algorithm to try to 3018 // validate the basic, low-level compatibility of the two types. 3019 3020 // As a minimum, require the sizes and alignments to match. 3021 TypeInfo LeftTI = Context.getTypeInfo(left); 3022 TypeInfo RightTI = Context.getTypeInfo(right); 3023 if (LeftTI.Width != RightTI.Width) 3024 return false; 3025 3026 if (LeftTI.Align != RightTI.Align) 3027 return false; 3028 3029 // Consider all the kinds of non-dependent canonical types: 3030 // - functions and arrays aren't possible as return and parameter types 3031 3032 // - vector types of equal size can be arbitrarily mixed 3033 if (isa<VectorType>(left)) return isa<VectorType>(right); 3034 if (isa<VectorType>(right)) return false; 3035 3036 // - references should only match references of identical type 3037 // - structs, unions, and Objective-C objects must match more-or-less 3038 // exactly 3039 // - everything else should be a scalar 3040 if (!left->isScalarType() || !right->isScalarType()) 3041 return tryMatchRecordTypes(Context, strategy, left, right); 3042 3043 // Make scalars agree in kind, except count bools as chars, and group 3044 // all non-member pointers together. 3045 Type::ScalarTypeKind leftSK = left->getScalarTypeKind(); 3046 Type::ScalarTypeKind rightSK = right->getScalarTypeKind(); 3047 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral; 3048 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral; 3049 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer) 3050 leftSK = Type::STK_ObjCObjectPointer; 3051 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer) 3052 rightSK = Type::STK_ObjCObjectPointer; 3053 3054 // Note that data member pointers and function member pointers don't 3055 // intermix because of the size differences. 3056 3057 return (leftSK == rightSK); 3058 } 3059 3060 static bool tryMatchRecordTypes(ASTContext &Context, 3061 Sema::MethodMatchStrategy strategy, 3062 const Type *lt, const Type *rt) { 3063 assert(lt && rt && lt != rt); 3064 3065 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false; 3066 RecordDecl *left = cast<RecordType>(lt)->getDecl(); 3067 RecordDecl *right = cast<RecordType>(rt)->getDecl(); 3068 3069 // Require union-hood to match. 3070 if (left->isUnion() != right->isUnion()) return false; 3071 3072 // Require an exact match if either is non-POD. 3073 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) || 3074 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD())) 3075 return false; 3076 3077 // Require size and alignment to match. 3078 TypeInfo LeftTI = Context.getTypeInfo(lt); 3079 TypeInfo RightTI = Context.getTypeInfo(rt); 3080 if (LeftTI.Width != RightTI.Width) 3081 return false; 3082 3083 if (LeftTI.Align != RightTI.Align) 3084 return false; 3085 3086 // Require fields to match. 3087 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end(); 3088 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end(); 3089 for (; li != le && ri != re; ++li, ++ri) { 3090 if (!matchTypes(Context, strategy, li->getType(), ri->getType())) 3091 return false; 3092 } 3093 return (li == le && ri == re); 3094 } 3095 3096 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and 3097 /// returns true, or false, accordingly. 3098 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons 3099 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left, 3100 const ObjCMethodDecl *right, 3101 MethodMatchStrategy strategy) { 3102 if (!matchTypes(Context, strategy, left->getReturnType(), 3103 right->getReturnType())) 3104 return false; 3105 3106 // If either is hidden, it is not considered to match. 3107 if (left->isHidden() || right->isHidden()) 3108 return false; 3109 3110 if (getLangOpts().ObjCAutoRefCount && 3111 (left->hasAttr<NSReturnsRetainedAttr>() 3112 != right->hasAttr<NSReturnsRetainedAttr>() || 3113 left->hasAttr<NSConsumesSelfAttr>() 3114 != right->hasAttr<NSConsumesSelfAttr>())) 3115 return false; 3116 3117 ObjCMethodDecl::param_const_iterator 3118 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(), 3119 re = right->param_end(); 3120 3121 for (; li != le && ri != re; ++li, ++ri) { 3122 assert(ri != right->param_end() && "Param mismatch"); 3123 const ParmVarDecl *lparm = *li, *rparm = *ri; 3124 3125 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType())) 3126 return false; 3127 3128 if (getLangOpts().ObjCAutoRefCount && 3129 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>()) 3130 return false; 3131 } 3132 return true; 3133 } 3134 3135 void Sema::addMethodToGlobalList(ObjCMethodList *List, 3136 ObjCMethodDecl *Method) { 3137 // Record at the head of the list whether there were 0, 1, or >= 2 methods 3138 // inside categories. 3139 if (ObjCCategoryDecl *CD = 3140 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext())) 3141 if (!CD->IsClassExtension() && List->getBits() < 2) 3142 List->setBits(List->getBits() + 1); 3143 3144 // If the list is empty, make it a singleton list. 3145 if (List->getMethod() == nullptr) { 3146 List->setMethod(Method); 3147 List->setNext(nullptr); 3148 return; 3149 } 3150 3151 // We've seen a method with this name, see if we have already seen this type 3152 // signature. 3153 ObjCMethodList *Previous = List; 3154 for (; List; Previous = List, List = List->getNext()) { 3155 // If we are building a module, keep all of the methods. 3156 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty()) 3157 continue; 3158 3159 if (!MatchTwoMethodDeclarations(Method, List->getMethod())) { 3160 // Even if two method types do not match, we would like to say 3161 // there is more than one declaration so unavailability/deprecated 3162 // warning is not too noisy. 3163 if (!Method->isDefined()) 3164 List->setHasMoreThanOneDecl(true); 3165 continue; 3166 } 3167 3168 ObjCMethodDecl *PrevObjCMethod = List->getMethod(); 3169 3170 // Propagate the 'defined' bit. 3171 if (Method->isDefined()) 3172 PrevObjCMethod->setDefined(true); 3173 else { 3174 // Objective-C doesn't allow an @interface for a class after its 3175 // @implementation. So if Method is not defined and there already is 3176 // an entry for this type signature, Method has to be for a different 3177 // class than PrevObjCMethod. 3178 List->setHasMoreThanOneDecl(true); 3179 } 3180 3181 // If a method is deprecated, push it in the global pool. 3182 // This is used for better diagnostics. 3183 if (Method->isDeprecated()) { 3184 if (!PrevObjCMethod->isDeprecated()) 3185 List->setMethod(Method); 3186 } 3187 // If the new method is unavailable, push it into global pool 3188 // unless previous one is deprecated. 3189 if (Method->isUnavailable()) { 3190 if (PrevObjCMethod->getAvailability() < AR_Deprecated) 3191 List->setMethod(Method); 3192 } 3193 3194 return; 3195 } 3196 3197 // We have a new signature for an existing method - add it. 3198 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded". 3199 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>(); 3200 Previous->setNext(new (Mem) ObjCMethodList(Method)); 3201 } 3202 3203 /// \brief Read the contents of the method pool for a given selector from 3204 /// external storage. 3205 void Sema::ReadMethodPool(Selector Sel) { 3206 assert(ExternalSource && "We need an external AST source"); 3207 ExternalSource->ReadMethodPool(Sel); 3208 } 3209 3210 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, 3211 bool instance) { 3212 // Ignore methods of invalid containers. 3213 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl()) 3214 return; 3215 3216 if (ExternalSource) 3217 ReadMethodPool(Method->getSelector()); 3218 3219 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector()); 3220 if (Pos == MethodPool.end()) 3221 Pos = MethodPool.insert(std::make_pair(Method->getSelector(), 3222 GlobalMethods())).first; 3223 3224 Method->setDefined(impl); 3225 3226 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second; 3227 addMethodToGlobalList(&Entry, Method); 3228 } 3229 3230 /// Determines if this is an "acceptable" loose mismatch in the global 3231 /// method pool. This exists mostly as a hack to get around certain 3232 /// global mismatches which we can't afford to make warnings / errors. 3233 /// Really, what we want is a way to take a method out of the global 3234 /// method pool. 3235 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen, 3236 ObjCMethodDecl *other) { 3237 if (!chosen->isInstanceMethod()) 3238 return false; 3239 3240 Selector sel = chosen->getSelector(); 3241 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length") 3242 return false; 3243 3244 // Don't complain about mismatches for -length if the method we 3245 // chose has an integral result type. 3246 return (chosen->getReturnType()->isIntegerType()); 3247 } 3248 3249 bool Sema::CollectMultipleMethodsInGlobalPool( 3250 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, bool instance) { 3251 if (ExternalSource) 3252 ReadMethodPool(Sel); 3253 3254 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3255 if (Pos == MethodPool.end()) 3256 return false; 3257 // Gather the non-hidden methods. 3258 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 3259 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) 3260 if (M->getMethod() && !M->getMethod()->isHidden()) 3261 Methods.push_back(M->getMethod()); 3262 return Methods.size() > 1; 3263 } 3264 3265 bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, 3266 SourceRange R, 3267 bool receiverIdOrClass) { 3268 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3269 // Test for no method in the pool which should not trigger any warning by 3270 // caller. 3271 if (Pos == MethodPool.end()) 3272 return true; 3273 ObjCMethodList &MethList = 3274 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second; 3275 3276 // Diagnose finding more than one method in global pool 3277 SmallVector<ObjCMethodDecl *, 4> Methods; 3278 Methods.push_back(BestMethod); 3279 for (ObjCMethodList *ML = &MethList; ML; ML = ML->getNext()) 3280 if (ObjCMethodDecl *M = ML->getMethod()) 3281 if (!M->isHidden() && M != BestMethod && !M->hasAttr<UnavailableAttr>()) 3282 Methods.push_back(M); 3283 if (Methods.size() > 1) 3284 DiagnoseMultipleMethodInGlobalPool(Methods, Sel, R, receiverIdOrClass); 3285 3286 return MethList.hasMoreThanOneDecl(); 3287 } 3288 3289 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R, 3290 bool receiverIdOrClass, 3291 bool instance) { 3292 if (ExternalSource) 3293 ReadMethodPool(Sel); 3294 3295 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3296 if (Pos == MethodPool.end()) 3297 return nullptr; 3298 3299 // Gather the non-hidden methods. 3300 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second; 3301 SmallVector<ObjCMethodDecl *, 4> Methods; 3302 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) { 3303 if (M->getMethod() && !M->getMethod()->isHidden()) 3304 return M->getMethod(); 3305 } 3306 return nullptr; 3307 } 3308 3309 void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, 3310 Selector Sel, SourceRange R, 3311 bool receiverIdOrClass) { 3312 // We found multiple methods, so we may have to complain. 3313 bool issueDiagnostic = false, issueError = false; 3314 3315 // We support a warning which complains about *any* difference in 3316 // method signature. 3317 bool strictSelectorMatch = 3318 receiverIdOrClass && 3319 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin()); 3320 if (strictSelectorMatch) { 3321 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3322 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) { 3323 issueDiagnostic = true; 3324 break; 3325 } 3326 } 3327 } 3328 3329 // If we didn't see any strict differences, we won't see any loose 3330 // differences. In ARC, however, we also need to check for loose 3331 // mismatches, because most of them are errors. 3332 if (!strictSelectorMatch || 3333 (issueDiagnostic && getLangOpts().ObjCAutoRefCount)) 3334 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3335 // This checks if the methods differ in type mismatch. 3336 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) && 3337 !isAcceptableMethodMismatch(Methods[0], Methods[I])) { 3338 issueDiagnostic = true; 3339 if (getLangOpts().ObjCAutoRefCount) 3340 issueError = true; 3341 break; 3342 } 3343 } 3344 3345 if (issueDiagnostic) { 3346 if (issueError) 3347 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R; 3348 else if (strictSelectorMatch) 3349 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R; 3350 else 3351 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R; 3352 3353 Diag(Methods[0]->getLocStart(), 3354 issueError ? diag::note_possibility : diag::note_using) 3355 << Methods[0]->getSourceRange(); 3356 for (unsigned I = 1, N = Methods.size(); I != N; ++I) { 3357 Diag(Methods[I]->getLocStart(), diag::note_also_found) 3358 << Methods[I]->getSourceRange(); 3359 } 3360 } 3361 } 3362 3363 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) { 3364 GlobalMethodPool::iterator Pos = MethodPool.find(Sel); 3365 if (Pos == MethodPool.end()) 3366 return nullptr; 3367 3368 GlobalMethods &Methods = Pos->second; 3369 for (const ObjCMethodList *Method = &Methods.first; Method; 3370 Method = Method->getNext()) 3371 if (Method->getMethod() && 3372 (Method->getMethod()->isDefined() || 3373 Method->getMethod()->isPropertyAccessor())) 3374 return Method->getMethod(); 3375 3376 for (const ObjCMethodList *Method = &Methods.second; Method; 3377 Method = Method->getNext()) 3378 if (Method->getMethod() && 3379 (Method->getMethod()->isDefined() || 3380 Method->getMethod()->isPropertyAccessor())) 3381 return Method->getMethod(); 3382 return nullptr; 3383 } 3384 3385 static void 3386 HelperSelectorsForTypoCorrection( 3387 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod, 3388 StringRef Typo, const ObjCMethodDecl * Method) { 3389 const unsigned MaxEditDistance = 1; 3390 unsigned BestEditDistance = MaxEditDistance + 1; 3391 std::string MethodName = Method->getSelector().getAsString(); 3392 3393 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size()); 3394 if (MinPossibleEditDistance > 0 && 3395 Typo.size() / MinPossibleEditDistance < 1) 3396 return; 3397 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance); 3398 if (EditDistance > MaxEditDistance) 3399 return; 3400 if (EditDistance == BestEditDistance) 3401 BestMethod.push_back(Method); 3402 else if (EditDistance < BestEditDistance) { 3403 BestMethod.clear(); 3404 BestMethod.push_back(Method); 3405 } 3406 } 3407 3408 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel, 3409 QualType ObjectType) { 3410 if (ObjectType.isNull()) 3411 return true; 3412 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/)) 3413 return true; 3414 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) != 3415 nullptr; 3416 } 3417 3418 const ObjCMethodDecl * 3419 Sema::SelectorsForTypoCorrection(Selector Sel, 3420 QualType ObjectType) { 3421 unsigned NumArgs = Sel.getNumArgs(); 3422 SmallVector<const ObjCMethodDecl *, 8> Methods; 3423 bool ObjectIsId = true, ObjectIsClass = true; 3424 if (ObjectType.isNull()) 3425 ObjectIsId = ObjectIsClass = false; 3426 else if (!ObjectType->isObjCObjectPointerType()) 3427 return nullptr; 3428 else if (const ObjCObjectPointerType *ObjCPtr = 3429 ObjectType->getAsObjCInterfacePointerType()) { 3430 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0); 3431 ObjectIsId = ObjectIsClass = false; 3432 } 3433 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType()) 3434 ObjectIsClass = false; 3435 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType()) 3436 ObjectIsId = false; 3437 else 3438 return nullptr; 3439 3440 for (GlobalMethodPool::iterator b = MethodPool.begin(), 3441 e = MethodPool.end(); b != e; b++) { 3442 // instance methods 3443 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext()) 3444 if (M->getMethod() && 3445 (M->getMethod()->getSelector().getNumArgs() == NumArgs) && 3446 (M->getMethod()->getSelector() != Sel)) { 3447 if (ObjectIsId) 3448 Methods.push_back(M->getMethod()); 3449 else if (!ObjectIsClass && 3450 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(), 3451 ObjectType)) 3452 Methods.push_back(M->getMethod()); 3453 } 3454 // class methods 3455 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext()) 3456 if (M->getMethod() && 3457 (M->getMethod()->getSelector().getNumArgs() == NumArgs) && 3458 (M->getMethod()->getSelector() != Sel)) { 3459 if (ObjectIsClass) 3460 Methods.push_back(M->getMethod()); 3461 else if (!ObjectIsId && 3462 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(), 3463 ObjectType)) 3464 Methods.push_back(M->getMethod()); 3465 } 3466 } 3467 3468 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods; 3469 for (unsigned i = 0, e = Methods.size(); i < e; i++) { 3470 HelperSelectorsForTypoCorrection(SelectedMethods, 3471 Sel.getAsString(), Methods[i]); 3472 } 3473 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr; 3474 } 3475 3476 /// DiagnoseDuplicateIvars - 3477 /// Check for duplicate ivars in the entire class at the start of 3478 /// \@implementation. This becomes necesssary because class extension can 3479 /// add ivars to a class in random order which will not be known until 3480 /// class's \@implementation is seen. 3481 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, 3482 ObjCInterfaceDecl *SID) { 3483 for (auto *Ivar : ID->ivars()) { 3484 if (Ivar->isInvalidDecl()) 3485 continue; 3486 if (IdentifierInfo *II = Ivar->getIdentifier()) { 3487 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II); 3488 if (prevIvar) { 3489 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II; 3490 Diag(prevIvar->getLocation(), diag::note_previous_declaration); 3491 Ivar->setInvalidDecl(); 3492 } 3493 } 3494 } 3495 } 3496 3497 /// Diagnose attempts to define ARC-__weak ivars when __weak is disabled. 3498 static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) { 3499 if (S.getLangOpts().ObjCWeak) return; 3500 3501 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin(); 3502 ivar; ivar = ivar->getNextIvar()) { 3503 if (ivar->isInvalidDecl()) continue; 3504 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 3505 if (S.getLangOpts().ObjCWeakRuntime) { 3506 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled); 3507 } else { 3508 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime); 3509 } 3510 } 3511 } 3512 } 3513 3514 Sema::ObjCContainerKind Sema::getObjCContainerKind() const { 3515 switch (CurContext->getDeclKind()) { 3516 case Decl::ObjCInterface: 3517 return Sema::OCK_Interface; 3518 case Decl::ObjCProtocol: 3519 return Sema::OCK_Protocol; 3520 case Decl::ObjCCategory: 3521 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension()) 3522 return Sema::OCK_ClassExtension; 3523 return Sema::OCK_Category; 3524 case Decl::ObjCImplementation: 3525 return Sema::OCK_Implementation; 3526 case Decl::ObjCCategoryImpl: 3527 return Sema::OCK_CategoryImplementation; 3528 3529 default: 3530 return Sema::OCK_None; 3531 } 3532 } 3533 3534 // Note: For class/category implementations, allMethods is always null. 3535 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods, 3536 ArrayRef<DeclGroupPtrTy> allTUVars) { 3537 if (getObjCContainerKind() == Sema::OCK_None) 3538 return nullptr; 3539 3540 assert(AtEnd.isValid() && "Invalid location for '@end'"); 3541 3542 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 3543 Decl *ClassDecl = cast<Decl>(OCD); 3544 3545 bool isInterfaceDeclKind = 3546 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl) 3547 || isa<ObjCProtocolDecl>(ClassDecl); 3548 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl); 3549 3550 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext. 3551 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap; 3552 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap; 3553 3554 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) { 3555 ObjCMethodDecl *Method = 3556 cast_or_null<ObjCMethodDecl>(allMethods[i]); 3557 3558 if (!Method) continue; // Already issued a diagnostic. 3559 if (Method->isInstanceMethod()) { 3560 /// Check for instance method of the same name with incompatible types 3561 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()]; 3562 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 3563 : false; 3564 if ((isInterfaceDeclKind && PrevMethod && !match) 3565 || (checkIdenticalMethods && match)) { 3566 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 3567 << Method->getDeclName(); 3568 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3569 Method->setInvalidDecl(); 3570 } else { 3571 if (PrevMethod) { 3572 Method->setAsRedeclaration(PrevMethod); 3573 if (!Context.getSourceManager().isInSystemHeader( 3574 Method->getLocation())) 3575 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 3576 << Method->getDeclName(); 3577 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3578 } 3579 InsMap[Method->getSelector()] = Method; 3580 /// The following allows us to typecheck messages to "id". 3581 AddInstanceMethodToGlobalPool(Method); 3582 } 3583 } else { 3584 /// Check for class method of the same name with incompatible types 3585 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()]; 3586 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod) 3587 : false; 3588 if ((isInterfaceDeclKind && PrevMethod && !match) 3589 || (checkIdenticalMethods && match)) { 3590 Diag(Method->getLocation(), diag::err_duplicate_method_decl) 3591 << Method->getDeclName(); 3592 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3593 Method->setInvalidDecl(); 3594 } else { 3595 if (PrevMethod) { 3596 Method->setAsRedeclaration(PrevMethod); 3597 if (!Context.getSourceManager().isInSystemHeader( 3598 Method->getLocation())) 3599 Diag(Method->getLocation(), diag::warn_duplicate_method_decl) 3600 << Method->getDeclName(); 3601 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 3602 } 3603 ClsMap[Method->getSelector()] = Method; 3604 AddFactoryMethodToGlobalPool(Method); 3605 } 3606 } 3607 } 3608 if (isa<ObjCInterfaceDecl>(ClassDecl)) { 3609 // Nothing to do here. 3610 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 3611 // Categories are used to extend the class by declaring new methods. 3612 // By the same token, they are also used to add new properties. No 3613 // need to compare the added property to those in the class. 3614 3615 if (C->IsClassExtension()) { 3616 ObjCInterfaceDecl *CCPrimary = C->getClassInterface(); 3617 DiagnoseClassExtensionDupMethods(C, CCPrimary); 3618 } 3619 } 3620 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) { 3621 if (CDecl->getIdentifier()) 3622 // ProcessPropertyDecl is responsible for diagnosing conflicts with any 3623 // user-defined setter/getter. It also synthesizes setter/getter methods 3624 // and adds them to the DeclContext and global method pools. 3625 for (auto *I : CDecl->properties()) 3626 ProcessPropertyDecl(I, CDecl); 3627 CDecl->setAtEndRange(AtEnd); 3628 } 3629 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) { 3630 IC->setAtEndRange(AtEnd); 3631 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) { 3632 // Any property declared in a class extension might have user 3633 // declared setter or getter in current class extension or one 3634 // of the other class extensions. Mark them as synthesized as 3635 // property will be synthesized when property with same name is 3636 // seen in the @implementation. 3637 for (const auto *Ext : IDecl->visible_extensions()) { 3638 for (const auto *Property : Ext->properties()) { 3639 // Skip over properties declared @dynamic 3640 if (const ObjCPropertyImplDecl *PIDecl 3641 = IC->FindPropertyImplDecl(Property->getIdentifier())) 3642 if (PIDecl->getPropertyImplementation() 3643 == ObjCPropertyImplDecl::Dynamic) 3644 continue; 3645 3646 for (const auto *Ext : IDecl->visible_extensions()) { 3647 if (ObjCMethodDecl *GetterMethod 3648 = Ext->getInstanceMethod(Property->getGetterName())) 3649 GetterMethod->setPropertyAccessor(true); 3650 if (!Property->isReadOnly()) 3651 if (ObjCMethodDecl *SetterMethod 3652 = Ext->getInstanceMethod(Property->getSetterName())) 3653 SetterMethod->setPropertyAccessor(true); 3654 } 3655 } 3656 } 3657 ImplMethodsVsClassMethods(S, IC, IDecl); 3658 AtomicPropertySetterGetterRules(IC, IDecl); 3659 DiagnoseOwningPropertyGetterSynthesis(IC); 3660 DiagnoseUnusedBackingIvarInAccessor(S, IC); 3661 if (IDecl->hasDesignatedInitializers()) 3662 DiagnoseMissingDesignatedInitOverrides(IC, IDecl); 3663 DiagnoseWeakIvars(*this, IC); 3664 3665 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>(); 3666 if (IDecl->getSuperClass() == nullptr) { 3667 // This class has no superclass, so check that it has been marked with 3668 // __attribute((objc_root_class)). 3669 if (!HasRootClassAttr) { 3670 SourceLocation DeclLoc(IDecl->getLocation()); 3671 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc)); 3672 Diag(DeclLoc, diag::warn_objc_root_class_missing) 3673 << IDecl->getIdentifier(); 3674 // See if NSObject is in the current scope, and if it is, suggest 3675 // adding " : NSObject " to the class declaration. 3676 NamedDecl *IF = LookupSingleName(TUScope, 3677 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject), 3678 DeclLoc, LookupOrdinaryName); 3679 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); 3680 if (NSObjectDecl && NSObjectDecl->getDefinition()) { 3681 Diag(SuperClassLoc, diag::note_objc_needs_superclass) 3682 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject "); 3683 } else { 3684 Diag(SuperClassLoc, diag::note_objc_needs_superclass); 3685 } 3686 } 3687 } else if (HasRootClassAttr) { 3688 // Complain that only root classes may have this attribute. 3689 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass); 3690 } 3691 3692 if (LangOpts.ObjCRuntime.isNonFragile()) { 3693 while (IDecl->getSuperClass()) { 3694 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass()); 3695 IDecl = IDecl->getSuperClass(); 3696 } 3697 } 3698 } 3699 SetIvarInitializers(IC); 3700 } else if (ObjCCategoryImplDecl* CatImplClass = 3701 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) { 3702 CatImplClass->setAtEndRange(AtEnd); 3703 3704 // Find category interface decl and then check that all methods declared 3705 // in this interface are implemented in the category @implementation. 3706 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) { 3707 if (ObjCCategoryDecl *Cat 3708 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) { 3709 ImplMethodsVsClassMethods(S, CatImplClass, Cat); 3710 } 3711 } 3712 } 3713 if (isInterfaceDeclKind) { 3714 // Reject invalid vardecls. 3715 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 3716 DeclGroupRef DG = allTUVars[i].get(); 3717 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 3718 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) { 3719 if (!VDecl->hasExternalStorage()) 3720 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass); 3721 } 3722 } 3723 } 3724 ActOnObjCContainerFinishDefinition(); 3725 3726 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) { 3727 DeclGroupRef DG = allTUVars[i].get(); 3728 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I) 3729 (*I)->setTopLevelDeclInObjCContainer(); 3730 Consumer.HandleTopLevelDeclInObjCContainer(DG); 3731 } 3732 3733 ActOnDocumentableDecl(ClassDecl); 3734 return ClassDecl; 3735 } 3736 3737 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for 3738 /// objective-c's type qualifier from the parser version of the same info. 3739 static Decl::ObjCDeclQualifier 3740 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) { 3741 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal; 3742 } 3743 3744 /// \brief Check whether the declared result type of the given Objective-C 3745 /// method declaration is compatible with the method's class. 3746 /// 3747 static Sema::ResultTypeCompatibilityKind 3748 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method, 3749 ObjCInterfaceDecl *CurrentClass) { 3750 QualType ResultType = Method->getReturnType(); 3751 3752 // If an Objective-C method inherits its related result type, then its 3753 // declared result type must be compatible with its own class type. The 3754 // declared result type is compatible if: 3755 if (const ObjCObjectPointerType *ResultObjectType 3756 = ResultType->getAs<ObjCObjectPointerType>()) { 3757 // - it is id or qualified id, or 3758 if (ResultObjectType->isObjCIdType() || 3759 ResultObjectType->isObjCQualifiedIdType()) 3760 return Sema::RTC_Compatible; 3761 3762 if (CurrentClass) { 3763 if (ObjCInterfaceDecl *ResultClass 3764 = ResultObjectType->getInterfaceDecl()) { 3765 // - it is the same as the method's class type, or 3766 if (declaresSameEntity(CurrentClass, ResultClass)) 3767 return Sema::RTC_Compatible; 3768 3769 // - it is a superclass of the method's class type 3770 if (ResultClass->isSuperClassOf(CurrentClass)) 3771 return Sema::RTC_Compatible; 3772 } 3773 } else { 3774 // Any Objective-C pointer type might be acceptable for a protocol 3775 // method; we just don't know. 3776 return Sema::RTC_Unknown; 3777 } 3778 } 3779 3780 return Sema::RTC_Incompatible; 3781 } 3782 3783 namespace { 3784 /// A helper class for searching for methods which a particular method 3785 /// overrides. 3786 class OverrideSearch { 3787 public: 3788 Sema &S; 3789 ObjCMethodDecl *Method; 3790 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden; 3791 bool Recursive; 3792 3793 public: 3794 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) { 3795 Selector selector = method->getSelector(); 3796 3797 // Bypass this search if we've never seen an instance/class method 3798 // with this selector before. 3799 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector); 3800 if (it == S.MethodPool.end()) { 3801 if (!S.getExternalSource()) return; 3802 S.ReadMethodPool(selector); 3803 3804 it = S.MethodPool.find(selector); 3805 if (it == S.MethodPool.end()) 3806 return; 3807 } 3808 ObjCMethodList &list = 3809 method->isInstanceMethod() ? it->second.first : it->second.second; 3810 if (!list.getMethod()) return; 3811 3812 ObjCContainerDecl *container 3813 = cast<ObjCContainerDecl>(method->getDeclContext()); 3814 3815 // Prevent the search from reaching this container again. This is 3816 // important with categories, which override methods from the 3817 // interface and each other. 3818 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) { 3819 searchFromContainer(container); 3820 if (ObjCInterfaceDecl *Interface = Category->getClassInterface()) 3821 searchFromContainer(Interface); 3822 } else { 3823 searchFromContainer(container); 3824 } 3825 } 3826 3827 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator; 3828 iterator begin() const { return Overridden.begin(); } 3829 iterator end() const { return Overridden.end(); } 3830 3831 private: 3832 void searchFromContainer(ObjCContainerDecl *container) { 3833 if (container->isInvalidDecl()) return; 3834 3835 switch (container->getDeclKind()) { 3836 #define OBJCCONTAINER(type, base) \ 3837 case Decl::type: \ 3838 searchFrom(cast<type##Decl>(container)); \ 3839 break; 3840 #define ABSTRACT_DECL(expansion) 3841 #define DECL(type, base) \ 3842 case Decl::type: 3843 #include "clang/AST/DeclNodes.inc" 3844 llvm_unreachable("not an ObjC container!"); 3845 } 3846 } 3847 3848 void searchFrom(ObjCProtocolDecl *protocol) { 3849 if (!protocol->hasDefinition()) 3850 return; 3851 3852 // A method in a protocol declaration overrides declarations from 3853 // referenced ("parent") protocols. 3854 search(protocol->getReferencedProtocols()); 3855 } 3856 3857 void searchFrom(ObjCCategoryDecl *category) { 3858 // A method in a category declaration overrides declarations from 3859 // the main class and from protocols the category references. 3860 // The main class is handled in the constructor. 3861 search(category->getReferencedProtocols()); 3862 } 3863 3864 void searchFrom(ObjCCategoryImplDecl *impl) { 3865 // A method in a category definition that has a category 3866 // declaration overrides declarations from the category 3867 // declaration. 3868 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) { 3869 search(category); 3870 if (ObjCInterfaceDecl *Interface = category->getClassInterface()) 3871 search(Interface); 3872 3873 // Otherwise it overrides declarations from the class. 3874 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) { 3875 search(Interface); 3876 } 3877 } 3878 3879 void searchFrom(ObjCInterfaceDecl *iface) { 3880 // A method in a class declaration overrides declarations from 3881 if (!iface->hasDefinition()) 3882 return; 3883 3884 // - categories, 3885 for (auto *Cat : iface->known_categories()) 3886 search(Cat); 3887 3888 // - the super class, and 3889 if (ObjCInterfaceDecl *super = iface->getSuperClass()) 3890 search(super); 3891 3892 // - any referenced protocols. 3893 search(iface->getReferencedProtocols()); 3894 } 3895 3896 void searchFrom(ObjCImplementationDecl *impl) { 3897 // A method in a class implementation overrides declarations from 3898 // the class interface. 3899 if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) 3900 search(Interface); 3901 } 3902 3903 void search(const ObjCProtocolList &protocols) { 3904 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end(); 3905 i != e; ++i) 3906 search(*i); 3907 } 3908 3909 void search(ObjCContainerDecl *container) { 3910 // Check for a method in this container which matches this selector. 3911 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(), 3912 Method->isInstanceMethod(), 3913 /*AllowHidden=*/true); 3914 3915 // If we find one, record it and bail out. 3916 if (meth) { 3917 Overridden.insert(meth); 3918 return; 3919 } 3920 3921 // Otherwise, search for methods that a hypothetical method here 3922 // would have overridden. 3923 3924 // Note that we're now in a recursive case. 3925 Recursive = true; 3926 3927 searchFromContainer(container); 3928 } 3929 }; 3930 } // end anonymous namespace 3931 3932 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, 3933 ObjCInterfaceDecl *CurrentClass, 3934 ResultTypeCompatibilityKind RTC) { 3935 // Search for overridden methods and merge information down from them. 3936 OverrideSearch overrides(*this, ObjCMethod); 3937 // Keep track if the method overrides any method in the class's base classes, 3938 // its protocols, or its categories' protocols; we will keep that info 3939 // in the ObjCMethodDecl. 3940 // For this info, a method in an implementation is not considered as 3941 // overriding the same method in the interface or its categories. 3942 bool hasOverriddenMethodsInBaseOrProtocol = false; 3943 for (OverrideSearch::iterator 3944 i = overrides.begin(), e = overrides.end(); i != e; ++i) { 3945 ObjCMethodDecl *overridden = *i; 3946 3947 if (!hasOverriddenMethodsInBaseOrProtocol) { 3948 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) || 3949 CurrentClass != overridden->getClassInterface() || 3950 overridden->isOverriding()) { 3951 hasOverriddenMethodsInBaseOrProtocol = true; 3952 3953 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) { 3954 // OverrideSearch will return as "overridden" the same method in the 3955 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to 3956 // check whether a category of a base class introduced a method with the 3957 // same selector, after the interface method declaration. 3958 // To avoid unnecessary lookups in the majority of cases, we use the 3959 // extra info bits in GlobalMethodPool to check whether there were any 3960 // category methods with this selector. 3961 GlobalMethodPool::iterator It = 3962 MethodPool.find(ObjCMethod->getSelector()); 3963 if (It != MethodPool.end()) { 3964 ObjCMethodList &List = 3965 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second; 3966 unsigned CategCount = List.getBits(); 3967 if (CategCount > 0) { 3968 // If the method is in a category we'll do lookup if there were at 3969 // least 2 category methods recorded, otherwise only one will do. 3970 if (CategCount > 1 || 3971 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) { 3972 OverrideSearch overrides(*this, overridden); 3973 for (OverrideSearch::iterator 3974 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) { 3975 ObjCMethodDecl *SuperOverridden = *OI; 3976 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) || 3977 CurrentClass != SuperOverridden->getClassInterface()) { 3978 hasOverriddenMethodsInBaseOrProtocol = true; 3979 overridden->setOverriding(true); 3980 break; 3981 } 3982 } 3983 } 3984 } 3985 } 3986 } 3987 } 3988 3989 // Propagate down the 'related result type' bit from overridden methods. 3990 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType()) 3991 ObjCMethod->SetRelatedResultType(); 3992 3993 // Then merge the declarations. 3994 mergeObjCMethodDecls(ObjCMethod, overridden); 3995 3996 if (ObjCMethod->isImplicit() && overridden->isImplicit()) 3997 continue; // Conflicting properties are detected elsewhere. 3998 3999 // Check for overriding methods 4000 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || 4001 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext())) 4002 CheckConflictingOverridingMethod(ObjCMethod, overridden, 4003 isa<ObjCProtocolDecl>(overridden->getDeclContext())); 4004 4005 if (CurrentClass && overridden->getDeclContext() != CurrentClass && 4006 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) && 4007 !overridden->isImplicit() /* not meant for properties */) { 4008 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(), 4009 E = ObjCMethod->param_end(); 4010 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(), 4011 PrevE = overridden->param_end(); 4012 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) { 4013 assert(PrevI != overridden->param_end() && "Param mismatch"); 4014 QualType T1 = Context.getCanonicalType((*ParamI)->getType()); 4015 QualType T2 = Context.getCanonicalType((*PrevI)->getType()); 4016 // If type of argument of method in this class does not match its 4017 // respective argument type in the super class method, issue warning; 4018 if (!Context.typesAreCompatible(T1, T2)) { 4019 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super) 4020 << T1 << T2; 4021 Diag(overridden->getLocation(), diag::note_previous_declaration); 4022 break; 4023 } 4024 } 4025 } 4026 } 4027 4028 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol); 4029 } 4030 4031 /// Merge type nullability from for a redeclaration of the same entity, 4032 /// producing the updated type of the redeclared entity. 4033 static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc, 4034 QualType type, 4035 bool usesCSKeyword, 4036 SourceLocation prevLoc, 4037 QualType prevType, 4038 bool prevUsesCSKeyword) { 4039 // Determine the nullability of both types. 4040 auto nullability = type->getNullability(S.Context); 4041 auto prevNullability = prevType->getNullability(S.Context); 4042 4043 // Easy case: both have nullability. 4044 if (nullability.hasValue() == prevNullability.hasValue()) { 4045 // Neither has nullability; continue. 4046 if (!nullability) 4047 return type; 4048 4049 // The nullabilities are equivalent; do nothing. 4050 if (*nullability == *prevNullability) 4051 return type; 4052 4053 // Complain about mismatched nullability. 4054 S.Diag(loc, diag::err_nullability_conflicting) 4055 << DiagNullabilityKind(*nullability, usesCSKeyword) 4056 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword); 4057 return type; 4058 } 4059 4060 // If it's the redeclaration that has nullability, don't change anything. 4061 if (nullability) 4062 return type; 4063 4064 // Otherwise, provide the result with the same nullability. 4065 return S.Context.getAttributedType( 4066 AttributedType::getNullabilityAttrKind(*prevNullability), 4067 type, type); 4068 } 4069 4070 /// Merge information from the declaration of a method in the \@interface 4071 /// (or a category/extension) into the corresponding method in the 4072 /// @implementation (for a class or category). 4073 static void mergeInterfaceMethodToImpl(Sema &S, 4074 ObjCMethodDecl *method, 4075 ObjCMethodDecl *prevMethod) { 4076 // Merge the objc_requires_super attribute. 4077 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() && 4078 !method->hasAttr<ObjCRequiresSuperAttr>()) { 4079 // merge the attribute into implementation. 4080 method->addAttr( 4081 ObjCRequiresSuperAttr::CreateImplicit(S.Context, 4082 method->getLocation())); 4083 } 4084 4085 // Merge nullability of the result type. 4086 QualType newReturnType 4087 = mergeTypeNullabilityForRedecl( 4088 S, method->getReturnTypeSourceRange().getBegin(), 4089 method->getReturnType(), 4090 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability, 4091 prevMethod->getReturnTypeSourceRange().getBegin(), 4092 prevMethod->getReturnType(), 4093 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability); 4094 method->setReturnType(newReturnType); 4095 4096 // Handle each of the parameters. 4097 unsigned numParams = method->param_size(); 4098 unsigned numPrevParams = prevMethod->param_size(); 4099 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) { 4100 ParmVarDecl *param = method->param_begin()[i]; 4101 ParmVarDecl *prevParam = prevMethod->param_begin()[i]; 4102 4103 // Merge nullability. 4104 QualType newParamType 4105 = mergeTypeNullabilityForRedecl( 4106 S, param->getLocation(), param->getType(), 4107 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability, 4108 prevParam->getLocation(), prevParam->getType(), 4109 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability); 4110 param->setType(newParamType); 4111 } 4112 } 4113 4114 Decl *Sema::ActOnMethodDeclaration( 4115 Scope *S, 4116 SourceLocation MethodLoc, SourceLocation EndLoc, 4117 tok::TokenKind MethodType, 4118 ObjCDeclSpec &ReturnQT, ParsedType ReturnType, 4119 ArrayRef<SourceLocation> SelectorLocs, 4120 Selector Sel, 4121 // optional arguments. The number of types/arguments is obtained 4122 // from the Sel.getNumArgs(). 4123 ObjCArgInfo *ArgInfo, 4124 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args 4125 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind, 4126 bool isVariadic, bool MethodDefinition) { 4127 // Make sure we can establish a context for the method. 4128 if (!CurContext->isObjCContainer()) { 4129 Diag(MethodLoc, diag::error_missing_method_context); 4130 return nullptr; 4131 } 4132 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext); 4133 Decl *ClassDecl = cast<Decl>(OCD); 4134 QualType resultDeclType; 4135 4136 bool HasRelatedResultType = false; 4137 TypeSourceInfo *ReturnTInfo = nullptr; 4138 if (ReturnType) { 4139 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo); 4140 4141 if (CheckFunctionReturnType(resultDeclType, MethodLoc)) 4142 return nullptr; 4143 4144 QualType bareResultType = resultDeclType; 4145 (void)AttributedType::stripOuterNullability(bareResultType); 4146 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType()); 4147 } else { // get the type for "id". 4148 resultDeclType = Context.getObjCIdType(); 4149 Diag(MethodLoc, diag::warn_missing_method_return_type) 4150 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)"); 4151 } 4152 4153 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create( 4154 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext, 4155 MethodType == tok::minus, isVariadic, 4156 /*isPropertyAccessor=*/false, 4157 /*isImplicitlyDeclared=*/false, /*isDefined=*/false, 4158 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional 4159 : ObjCMethodDecl::Required, 4160 HasRelatedResultType); 4161 4162 SmallVector<ParmVarDecl*, 16> Params; 4163 4164 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) { 4165 QualType ArgType; 4166 TypeSourceInfo *DI; 4167 4168 if (!ArgInfo[i].Type) { 4169 ArgType = Context.getObjCIdType(); 4170 DI = nullptr; 4171 } else { 4172 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI); 4173 } 4174 4175 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, 4176 LookupOrdinaryName, ForRedeclaration); 4177 LookupName(R, S); 4178 if (R.isSingleResult()) { 4179 NamedDecl *PrevDecl = R.getFoundDecl(); 4180 if (S->isDeclScope(PrevDecl)) { 4181 Diag(ArgInfo[i].NameLoc, 4182 (MethodDefinition ? diag::warn_method_param_redefinition 4183 : diag::warn_method_param_declaration)) 4184 << ArgInfo[i].Name; 4185 Diag(PrevDecl->getLocation(), 4186 diag::note_previous_declaration); 4187 } 4188 } 4189 4190 SourceLocation StartLoc = DI 4191 ? DI->getTypeLoc().getBeginLoc() 4192 : ArgInfo[i].NameLoc; 4193 4194 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc, 4195 ArgInfo[i].NameLoc, ArgInfo[i].Name, 4196 ArgType, DI, SC_None); 4197 4198 Param->setObjCMethodScopeInfo(i); 4199 4200 Param->setObjCDeclQualifier( 4201 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier())); 4202 4203 // Apply the attributes to the parameter. 4204 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs); 4205 4206 if (Param->hasAttr<BlocksAttr>()) { 4207 Diag(Param->getLocation(), diag::err_block_on_nonlocal); 4208 Param->setInvalidDecl(); 4209 } 4210 S->AddDecl(Param); 4211 IdResolver.AddDecl(Param); 4212 4213 Params.push_back(Param); 4214 } 4215 4216 for (unsigned i = 0, e = CNumArgs; i != e; ++i) { 4217 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param); 4218 QualType ArgType = Param->getType(); 4219 if (ArgType.isNull()) 4220 ArgType = Context.getObjCIdType(); 4221 else 4222 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]). 4223 ArgType = Context.getAdjustedParameterType(ArgType); 4224 4225 Param->setDeclContext(ObjCMethod); 4226 Params.push_back(Param); 4227 } 4228 4229 ObjCMethod->setMethodParams(Context, Params, SelectorLocs); 4230 ObjCMethod->setObjCDeclQualifier( 4231 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier())); 4232 4233 if (AttrList) 4234 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList); 4235 4236 // Add the method now. 4237 const ObjCMethodDecl *PrevMethod = nullptr; 4238 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) { 4239 if (MethodType == tok::minus) { 4240 PrevMethod = ImpDecl->getInstanceMethod(Sel); 4241 ImpDecl->addInstanceMethod(ObjCMethod); 4242 } else { 4243 PrevMethod = ImpDecl->getClassMethod(Sel); 4244 ImpDecl->addClassMethod(ObjCMethod); 4245 } 4246 4247 // Merge information from the @interface declaration into the 4248 // @implementation. 4249 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) { 4250 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(), 4251 ObjCMethod->isInstanceMethod())) { 4252 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD); 4253 4254 // Warn about defining -dealloc in a category. 4255 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() && 4256 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) { 4257 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category) 4258 << ObjCMethod->getDeclName(); 4259 } 4260 } 4261 } 4262 } else { 4263 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod); 4264 } 4265 4266 if (PrevMethod) { 4267 // You can never have two method definitions with the same name. 4268 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl) 4269 << ObjCMethod->getDeclName(); 4270 Diag(PrevMethod->getLocation(), diag::note_previous_declaration); 4271 ObjCMethod->setInvalidDecl(); 4272 return ObjCMethod; 4273 } 4274 4275 // If this Objective-C method does not have a related result type, but we 4276 // are allowed to infer related result types, try to do so based on the 4277 // method family. 4278 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl); 4279 if (!CurrentClass) { 4280 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) 4281 CurrentClass = Cat->getClassInterface(); 4282 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl)) 4283 CurrentClass = Impl->getClassInterface(); 4284 else if (ObjCCategoryImplDecl *CatImpl 4285 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) 4286 CurrentClass = CatImpl->getClassInterface(); 4287 } 4288 4289 ResultTypeCompatibilityKind RTC 4290 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass); 4291 4292 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC); 4293 4294 bool ARCError = false; 4295 if (getLangOpts().ObjCAutoRefCount) 4296 ARCError = CheckARCMethodDecl(ObjCMethod); 4297 4298 // Infer the related result type when possible. 4299 if (!ARCError && RTC == Sema::RTC_Compatible && 4300 !ObjCMethod->hasRelatedResultType() && 4301 LangOpts.ObjCInferRelatedResultType) { 4302 bool InferRelatedResultType = false; 4303 switch (ObjCMethod->getMethodFamily()) { 4304 case OMF_None: 4305 case OMF_copy: 4306 case OMF_dealloc: 4307 case OMF_finalize: 4308 case OMF_mutableCopy: 4309 case OMF_release: 4310 case OMF_retainCount: 4311 case OMF_initialize: 4312 case OMF_performSelector: 4313 break; 4314 4315 case OMF_alloc: 4316 case OMF_new: 4317 InferRelatedResultType = ObjCMethod->isClassMethod(); 4318 break; 4319 4320 case OMF_init: 4321 case OMF_autorelease: 4322 case OMF_retain: 4323 case OMF_self: 4324 InferRelatedResultType = ObjCMethod->isInstanceMethod(); 4325 break; 4326 } 4327 4328 if (InferRelatedResultType && 4329 !ObjCMethod->getReturnType()->isObjCIndependentClassType()) 4330 ObjCMethod->SetRelatedResultType(); 4331 } 4332 4333 ActOnDocumentableDecl(ObjCMethod); 4334 4335 return ObjCMethod; 4336 } 4337 4338 bool Sema::CheckObjCDeclScope(Decl *D) { 4339 // Following is also an error. But it is caused by a missing @end 4340 // and diagnostic is issued elsewhere. 4341 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) 4342 return false; 4343 4344 // If we switched context to translation unit while we are still lexically in 4345 // an objc container, it means the parser missed emitting an error. 4346 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext())) 4347 return false; 4348 4349 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope); 4350 D->setInvalidDecl(); 4351 4352 return true; 4353 } 4354 4355 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the 4356 /// instance variables of ClassName into Decls. 4357 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, 4358 IdentifierInfo *ClassName, 4359 SmallVectorImpl<Decl*> &Decls) { 4360 // Check that ClassName is a valid class 4361 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart); 4362 if (!Class) { 4363 Diag(DeclStart, diag::err_undef_interface) << ClassName; 4364 return; 4365 } 4366 if (LangOpts.ObjCRuntime.isNonFragile()) { 4367 Diag(DeclStart, diag::err_atdef_nonfragile_interface); 4368 return; 4369 } 4370 4371 // Collect the instance variables 4372 SmallVector<const ObjCIvarDecl*, 32> Ivars; 4373 Context.DeepCollectObjCIvars(Class, true, Ivars); 4374 // For each ivar, create a fresh ObjCAtDefsFieldDecl. 4375 for (unsigned i = 0; i < Ivars.size(); i++) { 4376 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]); 4377 RecordDecl *Record = dyn_cast<RecordDecl>(TagD); 4378 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, 4379 /*FIXME: StartL=*/ID->getLocation(), 4380 ID->getLocation(), 4381 ID->getIdentifier(), ID->getType(), 4382 ID->getBitWidth()); 4383 Decls.push_back(FD); 4384 } 4385 4386 // Introduce all of these fields into the appropriate scope. 4387 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin(); 4388 D != Decls.end(); ++D) { 4389 FieldDecl *FD = cast<FieldDecl>(*D); 4390 if (getLangOpts().CPlusPlus) 4391 PushOnScopeChains(cast<FieldDecl>(FD), S); 4392 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD)) 4393 Record->addDecl(FD); 4394 } 4395 } 4396 4397 /// \brief Build a type-check a new Objective-C exception variable declaration. 4398 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T, 4399 SourceLocation StartLoc, 4400 SourceLocation IdLoc, 4401 IdentifierInfo *Id, 4402 bool Invalid) { 4403 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 4404 // duration shall not be qualified by an address-space qualifier." 4405 // Since all parameters have automatic store duration, they can not have 4406 // an address space. 4407 if (T.getAddressSpace() != 0) { 4408 Diag(IdLoc, diag::err_arg_with_address_space); 4409 Invalid = true; 4410 } 4411 4412 // An @catch parameter must be an unqualified object pointer type; 4413 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"? 4414 if (Invalid) { 4415 // Don't do any further checking. 4416 } else if (T->isDependentType()) { 4417 // Okay: we don't know what this type will instantiate to. 4418 } else if (!T->isObjCObjectPointerType()) { 4419 Invalid = true; 4420 Diag(IdLoc ,diag::err_catch_param_not_objc_type); 4421 } else if (T->isObjCQualifiedIdType()) { 4422 Invalid = true; 4423 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm); 4424 } 4425 4426 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id, 4427 T, TInfo, SC_None); 4428 New->setExceptionVariable(true); 4429 4430 // In ARC, infer 'retaining' for variables of retainable type. 4431 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New)) 4432 Invalid = true; 4433 4434 if (Invalid) 4435 New->setInvalidDecl(); 4436 return New; 4437 } 4438 4439 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) { 4440 const DeclSpec &DS = D.getDeclSpec(); 4441 4442 // We allow the "register" storage class on exception variables because 4443 // GCC did, but we drop it completely. Any other storage class is an error. 4444 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) { 4445 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm) 4446 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc())); 4447 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) { 4448 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm) 4449 << DeclSpec::getSpecifierName(SCS); 4450 } 4451 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) 4452 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(), 4453 diag::err_invalid_thread) 4454 << DeclSpec::getSpecifierName(TSCS); 4455 D.getMutableDeclSpec().ClearStorageClassSpecs(); 4456 4457 DiagnoseFunctionSpecifiers(D.getDeclSpec()); 4458 4459 // Check that there are no default arguments inside the type of this 4460 // exception object (C++ only). 4461 if (getLangOpts().CPlusPlus) 4462 CheckExtraCXXDefaultArguments(D); 4463 4464 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 4465 QualType ExceptionType = TInfo->getType(); 4466 4467 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType, 4468 D.getSourceRange().getBegin(), 4469 D.getIdentifierLoc(), 4470 D.getIdentifier(), 4471 D.isInvalidType()); 4472 4473 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1). 4474 if (D.getCXXScopeSpec().isSet()) { 4475 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm) 4476 << D.getCXXScopeSpec().getRange(); 4477 New->setInvalidDecl(); 4478 } 4479 4480 // Add the parameter declaration into this scope. 4481 S->AddDecl(New); 4482 if (D.getIdentifier()) 4483 IdResolver.AddDecl(New); 4484 4485 ProcessDeclAttributes(S, New, D); 4486 4487 if (New->hasAttr<BlocksAttr>()) 4488 Diag(New->getLocation(), diag::err_block_on_nonlocal); 4489 return New; 4490 } 4491 4492 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require 4493 /// initialization. 4494 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, 4495 SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 4496 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; 4497 Iv= Iv->getNextIvar()) { 4498 QualType QT = Context.getBaseElementType(Iv->getType()); 4499 if (QT->isRecordType()) 4500 Ivars.push_back(Iv); 4501 } 4502 } 4503 4504 void Sema::DiagnoseUseOfUnimplementedSelectors() { 4505 // Load referenced selectors from the external source. 4506 if (ExternalSource) { 4507 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels; 4508 ExternalSource->ReadReferencedSelectors(Sels); 4509 for (unsigned I = 0, N = Sels.size(); I != N; ++I) 4510 ReferencedSelectors[Sels[I].first] = Sels[I].second; 4511 } 4512 4513 // Warning will be issued only when selector table is 4514 // generated (which means there is at lease one implementation 4515 // in the TU). This is to match gcc's behavior. 4516 if (ReferencedSelectors.empty() || 4517 !Context.AnyObjCImplementation()) 4518 return; 4519 for (auto &SelectorAndLocation : ReferencedSelectors) { 4520 Selector Sel = SelectorAndLocation.first; 4521 SourceLocation Loc = SelectorAndLocation.second; 4522 if (!LookupImplementedMethodInGlobalPool(Sel)) 4523 Diag(Loc, diag::warn_unimplemented_selector) << Sel; 4524 } 4525 } 4526 4527 ObjCIvarDecl * 4528 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, 4529 const ObjCPropertyDecl *&PDecl) const { 4530 if (Method->isClassMethod()) 4531 return nullptr; 4532 const ObjCInterfaceDecl *IDecl = Method->getClassInterface(); 4533 if (!IDecl) 4534 return nullptr; 4535 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true, 4536 /*shallowCategoryLookup=*/false, 4537 /*followSuper=*/false); 4538 if (!Method || !Method->isPropertyAccessor()) 4539 return nullptr; 4540 if ((PDecl = Method->findPropertyDecl())) 4541 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) { 4542 // property backing ivar must belong to property's class 4543 // or be a private ivar in class's implementation. 4544 // FIXME. fix the const-ness issue. 4545 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable( 4546 IV->getIdentifier()); 4547 return IV; 4548 } 4549 return nullptr; 4550 } 4551 4552 namespace { 4553 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property 4554 /// accessor references the backing ivar. 4555 class UnusedBackingIvarChecker : 4556 public DataRecursiveASTVisitor<UnusedBackingIvarChecker> { 4557 public: 4558 Sema &S; 4559 const ObjCMethodDecl *Method; 4560 const ObjCIvarDecl *IvarD; 4561 bool AccessedIvar; 4562 bool InvokedSelfMethod; 4563 4564 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method, 4565 const ObjCIvarDecl *IvarD) 4566 : S(S), Method(Method), IvarD(IvarD), 4567 AccessedIvar(false), InvokedSelfMethod(false) { 4568 assert(IvarD); 4569 } 4570 4571 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) { 4572 if (E->getDecl() == IvarD) { 4573 AccessedIvar = true; 4574 return false; 4575 } 4576 return true; 4577 } 4578 4579 bool VisitObjCMessageExpr(ObjCMessageExpr *E) { 4580 if (E->getReceiverKind() == ObjCMessageExpr::Instance && 4581 S.isSelfExpr(E->getInstanceReceiver(), Method)) { 4582 InvokedSelfMethod = true; 4583 } 4584 return true; 4585 } 4586 }; 4587 } // end anonymous namespace 4588 4589 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S, 4590 const ObjCImplementationDecl *ImplD) { 4591 if (S->hasUnrecoverableErrorOccurred()) 4592 return; 4593 4594 for (const auto *CurMethod : ImplD->instance_methods()) { 4595 unsigned DIAG = diag::warn_unused_property_backing_ivar; 4596 SourceLocation Loc = CurMethod->getLocation(); 4597 if (Diags.isIgnored(DIAG, Loc)) 4598 continue; 4599 4600 const ObjCPropertyDecl *PDecl; 4601 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl); 4602 if (!IV) 4603 continue; 4604 4605 UnusedBackingIvarChecker Checker(*this, CurMethod, IV); 4606 Checker.TraverseStmt(CurMethod->getBody()); 4607 if (Checker.AccessedIvar) 4608 continue; 4609 4610 // Do not issue this warning if backing ivar is used somewhere and accessor 4611 // implementation makes a self call. This is to prevent false positive in 4612 // cases where the ivar is accessed by another method that the accessor 4613 // delegates to. 4614 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) { 4615 Diag(Loc, DIAG) << IV; 4616 Diag(PDecl->getLocation(), diag::note_property_declare); 4617 } 4618 } 4619 } 4620