Skip to content

[SR-9425][Sema] Use derived conformance as witness when possible for == operator of raw representable enums #36752

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

Merged
merged 6 commits into from
Apr 21, 2021
Merged
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
45 changes: 45 additions & 0 deletions lib/Sema/TypeCheckProtocol.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3833,6 +3833,30 @@ void ConformanceChecker::checkNonFinalClassWitness(ValueDecl *requirement,
}
}

// If the given witness matches a generic RawRepresentable function conforming
// with a given protocol e.g. `func == <T : RawRepresentable>(lhs: T, rhs: T) ->
// Bool where T.RawValue : Equatable`
static bool isRawRepresentableGenericFunction(
ASTContext &ctx, const ValueDecl *witness,
const NormalProtocolConformance *conformance) {
auto *fnDecl = dyn_cast<AbstractFunctionDecl>(witness);
if (!fnDecl || !fnDecl->isStdlibDecl())
return false;

return fnDecl->isGeneric() && fnDecl->getGenericParams()->size() == 1 &&
fnDecl->getGenericRequirements().size() == 2 &&
llvm::all_of(
fnDecl->getGenericRequirements(), [&](Requirement genericReq) {
if (genericReq.getKind() != RequirementKind::Conformance)
return false;
return genericReq.getProtocolDecl() ==
ctx.getProtocol(
KnownProtocolKind::RawRepresentable) ||
genericReq.getProtocolDecl() ==
conformance->getProtocol();
});
}

