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