Skip to content

[CodeSynthesis] Improve synthesized Decodable.init(from:) for enums #41674

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 1 commit into from
Mar 11, 2022
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
3 changes: 2 additions & 1 deletion include/swift/AST/KnownIdentifiers.def
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ IDENTIFIER(keyPath)
IDENTIFIER(makeIterator)
IDENTIFIER(makeAsyncIterator)
IDENTIFIER(nestedContainer)
IDENTIFIER(isEmpty)
IDENTIFIER(Iterator)
IDENTIFIER(AsyncIterator)
IDENTIFIER(load)
Expand All @@ -124,6 +125,7 @@ IDENTIFIER(oldValue)
IDENTIFIER(Optional)
IDENTIFIER_(OptionalNilComparisonType)
IDENTIFIER(parameter)
IDENTIFIER(popFirst)
IDENTIFIER(projected)
IDENTIFIER(projectedValue)
IDENTIFIER(Protocol)
Expand All @@ -149,7 +151,6 @@ IDENTIFIER(Type)
IDENTIFIER(type)
IDENTIFIER(typeMismatch)
IDENTIFIER(underlyingError)
IDENTIFIER(unsafelyUnwrapped)
IDENTIFIER(Value)
IDENTIFIER(value)
IDENTIFIER_WITH_NAME(value_, "_value")
Expand Down
1 change: 1 addition & 0 deletions include/swift/AST/KnownStdlibTypes.def
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ KNOWN_STDLIB_TYPE_DECL(String, NominalTypeDecl, 0)
KNOWN_STDLIB_TYPE_DECL(StaticString, NominalTypeDecl, 0)
KNOWN_STDLIB_TYPE_DECL(Substring, NominalTypeDecl, 0)
KNOWN_STDLIB_TYPE_DECL(Array, NominalTypeDecl, 1)
KNOWN_STDLIB_TYPE_DECL(ArraySlice, NominalTypeDecl, 1)
KNOWN_STDLIB_TYPE_DECL(_ContiguousArrayStorage, ClassDecl, 1)
KNOWN_STDLIB_TYPE_DECL(Set, NominalTypeDecl, 1)
KNOWN_STDLIB_TYPE_DECL(Sequence, NominalTypeDecl, 1)
Expand Down
30 changes: 16 additions & 14 deletions lib/AST/ASTPrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4917,20 +4917,22 @@ void PrintAST::visitRepeatWhileStmt(RepeatWhileStmt *stmt) {
visit(stmt->getCond());
}

