-
Notifications
You must be signed in to change notification settings - Fork 10.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[SR-11588]Warn about derived Hashable implementation if there’s a custom Equatable #27801
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -6126,6 +6126,11 @@ ERROR(override_nsobject_hash_error,none, | |||||
"'NSObject.hash(into:)' is not overridable; " | ||||||
"did you mean to override 'NSObject.hash'?", ()) | ||||||
|
||||||
WARNING(synthesized_hashable_may_not_match_custom_equatable, none, | ||||||
"automatically generated 'Hashable' implementation for type %0 " | ||||||
"may not match the behavior of custom '==' operator", (Type)) | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
(Reduced written register doesn't use a definite article here.) More pertinently, is there a word to describe what is meant better than "match"? To me, a simple reading would suggest that 'Hashable' should behave like '==', and of course that doesn't make sense; a reader might ignore the warning because why would they want two disparate things (a protocol and an operator) to "match"? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. "be compatible with" might be more precise, but that's still not really actionable for the user unless we spell out what "compatible" actually means. I'm not sure how verbose we want this warning to be, however. Ideally we'd be able to just stick in a reference to some relevant documentation or something. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe, “aligned”? Instead of “behavior,” maybe “semantics”? Not sure but I think we can get a little closer with some wordsmithing. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. So if we were going to really spell it out precisely, what would we say? Let's start with that and try to back off. Something like "Any two values that compare equal with There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yeah, you beat me to the punch. I was going to suggest something similar: "custom 'Equatable' conformance without custom 'Hashable' conformance may cause equivalent values to have different hashes" (fixit: insert missing declarations required by 'Hashable') [Edit: or, "custom 'Equatable' conformance with synthesized 'Hashable' conformance may cause unexpected behavior; equivalent values must have same hash"] |
||||||
NOTE(add_custom_hashable, none, "add a custom 'hash(into:)' method", ()) | ||||||
|
||||||
WARNING(hashvalue_implementation,Deprecation, | ||||||
"'Hashable.hashValue' is deprecated as a protocol requirement; " | ||||||
"conform type %0 to 'Hashable' by implementing 'hash(into:)' instead", | ||||||
|
Original file line number | Diff line number | Diff line change | ||||
---|---|---|---|---|---|---|
|
@@ -11,7 +11,7 @@ | |||||
//===----------------------------------------------------------------------===https:// | ||||||
// | ||||||
// This file implements implicit derivation of the Equatable and Hashable | ||||||
// protocols. | ||||||
// protocols. | ||||||
// | ||||||
//===----------------------------------------------------------------------===https:// | ||||||
|
||||||
|
@@ -232,7 +232,7 @@ deriveBodyEquatable_enum_hasAssociatedValues_eq(AbstractFunctionDecl *eqDecl, | |||||
auto rhsVar = rhsPayloadVars[varIdx]; | ||||||
auto rhsExpr = new (C) DeclRefExpr(rhsVar, DeclNameLoc(), | ||||||
/*Implicit*/true); | ||||||
auto guardStmt = DerivedConformance::returnFalseIfNotEqualGuard(C, | ||||||
auto guardStmt = DerivedConformance::returnFalseIfNotEqualGuard(C, | ||||||
lhsExpr, rhsExpr); | ||||||
statementsInCase.emplace_back(guardStmt); | ||||||
} | ||||||
|
@@ -502,7 +502,7 @@ static CallExpr *createHasherCombineCall(ASTContext &C, | |||||
// hasher.combine(_:) | ||||||
auto *combineCall = UnresolvedDotExpr::createImplicit( | ||||||
C, hasherExpr, C.Id_combine, {Identifier()}); | ||||||
|
||||||
// hasher.combine(hashable) | ||||||
auto *argList = ArgumentList::forImplicitUnlabeled(C, {hashable}); | ||||||
return CallExpr::createImplicit(C, combineCall, argList); | ||||||
|
@@ -1006,14 +1006,14 @@ ValueDecl *DerivedConformance::deriveHashable(ValueDecl *requirement) { | |||||
if (hashValueDecl->isImplicit()) { | ||||||
// Neither hashValue nor hash(into:) is explicitly defined; we need to do | ||||||
// a full Hashable derivation. | ||||||
|
||||||
// Refuse to synthesize Hashable if type isn't a struct or enum, or if it | ||||||
// has non-Hashable stored properties/associated values. | ||||||
auto hashableProto = C.getProtocol(KnownProtocolKind::Hashable); | ||||||
auto nominalTy = Nominal->getDeclaredType(); | ||||||
if (!canDeriveConformance(getConformanceContext(), Nominal, | ||||||
hashableProto)) { | ||||||
ConformanceDecl->diagnose(diag::type_does_not_conform, | ||||||
Nominal->getDeclaredType(), | ||||||
ConformanceDecl->diagnose(diag::type_does_not_conform, nominalTy, | ||||||
hashableProto->getDeclaredInterfaceType()); | ||||||
// Ideally, this would be diagnosed in | ||||||
// ConformanceChecker::resolveWitnessViaLookup. That doesn't work for | ||||||
|
@@ -1028,6 +1028,27 @@ ValueDecl *DerivedConformance::deriveHashable(ValueDecl *requirement) { | |||||
if (checkAndDiagnoseDisallowedContext(requirement)) | ||||||
return nullptr; | ||||||
|
||||||
// Warn the user that having a custom == almost surely require a | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
// custom Hashable conformance even if, for source stability reasons, | ||||||
// it will be synthesized | ||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||
auto equatableProto = C.getProtocol(KnownProtocolKind::Equatable); | ||||||
auto eqConformance = TypeChecker::conformsToProtocol(nominalTy, | ||||||
equatableProto, getParentModule()); | ||||||
if (eqConformance) { | ||||||
DeclName equalsName(C, DeclBaseName(C.Id_EqualsOperator), | ||||||
{Identifier(), Identifier()}); | ||||||
ConcreteDeclRef witness = eqConformance.getWitnessByName( | ||||||
nominalTy->getRValueType(), equalsName); | ||||||
|
||||||
auto equalsDeclaration = witness.getDecl(); | ||||||
if (equalsDeclaration && !equalsDeclaration->isImplicit()) { | ||||||
equalsDeclaration->diagnose( | ||||||
diag::synthesized_hashable_may_not_match_custom_equatable, | ||||||
nominalTy); | ||||||
equalsDeclaration->diagnose(diag::add_custom_hashable); | ||||||
} | ||||||
} | ||||||
|
||||||
if (auto ED = dyn_cast<EnumDecl>(Nominal)) { | ||||||
std::pair<BraceStmt *, bool> (*bodySynthesizer)( | ||||||
AbstractFunctionDecl *, void *); | ||||||
|
@@ -1043,7 +1064,7 @@ ValueDecl *DerivedConformance::deriveHashable(ValueDecl *requirement) { | |||||
&deriveBodyHashable_struct_hashInto); | ||||||
else // This should've been caught by canDeriveHashable above. | ||||||
llvm_unreachable("Attempt to derive Hashable for a type other " | ||||||
"than a struct or enum"); | ||||||
"than a struct or enum"); | ||||||
} else { | ||||||
// hashValue has an explicit implementation, but hash(into:) doesn't. | ||||||
// Emit a deprecation warning, then derive hash(into:) in terms of | ||||||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
public struct ImplicitEquatable: ExpressibleByIntegerLiteral, Equatable { | ||
public init(integerLiteral: Int) {} | ||
} | ||
|
||
public struct ExplicitEquatable: ExpressibleByIntegerLiteral, Equatable { | ||
public init(integerLiteral: Int) {} | ||
|
||
public static func == (lhs: ExplicitEquatable, rhs: ExplicitEquatable) -> Bool { | ||
return true | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,90 @@ | ||
// RUN: %empty-directory(%t) | ||
// RUN: %target-swift-frontend -emit-module -o %t/NormalLibrary.swiftmodule %S/Inputs/external_equatable_conformance.swift | ||
|
||
// RUN: %target-typecheck-verify-swift -I %t | ||
|
||
import NormalLibrary | ||
|
||
// All conformance synthesized no warning emitted | ||
struct NoCustomEquatable: Hashable { | ||
let a:Int | ||
} | ||
|
||
// Equatable implemented and Hashable synthesized raise a warning | ||
enum CustomEquatable: Hashable { | ||
case a | ||
|
||
static func == (lhs: CustomEquatable, rhs: CustomEquatable) -> Bool { | ||
// expected-warning@-1 {{automatically generated 'Hashable' implementation for type 'CustomEquatable' may not match the behavior of custom '==' operator}} | ||
// expected-note@-2 {{add a custom 'hash(into:)' method}} | ||
return true | ||
} | ||
} | ||
|
||
// All conformance implemented no warning emitted | ||
enum CustomHashable: Hashable { | ||
case a | ||
|
||
func hash(into hasher: inout Hasher) {} | ||
|
||
static func == (lhs: CustomHashable, rhs: CustomHashable) -> Bool { | ||
return true | ||
} | ||
} | ||
|
||
struct ExtendedConformance: Hashable { | ||
let a:Int | ||
} | ||
|
||
extension ExtendedConformance { | ||
static func == (lhs: ExtendedConformance, rhs: ExtendedConformance) -> Bool { | ||
// expected-warning@-1 {{automatically generated 'Hashable' implementation for type 'ExtendedConformance' may not match the behavior of custom '==' operator}} | ||
// expected-note@-2 {{add a custom 'hash(into:)' method}} | ||
return true | ||
} | ||
} | ||
|
||
enum ImportedConformance: ImplicitEquatable { | ||
case x = 1 | ||
} | ||
|
||
enum ImportedExplicitConformance: ExplicitEquatable { | ||
case x = 1 | ||
} | ||
|
||
protocol DefaultedImplementationProtocol: Equatable {} | ||
extension DefaultedImplementationProtocol { | ||
static func == (lhs: Self, rhs: Self) -> Bool { true } | ||
// expected-warning@-1 {{automatically generated 'Hashable' implementation for type 'DefaultedImplementation' may not match the behavior of custom '==' operator}} | ||
// expected-note@-2 {{add a custom 'hash(into:)' method}} | ||
} | ||
|
||
struct DefaultedImplementation: DefaultedImplementationProtocol, Hashable { | ||
let a: Int | ||
} | ||
|
||
protocol ConditionalImplementationProtocol {} | ||
extension ConditionalImplementationProtocol where Self: Equatable { | ||
static func == (lhs: Self, rhs: Self) -> Bool { true } | ||
// expected-warning@-1 {{automatically generated 'Hashable' implementation for type 'ConditionalImplementation' may not match the behavior of custom '==' operator}} | ||
// expected-note@-2 {{add a custom 'hash(into:)' method}} | ||
} | ||
|
||
struct ConditionalImplementation: ConditionalImplementationProtocol, Hashable { | ||
let a: Int | ||
} | ||
|
||
protocol ConditionalHashableImplementationProtocol {} | ||
extension ConditionalHashableImplementationProtocol where Self: Equatable { | ||
static func == (lhs: Self, rhs: Self) -> Bool { true } | ||
// expected-warning@-1 {{automatically generated 'Hashable' implementation for type 'ConditionalHashableImplementation' may not match the behavior of custom '==' operator}} | ||
// expected-note@-2 {{add a custom 'hash(into:)' method}} | ||
} | ||
|
||
extension ConditionalHashableImplementationProtocol where Self: Hashable { | ||
func hash(into hasher: Hasher) {} | ||
} | ||
|
||
struct ConditionalHashableImplementation: ConditionalHashableImplementationProtocol, Hashable { | ||
let a: Int | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is there a reason to avoid the commonly used word 'synthesized' here?