ResolveWitnessResult
ConformanceChecker::resolveWitnessViaLookup(ValueDecl *requirement) {
assert(!isa<AssociatedTypeDecl>(requirement) && "Use resolveTypeWitnessVia*");
Expand Down Expand Up @@ -3881,6 +3905,16 @@ ConformanceChecker::resolveWitnessViaLookup(ValueDecl *requirement) {
bool considerRenames =
!canDerive && !requirement->getAttrs().hasAttribute<OptionalAttr>() &&
!requirement->getAttrs().isUnavailable(getASTContext());

auto &ctx = getASTContext();
bool isEquatableConformance = Conformance->getProtocol() ==
ctx.getProtocol(KnownProtocolKind::Equatable);

auto decl = Conformance->getDeclContext()->getSelfNominalTypeDecl();
auto *enumDecl = dyn_cast_or_null<EnumDecl>(decl);
bool isSwiftRawRepresentableEnum =
enumDecl && enumDecl->hasRawType() && !enumDecl->isObjC();

if (findBestWitness(requirement,
considerRenames ? &ignoringNames : nullptr,
Conformance,
Expand All @@ -3889,6 +3923,17 @@ ConformanceChecker::resolveWitnessViaLookup(ValueDecl *requirement) {
const auto &best = matches[bestIdx];
auto witness = best.Witness;

if (canDerive && isSwiftRawRepresentableEnum && isEquatableConformance) {
// For swift enum types that can derive equatable conformance,
// if the best witness is default generic conditional conforming
// `func == <T : RawRepresentable>(lhs: T, rhs: T) -> Bool where
// T.RawValue : Equatable` let's return as missing and derive
// the conformance since it is possible.
if (isRawRepresentableGenericFunction(ctx, witness, Conformance)) {
return ResolveWitnessResult::Missing;
}
}

// If the name didn't actually line up, complain.
if (ignoringNames &&
requirement->getName() != best.Witness->getName() &&
Expand Down
70 changes: 70 additions & 0 deletions test/SILGen/enum_equatable_witness.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// RUN: %target-swift-emit-silgen -module-name main %s -verify | %FileCheck %s
// SR-9425
enum MyState : String {
case closed = "closed"
case opened = "opened"
}

@inline(never)
func check_state(_ state : MyState) -> Int {
// CHECK: function_ref @$s4main7MyStateO21__derived_enum_equalsySbAC_ACtFZ
return state == .opened ? 1 : 0
}

// generic-enum.swift
enum GenericMyState<T> : String {
case closed
case opened
}

@inline(never)
func check_generic_state(_ state : GenericMyState<Int>) -> Int {
// CHECK: function_ref @$s4main14GenericMyStateO21__derived_enum_equalsySbACyxG_AEtFZ
return state == .opened ? 1 : 0
}

// regular-enum.swift
enum Regular {
case closed
case opened
}

@inline(never)
func check_regular(_ state : Regular) -> Int {
// CHECK: function_ref @$s4main7RegularO21__derived_enum_equalsySbAC_ACtFZ
return state == .closed ? 1 : 0
}

// string-enum.swift
enum Alphabet : String {
case A = "A", B = "B", C = "C", D = "D", E = "E", F = "F", G = "G", H = "H", I = "I", J = "J"
}

@inline(never)
func check_alphabet(_ state : Alphabet) -> Int {
// CHECK: function_ref @$s4main8AlphabetO21__derived_enum_equalsySbAC_ACtFZ
return state == .E ? 1 : 0
}

@inline(never)
func compareIt(_ state : Alphabet, _ rhs: Alphabet) -> Bool {
// CHECK: function_ref @$s4main8AlphabetO21__derived_enum_equalsySbAC_ACtFZ
return state == rhs
}

// int-enum.swift
enum AlphabetInt : Int {
case A = 10, B = 100, C = 12, D = 456, E = 1, F = 3, G = 77, H = 2, I = 27, J = 42
}

@inline(never)
func check_alphabet_int(_ state : AlphabetInt) -> Int {
// CHECK: function_ref @$s4main11AlphabetIntO21__derived_enum_equalsySbAC_ACtFZ
return state == .E ? 1 : 0
}

@inline(never)
func compareIt(_ state : AlphabetInt, _ rhs: AlphabetInt) -> Bool {
// CHECK: function_ref @$s4main11AlphabetIntO21__derived_enum_equalsySbAC_ACtFZ
return state == rhs
}
26 changes: 23 additions & 3 deletions test/SILGen/opaque_ownership.swift
Original file line number Diff line number Diff line change
Expand Up @@ -150,13 +150,33 @@ public struct Int64 : ExpressibleByIntegerLiteral, _ExpressibleByBuiltinIntegerL
}
}

public struct Int : _ExpressibleByBuiltinIntegerLiteral, ExpressibleByIntegerLiteral, Equatable {
var _value: Builtin.Int64
public init() {
self = 0
}
public typealias IntegerLiteralType = Int
public init(_builtinIntegerLiteral x: _MaxBuiltinIntegerType) {
_value = Builtin.s_to_s_checked_trunc_IntLiteral_Int64(x).0
}

public init(integerLiteral value: Int) {
self = value
}

public static func ==(_ lhs: Int, rhs: Int) -> Bool {
return Bool(Builtin.cmp_eq_Int64(lhs._value, rhs._value))
}
}

// Test ownership of multi-case Enum values in the context of to @in thunks.
// ---
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] [ossa] @$ss17FloatingPointSignOSQsSQ2eeoiySbx_xtFZTW :
// CHECK: bb0(%0 : $FloatingPointSign, %1 : $FloatingPointSign, %2 : $@thick FloatingPointSign.Type):
// CHECK: %3 = function_ref @$ss2eeoiySbx_xtSYRzSQ8RawValueRpzlF : $@convention(thin) <τ_0_0 where τ_0_0 : RawRepresentable, τ_0_0.RawValue : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool
// CHECK: %4 = apply %3<FloatingPointSign>(%0, %1) : $@convention(thin) <τ_0_0 where τ_0_0 : RawRepresentable, τ_0_0.RawValue : Equatable> (@in_guaranteed τ_0_0, @in_guaranteed τ_0_0) -> Bool
// CHECK: return %4 : $Bool
// CHECK: %3 = metatype $@thin FloatingPointSign.Type // user: %5
// CHECK: %4 = function_ref @$ss17FloatingPointSignO21__derived_enum_equalsySbAB_ABtFZ : $@convention(method) (FloatingPointSign, FloatingPointSign, @thin FloatingPointSign.Type) -> Bool // user: %5
// CHECK: %5 = apply %4(%0, %1, %3) : $@convention(method) (FloatingPointSign, FloatingPointSign, @thin FloatingPointSign.Type) -> Bool // user: %6
// CHECK: return %5 : $Bool
// CHECK-LABEL: } // end sil function '$ss17FloatingPointSignOSQsSQ2eeoiySbx_xtFZTW'
public enum FloatingPointSign: Int64 {
/// The sign for a positive value.
Expand Down
31 changes: 31 additions & 0 deletions test/api-digester/Outputs/cake-abi.json
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,37 @@
"moduleName": "cake",
"fixedbinaryorder": 0
},
{
"kind": "Function",
"name": "__derived_enum_equals",
"printedName": "__derived_enum_equals(_:_:)",
"children": [
{
"kind": "TypeNominal",
"name": "Bool",
"printedName": "Swift.Bool",
"usr": "s:Sb"
},
{
"kind": "TypeNominal",
"name": "Number",
"printedName": "cake.Number",
"usr": "s:4cake6NumberO"
},
{
"kind": "TypeNominal",
"name": "Number",
"printedName": "cake.Number",
"usr": "s:4cake6NumberO"
}
],
"declKind": "Func",
"usr": "s:4cake6NumberO21__derived_enum_equalsySbAC_ACtFZ",
"moduleName": "cake",
"static": true,
"implicit": true,
"funcSelfKind": "NonMutating"
},
{
"kind": "Constructor",
"name": "init",
Expand Down
31 changes: 31 additions & 0 deletions test/api-digester/Outputs/cake.json
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,37 @@
"usr": "s:4cake6NumberO3oneyA2CmF",
"moduleName": "cake"
},
{
"kind": "Function",
"name": "__derived_enum_equals",
"printedName": "__derived_enum_equals(_:_:)",
"children": [
{
"kind": "TypeNominal",
"name": "Bool",
"printedName": "Swift.Bool",
"usr": "s:Sb"
},
{
"kind": "TypeNominal",
"name": "Number",
"printedName": "cake.Number",
"usr": "s:4cake6NumberO"
},
{
"kind": "TypeNominal",
"name": "Number",
"printedName": "cake.Number",
"usr": "s:4cake6NumberO"
}
],
"declKind": "Func",
"usr": "s:4cake6NumberO21__derived_enum_equalsySbAC_ACtFZ",
"moduleName": "cake",
"static": true,
"implicit": true,
"funcSelfKind": "NonMutating"
},
{
"kind": "Constructor",
"name": "init",
Expand Down