Skip to content

[4.2] Handle unexpected raw values for @objc enums in derived conformances #17881

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
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
46 changes: 42 additions & 4 deletions lib/Sema/DerivedConformanceEquatableHashable.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -831,6 +831,35 @@ deriveBodyHashable_compat_hashInto(AbstractFunctionDecl *hashIntoDecl) {
hashIntoDecl->setBody(body);
}

/// Derive the body for the 'hash(into:)' method for an enum by using its raw
/// value.
static void
deriveBodyHashable_enum_rawValue_hashInto(
AbstractFunctionDecl *hashIntoDecl
) {
// enum SomeEnum: Int {
// case A, B, C
// @derived func hash(into hasher: inout Hasher) {
// hasher.combine(self.rawValue)
// }
// }
ASTContext &C = hashIntoDecl->getASTContext();

// generate: self.rawValue
auto *selfRef = DerivedConformance::createSelfDeclRef(hashIntoDecl);
auto *rawValueRef = new (C) UnresolvedDotExpr(selfRef, SourceLoc(),
C.Id_rawValue, DeclNameLoc(),
/*Implicit=*/true);

// generate: hasher.combine(discriminator)
auto hasherParam = hashIntoDecl->getParameterList(1)->get(0);
ASTNode combineStmt = createHasherCombineCall(C, hasherParam, rawValueRef);

auto body = BraceStmt::create(C, SourceLoc(), combineStmt, SourceLoc(),
/*implicit*/ true);
hashIntoDecl->setBody(body);
}