void PrintAST::printStmtCondition(StmtCondition stmt) {
for (auto elt : stmt) {
if (auto pattern = elt.getPatternOrNull()) {
printPattern(pattern);
auto initializer = elt.getInitializer();
if (initializer) {
Printer << " = ";
visit(initializer);
}
}
else if (auto boolean = elt.getBooleanOrNull()) {
visit(boolean);
}
}
void PrintAST::printStmtCondition(StmtCondition condition) {
interleave(
condition,
[&](StmtConditionElement &elt) {
if (auto pattern = elt.getPatternOrNull()) {
printPattern(pattern);
auto initializer = elt.getInitializer();
if (initializer) {
Printer << " = ";
visit(initializer);
}
} else if (auto boolean = elt.getBooleanOrNull()) {
visit(boolean);
}
},
[&] { Printer << ", "; });
}

void PrintAST::visitDoStmt(DoStmt *stmt) {
Expand Down
98 changes: 64 additions & 34 deletions lib/Sema/DerivedConformanceCodable.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1552,13 +1552,14 @@ deriveBodyDecodable_enum_init(AbstractFunctionDecl *initDecl, void *) {
//
// @derived init(from decoder: Decoder) throws {
// let container = try decoder.container(keyedBy: CodingKeys.self)
// if container.allKeys.count != 1 {
// var allKeys = ArraySlice(container.allKeys)
// guard let onlyKey = allKeys.popFirst(), allKeys.isEmpty else {
// let context = DecodingError.Context(
// codingPath: container.codingPath,
// debugDescription: "Invalid number of keys found, expected one.")
// throw DecodingError.typeMismatch(Foo.self, context)
// }
// switch container.allKeys.first {
// switch onlyKey {
// case .bar:
// let nestedContainer = try container.nestedContainer(
// keyedBy: BarCodingKeys.self, forKey: .bar)
Expand Down Expand Up @@ -1597,15 +1598,67 @@ deriveBodyDecodable_enum_init(AbstractFunctionDecl *initDecl, void *) {
initDecl->getParameters()->get(0), codingKeysEnum, statements,
/*throws*/ true);

// generate: var allKeys = ArraySlice(container.allKeys);
auto *allKeysDecl =
new (C) VarDecl(/*IsStatic=*/false, VarDecl::Introducer::Var,
SourceLoc(), C.Id_allKeys, funcDC);
allKeysDecl->setImplicit();
allKeysDecl->setSynthesized();
{
auto *arraySliceRef =
new (C) DeclRefExpr(ConcreteDeclRef(C.getArraySliceDecl()),
DeclNameLoc(), /*Implicit=*/true);
auto *containerAllKeys =
UnresolvedDotExpr::createImplicit(C, containerExpr, C.Id_allKeys);
auto *argList = ArgumentList::createImplicit(
C, {Argument::unlabeled(containerAllKeys)});
auto *init = CallExpr::createImplicit(C, arraySliceRef, argList);

auto *allKeysPattern = NamedPattern::createImplicit(C, allKeysDecl);
auto *allKeysBindingDecl = PatternBindingDecl::createImplicit(
C, StaticSpellingKind::None, allKeysPattern, init, funcDC);

statements.push_back(allKeysBindingDecl);
statements.push_back(allKeysDecl);
}

// generate:
//
// if container.allKeys.count != 1 {
// guard let onlyKey = allKeys.popFirst(), allKeys.isEmpty else {
// let context = DecodingError.Context(
// codingPath: container.codingPath,
// debugDescription: "Invalid number of keys found, expected
// one.")
// throw DecodingError.typeMismatch(Foo.self, context)
// }
auto *theKeyDecl =
new (C) VarDecl(/*IsStatic=*/false, VarDecl::Introducer::Let,
SourceLoc(), C.getIdentifier("onlyKey"), funcDC);
theKeyDecl->setImplicit();
theKeyDecl->setSynthesized();

SmallVector<StmtConditionElement, 2> guardElements;
{
auto *allKeysExpr =
new (C) DeclRefExpr(ConcreteDeclRef(allKeysDecl), DeclNameLoc(),
/*Implicit=*/true);

// generate: let onlyKey = allKeys.popFirst;
auto *allKeysPopFisrtCallExpr = CallExpr::createImplicitEmpty(
C, UnresolvedDotExpr::createImplicit(C, allKeysExpr, C.Id_popFirst));

auto *theKeyPattern = BindingPattern::createImplicit(
C, /*isLet=*/true, NamedPattern::createImplicit(C, theKeyDecl));

guardElements.emplace_back(SourceLoc(), theKeyPattern,
allKeysPopFisrtCallExpr);

// generate: allKeys.isEmpty;
auto *allKeysIsEmptyExpr =
UnresolvedDotExpr::createImplicit(C, allKeysExpr, C.Id_isEmpty);

guardElements.emplace_back(allKeysIsEmptyExpr);
}

auto *targetType = TypeExpr::createImplicit(
funcDC->mapTypeIntoContext(targetEnum->getDeclaredInterfaceType()), C);
auto *targetTypeExpr =
Expand All @@ -1615,44 +1668,21 @@ deriveBodyDecodable_enum_init(AbstractFunctionDecl *initDecl, void *) {
C, containerExpr, C.getDecodingErrorDecl(), C.Id_typeMismatch,
targetTypeExpr, "Invalid number of keys found, expected one.");

// container.allKeys
auto *allKeysExpr =
UnresolvedDotExpr::createImplicit(C, containerExpr, C.Id_allKeys);

// container.allKeys.count
auto *keysCountExpr =
UnresolvedDotExpr::createImplicit(C, allKeysExpr, C.Id_count);

// container.allKeys.count == 1
auto *cmpFunc = C.getEqualIntDecl();
auto *fnType = cmpFunc->getInterfaceType()->castTo<FunctionType>();
auto *cmpFuncExpr = new (C)
DeclRefExpr(cmpFunc, DeclNameLoc(),
/*implicit*/ true, AccessSemantics::Ordinary, fnType);
auto *oneExpr = IntegerLiteralExpr::createFromUnsigned(C, 1);

auto *cmpExpr = BinaryExpr::create(C, keysCountExpr, cmpFuncExpr, oneExpr,
/*implicit*/ true);
cmpExpr->setThrows(false);

auto *guardBody = BraceStmt::create(C, SourceLoc(), {throwStmt},
SourceLoc(), /* Implicit */ true);

auto *guardStmt = new (C)
GuardStmt(SourceLoc(), cmpExpr, guardBody, /* Implicit */ true, C);
auto *guardStmt =
new (C) GuardStmt(SourceLoc(), C.AllocateCopy(guardElements), guardBody,
/* Implicit */ true);

statements.push_back(guardStmt);

// generate: switch container.allKeys.first { }
auto *firstExpr =
UnresolvedDotExpr::createImplicit(C, allKeysExpr, C.Id_first);

// generate: switch container.allKeys.first.unsafelyUnwrapped { }
auto *unwrapped =
UnresolvedDotExpr::createImplicit(C, firstExpr, C.Id_unsafelyUnwrapped);
// generate: switch onlyKey { }
auto *theKeyExpr = new (C) DeclRefExpr(ConcreteDeclRef(theKeyDecl),
DeclNameLoc(), /*Implicit=*/true);

auto switchStmt = createEnumSwitch(
C, funcDC, unwrapped, targetEnum, codingKeysEnum,
C, funcDC, theKeyExpr, targetEnum, codingKeysEnum,
/*createSubpattern*/ false,
[&](auto *elt, auto *codingKeyCase,
auto payloadVars) -> std::tuple<EnumElementDecl *, BraceStmt *> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,12 @@ enum Payload: Codable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Payload.CodingKeys.self)

guard container.allKeys.count == 1 else {
var allKeys = ArraySlice(container.allKeys)

guard let onlyKey = allKeys.popFirst(), allKeys.isEmpty else {
Copy link
Contributor

@louisdh louisdh Mar 5, 2022

Choose a reason for hiding this comment

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

Perfect!

I was confused at first seeing allKeys.isEmpty. Then I realized it's mutating allKeys with the popFirst() (I initially just read it as accessing the first key, not removing it from the array).

Seems like a much more efficient (and safe) way for checking that's there's only 1 key. 😃

throw DecodingError.typeMismatch(Payload.self, DecodingError.Context.init(codingPath: container.codingPath, debugDescription: "Invalid number of keys found, expected one.", underlyingError: nil))
}
switch container.allKeys.first.unsafelyUnwrapped {
switch onlyKey {
case .plain:

let nestedContainer = try container.nestedContainer(keyedBy: Payload.PlainCodingKeys.self, forKey: Payload.CodingKeys.plain)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,12 @@ enum Payload_D: Decodable {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: Payload_D.CodingKeys.self)

guard container.allKeys.count == 1 else {
var allKeys = ArraySlice(container.allKeys)

guard let onlyKey = allKeys.popFirst(), allKeys.isEmpty else {
throw DecodingError.typeMismatch(Payload_D.self, DecodingError.Context.init(codingPath: container.codingPath, debugDescription: "Invalid number of keys found, expected one.", underlyingError: nil))
}
switch container.allKeys.first.unsafelyUnwrapped {
switch onlyKey {
case .plain:

let nestedContainer = try container.nestedContainer(keyedBy: Payload_D.PlainCodingKeys.self, forKey: Payload_D.CodingKeys.plain)
Expand Down