Skip to content

Sema: Fix unavailable enum element cases in derived hashable/equatable impls #67636

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
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: 3 additions & 2 deletions lib/AST/ASTPrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5648,9 +5648,10 @@ void PrintAST::visitCaseStmt(CaseStmt *CS) {
[&] { Printer << ", "; });
}
Printer << ":";
Printer.printNewline();

printASTNodes((cast<BraceStmt>(CS->getBody())->getElements()));
if (!printASTNodes((cast<BraceStmt>(CS->getBody())->getElements())))
Printer.printNewline();
indent();
}

void PrintAST::visitFailStmt(FailStmt *stmt) {
Expand Down
2 changes: 2 additions & 0 deletions lib/Sema/DerivedConformanceComparable.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -342,5 +342,7 @@ void DerivedConformance::tryDiagnoseFailedComparableDerivation(
rawType, nominal->getDeclaredInterfaceType(),
comparableProto->getDeclaredInterfaceType());
}
// FIXME: Diagnose potentially unavailable enum elements that are preventing
// Comparable synthesis.
}
}
14 changes: 14 additions & 0 deletions lib/Sema/DerivedConformanceEquatableHashable.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,13 @@ deriveBodyEquatable_enum_hasAssociatedValues_eq(AbstractFunctionDecl *eqDecl,
for (auto elt : enumDecl->getAllElements()) {
++elementCount;

if (auto *unavailableElementCase =
DerivedConformance::unavailableEnumElementCaseStmt(
enumType, elt, eqDecl, /*subPatternCount=*/2)) {
cases.push_back(unavailableElementCase);
continue;
}

// .<elt>(let l0, let l1, ...)
SmallVector<VarDecl*, 3> lhsPayloadVars;
auto lhsSubpattern = DerivedConformance::enumElementPayloadSubpattern(elt, 'l', eqDecl,
Expand Down Expand Up @@ -692,6 +699,13 @@ deriveBodyHashable_enum_hasAssociatedValues_hashInto(
// For each enum element, generate a case statement that binds the associated
// values so that they can be fed to the hasher.
for (auto elt : enumDecl->getAllElements()) {
if (auto *unavailableElementCase =
DerivedConformance::unavailableEnumElementCaseStmt(enumType, elt,
hashIntoDecl)) {
cases.push_back(unavailableElementCase);
continue;
}

// case .<elt>(let a0, let a1, ...):
SmallVector<VarDecl*, 3> payloadVars;
SmallVector<ASTNode, 3> statements;
Expand Down
66 changes: 66 additions & 0 deletions lib/Sema/DerivedConformances.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,19 @@ DerivedConformance::createBuiltinCall(ASTContext &ctx,
return call;
}

CallExpr *DerivedConformance::createDiagnoseUnavailableCodeReachedCallExpr(
ASTContext &ctx) {
FuncDecl *diagnoseDecl = ctx.getDiagnoseUnavailableCodeReached();
auto diagnoseDeclRefExpr =
new (ctx) DeclRefExpr(diagnoseDecl, DeclNameLoc(), true);
diagnoseDeclRefExpr->setType(diagnoseDecl->getInterfaceType());
auto argList = ArgumentList::createImplicit(ctx, {});
auto callExpr = CallExpr::createImplicit(ctx, diagnoseDeclRefExpr, argList);
callExpr->setType(ctx.getNeverType());
callExpr->setThrows(false);
return callExpr;
}

AccessorDecl *DerivedConformance::
addGetterToReadOnlyDerivedProperty(VarDecl *property,
Type propertyContextType) {
Expand Down Expand Up @@ -761,6 +774,13 @@ DeclRefExpr *DerivedConformance::convertEnumToIndex(SmallVectorImpl<ASTNode> &st
unsigned index = 0;
SmallVector<ASTNode, 4> cases;
for (auto elt : enumDecl->getAllElements()) {
if (auto *unavailableElementCase =
DerivedConformance::unavailableEnumElementCaseStmt(enumType, elt,
funcDecl)) {
cases.push_back(unavailableElementCase);
continue;
}

// generate: case .<Case>:
auto pat = new (C)
EnumElementPattern(TypeExpr::createImplicit(enumType, C), SourceLoc(),
Expand Down Expand Up @@ -907,6 +927,52 @@ Pattern *DerivedConformance::enumElementPayloadSubpattern(
return ParenPattern::createImplicit(C, letPattern);
}

CaseStmt *DerivedConformance::unavailableEnumElementCaseStmt(
Type enumType, EnumElementDecl *elt, DeclContext *parentDC,
unsigned subPatternCount) {
assert(subPatternCount > 0);

ASTContext &C = parentDC->getASTContext();
auto availableAttr = elt->getAttrs().getUnavailable(C);
if (!availableAttr)
return nullptr;

if (!availableAttr->isUnconditionallyUnavailable())
return nullptr;

auto createElementPattern = [&]() -> EnumElementPattern * {
// .<elt>
EnumElementPattern *eltPattern = new (C) EnumElementPattern(
TypeExpr::createImplicit(enumType, C), SourceLoc(), DeclNameLoc(),
DeclNameRef(elt->getBaseIdentifier()), elt, nullptr, /*DC*/ parentDC);
eltPattern->setImplicit();
return eltPattern;
};

Pattern *labelItemPattern;
if (subPatternCount > 1) {
SmallVector<TuplePatternElt, 2> tuplePatternElts;
for (unsigned i = 0; i < subPatternCount; i++) {
tuplePatternElts.push_back(TuplePatternElt(createElementPattern()));
}

// (.<elt>, ..., .<elt>)
auto caseTuplePattern = TuplePattern::createImplicit(C, tuplePatternElts);
caseTuplePattern->setImplicit();
labelItemPattern = caseTuplePattern;
} else {
labelItemPattern = createElementPattern();
}

auto labelItem = CaseLabelItem(labelItemPattern);
auto *callExpr =
DerivedConformance::createDiagnoseUnavailableCodeReachedCallExpr(C);
auto body = BraceStmt::create(C, SourceLoc(), {callExpr}, SourceLoc());
return CaseStmt::create(C, CaseParentKind::Switch, SourceLoc(), labelItem,
SourceLoc(), SourceLoc(), body, {},
/*implicit*/ true);
}

/// Creates a named variable based on a prefix character and a numeric index.
/// \p prefixChar The prefix character for the variable's name.
/// \p index The numeric index to append to the variable's name.
Expand Down
16 changes: 16 additions & 0 deletions lib/Sema/DerivedConformances.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ class AssociatedTypeDecl;
class ASTContext;
struct ASTNode;
class CallExpr;
class CaseStmt;
class Decl;
class DeclContext;
class DeclRefExpr;
Expand Down Expand Up @@ -389,6 +390,11 @@ class DerivedConformance {
ArrayRef<ProtocolConformanceRef> conformances,
ArrayRef<Expr *> args);

/// Build a call to the stdlib function that should be called when unavailable
/// code is reached unexpectedly.
static CallExpr *
createDiagnoseUnavailableCodeReachedCallExpr(ASTContext &ctx);

/// Returns true if this derivation is trying to use a context that isn't
/// appropriate for deriving.
///
Expand Down Expand Up @@ -453,6 +459,16 @@ class DerivedConformance {
EnumElementDecl *enumElementDecl, char varPrefix, DeclContext *varContext,
SmallVectorImpl<VarDecl *> &boundVars, bool useLabels = false);

/// Creates a synthesized case statement that has the following structure:
///
/// case .<elt>, ..., .<elt>:
/// _diagnoseUnavailableCodeReached()
///
/// The number of \c .<elt> matches is equal to \p subPatternCount.
static CaseStmt *unavailableEnumElementCaseStmt(
Type enumType, EnumElementDecl *enumElementDecl, DeclContext *parentDC,
unsigned subPatternCount = 1);

static VarDecl *indexedVarDecl(char prefixChar, int index, Type type,
DeclContext *varContext);
};
Expand Down
4 changes: 2 additions & 2 deletions lib/Sema/TypeCheckSwitchStmt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -828,8 +828,8 @@ namespace {
auto children = E->getAllElements();
llvm::transform(
children, std::back_inserter(arr), [&](EnumElementDecl *eed) {
// Don't force people to match unavailable cases; they can't
// even write them.
// Don't force people to match unavailable cases since they
// should not be instantiated at run time.
if (AvailableAttr::isUnavailable(eed)) {
return Space();
}
Expand Down
22 changes: 22 additions & 0 deletions test/Interpreter/enum_equatable_hashable_correctness.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// RUN: %target-run-simple-swift
// RUN: %target-run-simple-swift(-Xfrontend -unavailable-decl-optimization=complete)
// REQUIRES: executable_test

import StdlibUnittest
Expand All @@ -17,6 +18,20 @@ enum Combo<T: Hashable, U: Hashable>: Hashable {
case both(T, U)
}

@available(*, unavailable)
struct UnavailableStruct: Hashable {}

enum HasUnavailableCases: Hashable {
case available
case availablePayload(Int)

@available(*, unavailable)
case unavailable

@available(*, unavailable)
case unavailablePayload(UnavailableStruct)
}

var EnumSynthesisTests = TestSuite("EnumSynthesis")

EnumSynthesisTests.test("BasicEquatability/Hashability") {
Expand Down Expand Up @@ -52,6 +67,13 @@ EnumSynthesisTests.test("CloseGenericValuesDoNotCollide") {
expectNotEqual(Combo<String, Int>.both("foo", 3).hashValue, Combo<String, Int>.both("goo", 4).hashValue)
}

EnumSynthesisTests.test("HasUnavailableCasesEquatability/Hashability") {
checkHashable([
HasUnavailableCases.available,
HasUnavailableCases.availablePayload(2),
], equalityOracle: { $0 == $1 })
}

func hashEncode(_ body: (inout Hasher) -> ()) -> Int {
var hasher = Hasher()
body(&hasher)
Expand Down
Loading