/// Derive the body for the 'hash(into:)' method for an enum without associated
/// values.
static void
Expand Down Expand Up @@ -1203,10 +1232,19 @@ ValueDecl *DerivedConformance::deriveHashable(ValueDecl *requirement) {
return nullptr;

if (auto ED = dyn_cast<EnumDecl>(Nominal)) {
auto bodySynthesizer =
!ED->hasOnlyCasesWithoutAssociatedValues()
? &deriveBodyHashable_enum_hasAssociatedValues_hashInto
: &deriveBodyHashable_enum_noAssociatedValues_hashInto;
void (*bodySynthesizer)(AbstractFunctionDecl *);
if (ED->hasClangNode() ||
(ED->isObjC() && ED->hasRawType() &&
!ED->getInherited().front().isError())) {
// The checks for the raw type help avoid superfluous diagnostics in
// invalid code.
bodySynthesizer = deriveBodyHashable_enum_rawValue_hashInto;
} else if (ED->hasOnlyCasesWithoutAssociatedValues()) {
bodySynthesizer = deriveBodyHashable_enum_noAssociatedValues_hashInto;
} else {
bodySynthesizer =
deriveBodyHashable_enum_hasAssociatedValues_hashInto;
}
return deriveHashable_hashInto(*this, bodySynthesizer);
} else if (isa<StructDecl>(Nominal))
return deriveHashable_hashInto(*this,
Expand Down
21 changes: 21 additions & 0 deletions lib/Sema/DerivedConformanceRawRepresentable.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,27 @@ static void deriveBodyRawRepresentable_raw(AbstractFunctionDecl *toRawDecl) {
}
#endif

if (enumDecl->isObjC()) {
// Special case: ObjC enums are represented by their raw value, so just use
// a bitcast.

// return unsafeBitCast(self, to: RawType.self)
DeclName name(C, C.getIdentifier("unsafeBitCast"), {Identifier(), C.Id_to});
auto functionRef = new (C) UnresolvedDeclRefExpr(name,
DeclRefKind::Ordinary,
DeclNameLoc());
auto selfRef = DerivedConformance::createSelfDeclRef(toRawDecl);
auto bareTypeExpr = TypeExpr::createImplicit(rawTy, C);
auto typeExpr = new (C) DotSelfExpr(bareTypeExpr, SourceLoc(), SourceLoc());
auto call = CallExpr::createImplicit(C, functionRef, {selfRef, typeExpr},
{Identifier(), C.Id_to});
auto returnStmt = new (C) ReturnStmt(SourceLoc(), call);
auto body = BraceStmt::create(C, SourceLoc(), ASTNode(returnStmt),
SourceLoc());
toRawDecl->setBody(body);
return;
}

Type enumType = parentDC->getDeclaredTypeInContext();

SmallVector<ASTNode, 4> cases;
Expand Down
36 changes: 36 additions & 0 deletions test/Interpreter/enum-nonexhaustivity.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,18 @@ EnumTestSuite.test("UnexpectedOkayNested2/NonExhaustive") {
expectTrue(gotCorrectValue)
}

EnumTestSuite.test("Equatable/NonExhaustive") {
expectEqual(getExpectedValue(), .B)
expectNotEqual(getUnexpectedValue(), .B)
expectNotEqual(getExpectedValue(), getUnexpectedValue())
expectEqual(getUnexpectedValue(), getUnexpectedValue())
}

EnumTestSuite.test("Hashable/NonExhaustive") {
expectEqual(getExpectedValue().hashValue, NonExhaustiveEnum.B.hashValue)
expectNotEqual(getUnexpectedValue().hashValue, NonExhaustiveEnum.B.hashValue)
}


EnumTestSuite.test("PlainOldSwitch/LyingExhaustive") {
var gotCorrectValue = false
Expand Down Expand Up @@ -172,6 +184,18 @@ EnumTestSuite.test("UnexpectedOkayNested2/LyingExhaustive") {
expectTrue(gotCorrectValue)
}

EnumTestSuite.test("Equatable/LyingExhaustive") {
expectEqual(getExpectedLiarValue(), .B)
expectNotEqual(getUnexpectedLiarValue(), .B)
expectNotEqual(getExpectedLiarValue(), getUnexpectedLiarValue())
expectEqual(getUnexpectedLiarValue(), getUnexpectedLiarValue())
}

EnumTestSuite.test("Hashable/LyingExhaustive") {
expectEqual(getExpectedLiarValue().hashValue, LyingExhaustiveEnum.B.hashValue)
expectNotEqual(getUnexpectedLiarValue().hashValue, LyingExhaustiveEnum.B.hashValue)
}


@objc enum SwiftEnum : Int32 {
case A, B, C
Expand Down Expand Up @@ -264,6 +288,18 @@ EnumTestSuite.test("UnexpectedOkayNested2/SwiftExhaustive") {
expectTrue(gotCorrectValue)
}

EnumTestSuite.test("Equatable/SwiftExhaustive") {
expectEqual(SwiftEnum.getExpectedValue(), .B)
expectNotEqual(SwiftEnum.getUnexpectedValue(), .B)
expectNotEqual(SwiftEnum.getExpectedValue(), SwiftEnum.getUnexpectedValue())
expectEqual(SwiftEnum.getUnexpectedValue(), SwiftEnum.getUnexpectedValue())
}

EnumTestSuite.test("Hashable/SwiftExhaustive") {
expectEqual(SwiftEnum.getExpectedValue().hashValue, SwiftEnum.B.hashValue)
expectNotEqual(SwiftEnum.getUnexpectedValue().hashValue, SwiftEnum.B.hashValue)
}

@inline(never)
func switchOnTwoThings<T>(_ a: T, _ b: SwiftEnum) {
switch (a, b) {
Expand Down
12 changes: 8 additions & 4 deletions test/SILGen/enum_raw_representable.swift
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -enable-resilience %s | %FileCheck -check-prefix=CHECK-RESILIENT %s
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -emit-sorted-sil %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -emit-sorted-sil -enable-resilience %s | %FileCheck -check-prefix=CHECK-RESILIENT %s

public enum E: Int {
case a, b, c
}

// CHECK-DAG: sil [serialized] @$S22enum_raw_representable1EO0B5ValueACSgSi_tcfC
// CHECK-DAG: sil [serialized] @$S22enum_raw_representable1EO0B5ValueSivg
// CHECK-LABEL: sil [serialized] @$S22enum_raw_representable1EO0B5ValueACSgSi_tcfC

// CHECK-LABEL: sil [serialized] @$S22enum_raw_representable1EO0B5ValueSivg
// CHECK: switch_enum %0 : $E
// CHECK: end sil function '$S22enum_raw_representable1EO0B5ValueSivg'


// CHECK-RESILIENT-DAG: sil @$S22enum_raw_representable1EO0B5ValueACSgSi_tcfC
// CHECK-RESILIENT-DAG: sil @$S22enum_raw_representable1EO0B5ValueSivg
21 changes: 21 additions & 0 deletions test/SILGen/enum_raw_representable_objc.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -emit-sorted-sil -enable-objc-interop -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership -emit-sorted-sil -enable-objc-interop -disable-objc-attr-requires-foundation-module -enable-resilience %s | %FileCheck -check-prefix=CHECK-RESILIENT %s

@objc public enum CLike: Int {
case a, b, c
}

// CHECK-LABEL: sil [serialized] @$S27enum_raw_representable_objc5CLikeO0B5ValueACSgSi_tcfC

// CHECK-LABEL: sil [serialized] @$S27enum_raw_representable_objc5CLikeO0B5ValueSivg
// CHECK-DAG: [[RESULT_BOX:%.+]] = alloc_stack $Int
// CHECK-DAG: [[INPUT_BOX:%.+]] = alloc_stack $CLike
// CHECK: [[RAW_TYPE:%.+]] = metatype $@thick Int.Type
// CHECK: [[CAST_FUNC:%.+]] = function_ref @$Ss13unsafeBitCast_2toq_x_q_mtr0_lF
// CHECK: = apply [[CAST_FUNC]]<CLike, Int>([[RESULT_BOX]], [[INPUT_BOX]], [[RAW_TYPE]])
// CHECK: [[RESULT:%.+]] = load [trivial] [[RESULT_BOX]]
// CHECK: return [[RESULT]]
// CHECK: end sil function '$S27enum_raw_representable_objc5CLikeO0B5ValueSivg'

// CHECK-RESILIENT-DAG: sil @$S27enum_raw_representable_objc5CLikeO0B5ValueSivg
// CHECK-RESILIENT-DAG: sil @$S27enum_raw_representable_objc5CLikeO0B5ValueACSgSi_tcfC