Skip to content
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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -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 "
Copy link
Collaborator

@xwu xwu Aug 25, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"automatically generated 'Hashable' implementation for type %0 "
"synthesized 'Hashable' implementation for type %0 "

Is there a reason to avoid the commonly used word 'synthesized' here?

"may not match the behavior of custom '==' operator", (Type))
Copy link
Collaborator

@xwu xwu Aug 25, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"may not match the behavior of custom '==' operator", (Type))
"may not match behavior of custom '==' operator", (Type))

(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"?

Copy link
Contributor

Choose a reason for hiding this comment

The 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.

Copy link
Collaborator

Choose a reason for hiding this comment

The 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.

Copy link
Contributor

Choose a reason for hiding this comment

The 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 == must also have the same hash; because you have provided a custom == implementation for %0, you should also provide a custom implementation of Hashable."

Copy link
Collaborator

@xwu xwu Aug 25, 2021

Choose a reason for hiding this comment

The 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",
Expand Down
35 changes: 28 additions & 7 deletions lib/Sema/DerivedConformanceEquatableHashable.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
//===----------------------------------------------------------------------===https://
//
// This file implements implicit derivation of the Equatable and Hashable
// protocols.
// protocols.
//
//===----------------------------------------------------------------------===https://

Expand Down Expand Up @@ -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);
}
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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
Expand All @@ -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
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Warn the user that having a custom == almost surely require a
// Warn the user that having a custom == almost surely requires a

// custom Hashable conformance even if, for source stability reasons,
// it will be synthesized
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// it will be synthesized
// it will be synthesized.

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 *);
Expand All @@ -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
Expand Down
11 changes: 11 additions & 0 deletions test/Sema/Inputs/external_equatable_conformance.swift
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
}
}
90 changes: 90 additions & 0 deletions test/Sema/diag_custom_equatable_synthesized_hashable.swift
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
}
2 changes: 2 additions & 0 deletions test/Sema/enum_conformance_synthesis.swift
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,8 @@ public enum Medicine {
extension Medicine : Equatable {}

public func ==(lhs: Medicine, rhs: Medicine) -> Bool {
// expected-warning@-1 {{automatically generated 'Hashable' implementation for type 'Medicine' may not match the behavior of custom '==' operator}}
// expected-note@-2 {{add a custom 'hash(into:)' method}}
return true
}

Expand Down