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