CoreOffice / XMLCoder

Easy XML parsing using Codable protocols in Swift
https://coreoffice.github.io/XMLCoder/
MIT License
801 stars 112 forks source link

Decoding choice elements that can hold empty structs #120

Closed bwetherfield closed 5 years ago

bwetherfield commented 5 years ago

Introduction

In merging in #119, we fixed most but not quite all of #91! Decoding of null choice elements (represented as enums with empty struct associated values on the Swift side) still results in errors. This PR adds a test to demonstrate and fixes this issue by wrapping each NullBox inside of a SingleKeyedBox at the merge phase (called by transformToBoxTree).

Motivation

One of the main lessons from #119 was that we have to wrap choice elements in the decoding phase to hold onto their keys. The keys are needed for directing us to the correct branch of the do-catch pyramid used for decoding.

private enum Entry: Equatable {
    case run(Run)
    case properties(Properties)
    case br(Break)
}

extension Entry: Decodable {
    private enum CodingKeys: String, XMLChoiceCodingKey {
        case run, properties, br
    }

    public init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        do {
            self = .run(try container.decode(Run.self, forKey: .run))
        } catch {
            do {
                self = .properties(try container.decode(Properties.self, forKey: .properties))
            } catch {
                self = .br(try container.decode(Break.self, forKey: .br))
            }
        }
    }
}

where one of the associated values could be an empty struct (represented by null):

private struct Break: Decodable {}

Although we can throw out keys for non-choice null elements, a mechanism is needed for holding onto the keys while transforming from the XMLCoderElement tree to the boxTree. Only later will we know if the key is needed (if this wrapped element is transformed to a ChoiceBox); if not, we will be able to throw out the key.

Proposed solution

The Public API is unchanged. On the implementation side, we catch NullBox values in merge and wrap them in SingleKeyedBox instances.

Detailed Design

In merge, we wrap each NullBox in a SingleKeyedBox with the appropriate key bundled in. An XMLChoiceDecodingContainer can be constructed from the SingleKeyedBox by converting it to a ChoiceBox (just transferring over the contents) - as normal. In XMLKeyedDecodingContainer, when preparing the elements for concrete decoding, we unwrap all SingleKeyedBox values that may be contained therein, as any choice elements contained would have already been transformed to a ChoiceBox by this point in decoding: any stray SingleKeyedBox wrappers can thus be thrown out.

Source compatibility

This is purely an additive change.

bwetherfield commented 5 years ago

So quick! Thank you, @MaxDesiatov