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