From f80d7460ea7b0547d91175a8c5266035972abc41 Mon Sep 17 00:00:00 2001 From: Mihaela Mihaljevic Date: Fri, 5 Jun 2026 12:11:53 +0200 Subject: [PATCH] feat(coding): add keyed typed conversion --- CHANGELOG.md | 3 + README.md | 21 +- Sources/API.swift | 3 +- Sources/Decoding/Decoding.Decoder.swift | 56 ++- Sources/Decoding/Decoding.Error.swift | 6 + .../Decoding/Decoding.KeyedContainer.swift | 153 +++++++ Sources/Encoding/Encoding.Encoder.swift | 250 ++++-------- .../Encoding/Encoding.KeyedContainer.swift | 164 ++++++++ ...Encoding.UnsupportedUnkeyedContainer.swift | 123 ++++++ Tests/CodingTests.swift | 34 +- Tests/KeyedCodingTests.swift | 376 ++++++++++++++++++ docs/DESIGN.md | 15 +- 12 files changed, 992 insertions(+), 212 deletions(-) create mode 100644 Sources/Decoding/Decoding.KeyedContainer.swift create mode 100644 Sources/Encoding/Encoding.KeyedContainer.swift create mode 100644 Sources/Encoding/Encoding.UnsupportedUnkeyedContainer.swift create mode 100644 Tests/KeyedCodingTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ed4ee0..e7b5a26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -51,6 +51,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Add scalar typed Decodable and Encodable conversion APIs with exact path-aware errors. - Add unambiguous bracket-quoted validation paths for punctuation-heavy keys. +- Add keyed typed Decodable and Encodable conversion for mapping-backed structs. +- Validate YAML values before typed decoding so duplicate keys are rejected + deterministically. ### Changed diff --git a/README.md b/README.md index 4011985..bc4ccce 100644 --- a/README.md +++ b/README.md @@ -101,15 +101,30 @@ let yaml = PureYAML.dump(document) try PureYAML.validate(document) ``` -Typed scalar conversion is available for the first Decodable and Encodable -slice: +Typed conversion is available for scalar values and keyed mapping-backed +structs: ```swift +struct Info: Codable { + var title: String + var version: Int +} + let title = try PureYAML.decode(String.self, from: "Example") +let info = try PureYAML.decode(Info.self, from: """ +title: Example API +version: 1 +""") let value = try PureYAML.encode(42) -let yaml = try PureYAML.encodeToYAML(true) +let yaml = try PureYAML.encodeToYAML(info) ``` +Unkeyed sequences are still explicit future work; attempts to decode or encode +arrays through typed conversion report exact path-aware errors. +Typed decoding runs the default validator before constructing Swift values, so +duplicate mapping keys are reported as validation issues instead of silently +choosing one value. + Emitter options are explicit. The default is deterministic block-style output with quoted strings. Callers can opt into conservative plain strings, safe literal block scalars for multiline strings, and compact flow collections: diff --git a/Sources/API.swift b/Sources/API.swift index 55abe9c..b3918a7 100644 --- a/Sources/API.swift +++ b/Sources/API.swift @@ -27,7 +27,8 @@ public extension PureYAML { _: Value.Type = Value.self, from value: Model.Value, ) throws -> Value { - try Value(from: Decoding.Decoder(value: value)) + try validate(value) + return try Value(from: Decoding.Decoder(value: value, validatesInput: false)) } /// Parses YAML and decodes a typed value from the resulting value tree. diff --git a/Sources/Decoding/Decoding.Decoder.swift b/Sources/Decoding/Decoding.Decoder.swift index a748a85..d484a40 100644 --- a/Sources/Decoding/Decoding.Decoder.swift +++ b/Sources/Decoding/Decoding.Decoder.swift @@ -1,30 +1,45 @@ public extension PureYAML.Decoding { - /// Scalar typed decoder backed by a ``PureYAML/Model/Value``. + /// Typed decoder backed by a ``PureYAML/Model/Value``. struct Decoder: Swift.Decoder { public let value: PureYAML.Model.Value public let codingPath: [any CodingKey] public let userInfo: [CodingUserInfoKey: Any] + let validatesInput: Bool public init( value: PureYAML.Model.Value, codingPath: [any CodingKey] = [], userInfo: [CodingUserInfoKey: Any] = [:], + validatesInput: Bool = true, ) { self.value = value self.codingPath = codingPath self.userInfo = userInfo + self.validatesInput = validatesInput } public func container( keyedBy _: Key.Type, ) throws -> KeyedDecodingContainer { - throw Error.unsupportedContainer( - kind: "keyed", - path: PureYAML.Validation.Path(codingPath: codingPath), - ) + try validateIfNeeded() + guard case let .mapping(mapping) = value else { + throw Error.typeMismatch( + expected: "mapping", + actual: value.kindDescription, + path: PureYAML.Validation.Path(codingPath: codingPath), + ) + } + + return KeyedDecodingContainer(KeyedDecodingContainerImpl( + mapping: mapping, + codingPath: codingPath, + userInfo: userInfo, + validatesInput: validatesInput, + )) } public func unkeyedContainer() throws -> any UnkeyedDecodingContainer { + try validateIfNeeded() throw Error.unsupportedContainer( kind: "unkeyed", path: PureYAML.Validation.Path(codingPath: codingPath), @@ -32,12 +47,41 @@ public extension PureYAML.Decoding { } public func singleValueContainer() throws -> any SingleValueDecodingContainer { - SingleValueContainer( + try validateIfNeeded() + return SingleValueContainer( value: value, codingPath: codingPath, userInfo: userInfo, ) } + + private func validateIfNeeded() throws { + if validatesInput { + try PureYAML.Decoding.validate(value, codingPath: codingPath) + } + } + } +} + +extension PureYAML.Decoding { + static func validate( + _ value: PureYAML.Model.Value, + codingPath: [any CodingKey], + ) throws { + let result = PureYAML.Validation.Validator().collect(value) + guard !result.issues.isEmpty else { + return + } + + let pathPrefix = PureYAML.Validation.Path(codingPath: codingPath) + let issues = result.issues.map { issue in + PureYAML.Validation.Issue( + severity: issue.severity, + reason: issue.reason, + path: .init(pathPrefix.components + issue.path.components), + ) + } + throw PureYAML.Validation.Issue.Collection(issues) } } diff --git a/Sources/Decoding/Decoding.Error.swift b/Sources/Decoding/Decoding.Error.swift index 3ac5a15..4f79d40 100644 --- a/Sources/Decoding/Decoding.Error.swift +++ b/Sources/Decoding/Decoding.Error.swift @@ -10,6 +10,10 @@ public extension PureYAML.Decoding { type: String, path: PureYAML.Validation.Path, ) + case keyNotFound( + key: String, + path: PureYAML.Validation.Path, + ) case unsupportedContainer( kind: String, path: PureYAML.Validation.Path, @@ -21,6 +25,8 @@ public extension PureYAML.Decoding { "Expected \(expected) at \(path), found \(actual)" case let .integerOutOfRange(type, path): "\(type) value is outside PureYAML integer range at \(path)" + case let .keyNotFound(key, path): + "Missing required key '\(key)' at \(path)" case let .unsupportedContainer(kind, path): "Unsupported \(kind) decoding container at \(path)" } diff --git a/Sources/Decoding/Decoding.KeyedContainer.swift b/Sources/Decoding/Decoding.KeyedContainer.swift new file mode 100644 index 0000000..7eb1e9a --- /dev/null +++ b/Sources/Decoding/Decoding.KeyedContainer.swift @@ -0,0 +1,153 @@ +struct KeyedDecodingContainerImpl: KeyedDecodingContainerProtocol { + let mapping: PureYAML.Model.Mapping + let codingPath: [any CodingKey] + let userInfo: [CodingUserInfoKey: Any] + let validatesInput: Bool + + var allKeys: [Key] { + mapping.pairs.compactMap { Key(stringValue: $0.key) } + } + + func contains(_ key: Key) -> Bool { + mapping[key.stringValue] != nil + } + + func decodeNil(forKey key: Key) throws -> Bool { + try value(for: key) == .null + } + + func decode(_: Bool.Type, forKey key: Key) throws -> Bool { + try singleValue(for: key).decode(Bool.self) + } + + func decode(_: String.Type, forKey key: Key) throws -> String { + try singleValue(for: key).decode(String.self) + } + + func decode(_: Double.Type, forKey key: Key) throws -> Double { + try singleValue(for: key).decode(Double.self) + } + + func decode(_: Float.Type, forKey key: Key) throws -> Float { + try singleValue(for: key).decode(Float.self) + } + + func decode(_: Int.Type, forKey key: Key) throws -> Int { + try singleValue(for: key).decode(Int.self) + } + + func decode(_: Int8.Type, forKey key: Key) throws -> Int8 { + try singleValue(for: key).decode(Int8.self) + } + + func decode(_: Int16.Type, forKey key: Key) throws -> Int16 { + try singleValue(for: key).decode(Int16.self) + } + + func decode(_: Int32.Type, forKey key: Key) throws -> Int32 { + try singleValue(for: key).decode(Int32.self) + } + + func decode(_: Int64.Type, forKey key: Key) throws -> Int64 { + try singleValue(for: key).decode(Int64.self) + } + + func decode(_: UInt.Type, forKey key: Key) throws -> UInt { + try singleValue(for: key).decode(UInt.self) + } + + func decode(_: UInt8.Type, forKey key: Key) throws -> UInt8 { + try singleValue(for: key).decode(UInt8.self) + } + + func decode(_: UInt16.Type, forKey key: Key) throws -> UInt16 { + try singleValue(for: key).decode(UInt16.self) + } + + func decode(_: UInt32.Type, forKey key: Key) throws -> UInt32 { + try singleValue(for: key).decode(UInt32.self) + } + + func decode(_: UInt64.Type, forKey key: Key) throws -> UInt64 { + try singleValue(for: key).decode(UInt64.self) + } + + func decode(_: Value.Type, forKey key: Key) throws -> Value { + try Value(from: decoder(for: key)) + } + + func nestedContainer( + keyedBy _: NestedKey.Type, + forKey key: Key, + ) throws -> KeyedDecodingContainer { + let value = try value(for: key) + guard case let .mapping(mapping) = value else { + throw PureYAML.Decoding.Error.typeMismatch( + expected: "mapping", + actual: value.kindDescription, + path: PureYAML.Validation.Path(codingPath: codingPath + [key]), + ) + } + + return KeyedDecodingContainer(KeyedDecodingContainerImpl( + mapping: mapping, + codingPath: codingPath + [key], + userInfo: userInfo, + validatesInput: validatesInput, + )) + } + + func nestedUnkeyedContainer(forKey key: Key) throws -> any UnkeyedDecodingContainer { + let value = try value(for: key) + try validateIfNeeded(value, forKey: key) + throw PureYAML.Decoding.Error.unsupportedContainer( + kind: "unkeyed", + path: PureYAML.Validation.Path(codingPath: codingPath + [key]), + ) + } + + func superDecoder() throws -> any Swift.Decoder { + PureYAML.Decoding.Decoder( + value: .mapping(mapping), + codingPath: codingPath, + userInfo: userInfo, + validatesInput: validatesInput, + ) + } + + func superDecoder(forKey key: Key) throws -> any Swift.Decoder { + try decoder(for: key) + } + + private func singleValue(for key: Key) throws -> any SingleValueDecodingContainer { + try decoder(for: key).singleValueContainer() + } + + private func decoder(for key: Key) throws -> PureYAML.Decoding.Decoder { + try PureYAML.Decoding.Decoder( + value: value(for: key), + codingPath: codingPath + [key], + userInfo: userInfo, + validatesInput: validatesInput, + ) + } + + private func value(for key: Key) throws -> PureYAML.Model.Value { + guard let value = mapping[key.stringValue] else { + throw PureYAML.Decoding.Error.keyNotFound( + key: key.stringValue, + path: PureYAML.Validation.Path(codingPath: codingPath + [key]), + ) + } + return value + } + + private func validateIfNeeded( + _ value: PureYAML.Model.Value, + forKey key: Key, + ) throws { + if validatesInput { + try PureYAML.Decoding.validate(value, codingPath: codingPath + [key]) + } + } +} diff --git a/Sources/Encoding/Encoding.Encoder.swift b/Sources/Encoding/Encoding.Encoder.swift index 0ad2f36..08b9209 100644 --- a/Sources/Encoding/Encoding.Encoder.swift +++ b/Sources/Encoding/Encoding.Encoder.swift @@ -1,5 +1,5 @@ public extension PureYAML.Encoding { - /// Scalar typed encoder that writes a ``PureYAML/Model/Value``. + /// Typed encoder that writes a ``PureYAML/Model/Value``. final class Encoder: Swift.Encoder { public let codingPath: [any CodingKey] public let userInfo: [CodingUserInfoKey: Any] @@ -15,7 +15,7 @@ public extension PureYAML.Encoding { storage = Storage() } - fileprivate init( + init( codingPath: [any CodingKey], userInfo: [CodingUserInfoKey: Any], storage: Storage, @@ -41,131 +41,163 @@ public extension PureYAML.Encoding { public func container( keyedBy _: Key.Type, ) -> KeyedEncodingContainer { - storage.error = .unsupportedContainer( - kind: "keyed", - path: PureYAML.Validation.Path(codingPath: codingPath), - ) - return KeyedEncodingContainer(UnsupportedKeyedEncodingContainer( + storage.set(.mapping(.init())) + return KeyedEncodingContainer(KeyedEncodingContainerImpl( + storage: storage, codingPath: codingPath, + userInfo: userInfo, )) } public func unkeyedContainer() -> any UnkeyedEncodingContainer { - storage.error = .unsupportedContainer( + storage.fail(.unsupportedContainer( kind: "unkeyed", path: PureYAML.Validation.Path(codingPath: codingPath), + )) + return UnsupportedUnkeyedEncodingContainer( + codingPath: codingPath, + userInfo: userInfo, ) - return UnsupportedUnkeyedEncodingContainer(codingPath: codingPath) } public func singleValueContainer() -> any SingleValueEncodingContainer { - SingleValueContainer(storage: storage, codingPath: codingPath) + SingleValueContainer( + storage: storage, + codingPath: codingPath, + userInfo: userInfo, + ) } } } -private extension PureYAML.Encoding.Encoder { +extension PureYAML.Encoding.Encoder { final class Storage { var value: PureYAML.Model.Value? var error: PureYAML.Encoding.Error? + private let parent: Storage? + private let parentKey: String? + + init( + parent: Storage? = nil, + parentKey: String? = nil, + ) { + self.parent = parent + self.parentKey = parentKey + } + + func set(_ value: PureYAML.Model.Value) { + self.value = value + if let parent, let parentKey { + parent.set(value, forKey: parentKey) + } + } + + func set( + _ value: PureYAML.Model.Value, + forKey key: String, + ) { + var mapping: PureYAML.Model.Mapping = if case let .mapping(existing) = self.value { + existing + } else { + .init() + } + + if let index = mapping.pairs.firstIndex(where: { $0.key == key }) { + mapping.pairs[index] = .init(key: key, value: value) + } else { + mapping.pairs.append(.init(key: key, value: value)) + } + set(.mapping(mapping)) + } + + func fail(_ error: PureYAML.Encoding.Error) { + self.error = error + parent?.fail(error) + } } } private struct SingleValueContainer: SingleValueEncodingContainer { let storage: PureYAML.Encoding.Encoder.Storage let codingPath: [any CodingKey] + let userInfo: [CodingUserInfoKey: Any] mutating func encodeNil() throws { - storage.error = nil - storage.value = .null + storage.set(.null) } mutating func encode(_ value: Bool) throws { - storage.error = nil - storage.value = .bool(value) + storage.set(.bool(value)) } mutating func encode(_ value: String) throws { - storage.error = nil - storage.value = .string(value) + storage.set(.string(value)) } mutating func encode(_ value: Double) throws { - storage.error = nil - storage.value = .double(value) + storage.set(.double(value)) } mutating func encode(_ value: Float) throws { - storage.error = nil - storage.value = .double(Double(value)) + storage.set(.double(Double(value))) } mutating func encode(_ value: Int) throws { - storage.error = nil - storage.value = .int(value) + storage.set(.int(value)) } mutating func encode(_ value: Int8) throws { - storage.error = nil - storage.value = .int(Int(value)) + storage.set(.int(Int(value))) } mutating func encode(_ value: Int16) throws { - storage.error = nil - storage.value = .int(Int(value)) + storage.set(.int(Int(value))) } mutating func encode(_ value: Int32) throws { - storage.error = nil - storage.value = .int(Int(value)) + storage.set(.int(Int(value))) } mutating func encode(_ value: Int64) throws { guard let value = Int(exactly: value) else { throw unsupportedInteger("Int64") } - storage.error = nil - storage.value = .int(value) + storage.set(.int(value)) } mutating func encode(_ value: UInt) throws { guard let value = Int(exactly: value) else { throw unsupportedInteger("UInt") } - storage.error = nil - storage.value = .int(value) + storage.set(.int(value)) } mutating func encode(_ value: UInt8) throws { - storage.error = nil - storage.value = .int(Int(value)) + storage.set(.int(Int(value))) } mutating func encode(_ value: UInt16) throws { - storage.error = nil - storage.value = .int(Int(value)) + storage.set(.int(Int(value))) } mutating func encode(_ value: UInt32) throws { guard let value = Int(exactly: value) else { throw unsupportedInteger("UInt32") } - storage.error = nil - storage.value = .int(value) + storage.set(.int(value)) } mutating func encode(_ value: UInt64) throws { guard let value = Int(exactly: value) else { throw unsupportedInteger("UInt64") } - storage.error = nil - storage.value = .int(value) + storage.set(.int(value)) } mutating func encode(_ value: some Encodable) throws { try value.encode(to: PureYAML.Encoding.Encoder( codingPath: codingPath, - userInfo: [:], + userInfo: userInfo, storage: storage, )) } @@ -178,8 +210,9 @@ private struct SingleValueContainer: SingleValueEncodingContainer { } } -private struct UnsupportedKeyedEncodingContainer: KeyedEncodingContainerProtocol { +struct UnsupportedKeyedEncodingContainer: KeyedEncodingContainerProtocol { var codingPath: [any CodingKey] + var userInfo: [CodingUserInfoKey: Any] = [:] mutating func encodeNil(forKey key: Key) throws { throw unsupported(key) @@ -251,19 +284,23 @@ private struct UnsupportedKeyedEncodingContainer: KeyedEncodingC ) -> KeyedEncodingContainer { KeyedEncodingContainer(UnsupportedKeyedEncodingContainer( codingPath: codingPath + [key], + userInfo: userInfo, )) } mutating func nestedUnkeyedContainer(forKey key: Key) -> any UnkeyedEncodingContainer { - UnsupportedUnkeyedEncodingContainer(codingPath: codingPath + [key]) + UnsupportedUnkeyedEncodingContainer( + codingPath: codingPath + [key], + userInfo: userInfo, + ) } mutating func superEncoder() -> any Swift.Encoder { - PureYAML.Encoding.Encoder(codingPath: codingPath, userInfo: [:]) + PureYAML.Encoding.Encoder(codingPath: codingPath, userInfo: userInfo) } mutating func superEncoder(forKey key: Key) -> any Swift.Encoder { - PureYAML.Encoding.Encoder(codingPath: codingPath + [key], userInfo: [:]) + PureYAML.Encoding.Encoder(codingPath: codingPath + [key], userInfo: userInfo) } private func unsupported(_ key: Key) -> PureYAML.Encoding.Error { @@ -273,124 +310,3 @@ private struct UnsupportedKeyedEncodingContainer: KeyedEncodingC ) } } - -private struct UnsupportedUnkeyedEncodingContainer: UnkeyedEncodingContainer { - var codingPath: [any CodingKey] - var count: Int { - 0 - } - - mutating func encodeNil() throws { - throw unsupported() - } - - mutating func encode(_: Bool) throws { - throw unsupported() - } - - mutating func encode(_: String) throws { - throw unsupported() - } - - mutating func encode(_: Double) throws { - throw unsupported() - } - - mutating func encode(_: Float) throws { - throw unsupported() - } - - mutating func encode(_: Int) throws { - throw unsupported() - } - - mutating func encode(_: Int8) throws { - throw unsupported() - } - - mutating func encode(_: Int16) throws { - throw unsupported() - } - - mutating func encode(_: Int32) throws { - throw unsupported() - } - - mutating func encode(_: Int64) throws { - throw unsupported() - } - - mutating func encode(_: UInt) throws { - throw unsupported() - } - - mutating func encode(_: UInt8) throws { - throw unsupported() - } - - mutating func encode(_: UInt16) throws { - throw unsupported() - } - - mutating func encode(_: UInt32) throws { - throw unsupported() - } - - mutating func encode(_: UInt64) throws { - throw unsupported() - } - - mutating func encode(_: some Encodable) throws { - throw unsupported() - } - - mutating func nestedContainer( - keyedBy _: NestedKey.Type, - ) -> KeyedEncodingContainer { - KeyedEncodingContainer(UnsupportedKeyedEncodingContainer( - codingPath: codingPath + [IndexCodingKey(index: count)], - )) - } - - mutating func nestedUnkeyedContainer() -> any UnkeyedEncodingContainer { - UnsupportedUnkeyedEncodingContainer( - codingPath: codingPath + [IndexCodingKey(index: count)], - ) - } - - mutating func superEncoder() -> any Swift.Encoder { - PureYAML.Encoding.Encoder( - codingPath: codingPath + [IndexCodingKey(index: count)], - userInfo: [:], - ) - } - - private func unsupported() -> PureYAML.Encoding.Error { - .unsupportedContainer( - kind: "unkeyed", - path: PureYAML.Validation.Path( - codingPath: codingPath + [IndexCodingKey(index: count)], - ), - ) - } -} - -private struct IndexCodingKey: CodingKey { - var stringValue: String - var intValue: Int? - - init(index: Int) { - stringValue = "\(index)" - intValue = index - } - - init?(stringValue: String) { - self.stringValue = stringValue - intValue = nil - } - - init?(intValue: Int) { - stringValue = "\(intValue)" - self.intValue = intValue - } -} diff --git a/Sources/Encoding/Encoding.KeyedContainer.swift b/Sources/Encoding/Encoding.KeyedContainer.swift new file mode 100644 index 0000000..5e1c829 --- /dev/null +++ b/Sources/Encoding/Encoding.KeyedContainer.swift @@ -0,0 +1,164 @@ +struct KeyedEncodingContainerImpl: KeyedEncodingContainerProtocol { + let storage: PureYAML.Encoding.Encoder.Storage + var codingPath: [any CodingKey] + let userInfo: [CodingUserInfoKey: Any] + + init( + storage: PureYAML.Encoding.Encoder.Storage, + codingPath: [any CodingKey], + userInfo: [CodingUserInfoKey: Any], + ) { + self.storage = storage + self.codingPath = codingPath + self.userInfo = userInfo + if storage.value == nil { + storage.set(.mapping(.init())) + } + } + + mutating func encodeNil(forKey key: Key) throws { + storage.set(.null, forKey: key.stringValue) + } + + mutating func encode(_ value: Bool, forKey key: Key) throws { + storage.set(.bool(value), forKey: key.stringValue) + } + + mutating func encode(_ value: String, forKey key: Key) throws { + storage.set(.string(value), forKey: key.stringValue) + } + + mutating func encode(_ value: Double, forKey key: Key) throws { + storage.set(.double(value), forKey: key.stringValue) + } + + mutating func encode(_ value: Float, forKey key: Key) throws { + storage.set(.double(Double(value)), forKey: key.stringValue) + } + + mutating func encode(_ value: Int, forKey key: Key) throws { + storage.set(.int(value), forKey: key.stringValue) + } + + mutating func encode(_ value: Int8, forKey key: Key) throws { + storage.set(.int(Int(value)), forKey: key.stringValue) + } + + mutating func encode(_ value: Int16, forKey key: Key) throws { + storage.set(.int(Int(value)), forKey: key.stringValue) + } + + mutating func encode(_ value: Int32, forKey key: Key) throws { + storage.set(.int(Int(value)), forKey: key.stringValue) + } + + mutating func encode(_ value: Int64, forKey key: Key) throws { + guard let value = Int(exactly: value) else { + throw integerOutOfRange("Int64", at: key) + } + storage.set(.int(value), forKey: key.stringValue) + } + + mutating func encode(_ value: UInt, forKey key: Key) throws { + guard let value = Int(exactly: value) else { + throw integerOutOfRange("UInt", at: key) + } + storage.set(.int(value), forKey: key.stringValue) + } + + mutating func encode(_ value: UInt8, forKey key: Key) throws { + storage.set(.int(Int(value)), forKey: key.stringValue) + } + + mutating func encode(_ value: UInt16, forKey key: Key) throws { + storage.set(.int(Int(value)), forKey: key.stringValue) + } + + mutating func encode(_ value: UInt32, forKey key: Key) throws { + guard let value = Int(exactly: value) else { + throw integerOutOfRange("UInt32", at: key) + } + storage.set(.int(value), forKey: key.stringValue) + } + + mutating func encode(_ value: UInt64, forKey key: Key) throws { + guard let value = Int(exactly: value) else { + throw integerOutOfRange("UInt64", at: key) + } + storage.set(.int(value), forKey: key.stringValue) + } + + mutating func encode(_ value: some Encodable, forKey key: Key) throws { + let childStorage = PureYAML.Encoding.Encoder.Storage( + parent: storage, + parentKey: key.stringValue, + ) + let childEncoder = PureYAML.Encoding.Encoder( + codingPath: codingPath + [key], + userInfo: userInfo, + storage: childStorage, + ) + try value.encode(to: childEncoder) + _ = try childEncoder.encodedValue() + } + + mutating func nestedContainer( + keyedBy _: NestedKey.Type, + forKey key: Key, + ) -> KeyedEncodingContainer { + let childStorage = PureYAML.Encoding.Encoder.Storage( + parent: storage, + parentKey: key.stringValue, + ) + return KeyedEncodingContainer(KeyedEncodingContainerImpl( + storage: childStorage, + codingPath: codingPath + [key], + userInfo: userInfo, + )) + } + + mutating func nestedUnkeyedContainer(forKey key: Key) -> any UnkeyedEncodingContainer { + let childStorage = PureYAML.Encoding.Encoder.Storage( + parent: storage, + parentKey: key.stringValue, + ) + childStorage.fail(.unsupportedContainer( + kind: "unkeyed", + path: PureYAML.Validation.Path(codingPath: codingPath + [key]), + )) + return UnsupportedUnkeyedEncodingContainer( + codingPath: codingPath + [key], + userInfo: userInfo, + ) + } + + mutating func superEncoder() -> any Swift.Encoder { + PureYAML.Encoding.Encoder( + codingPath: codingPath, + userInfo: userInfo, + storage: storage, + ) + } + + mutating func superEncoder(forKey key: Key) -> any Swift.Encoder { + let childStorage = PureYAML.Encoding.Encoder.Storage( + parent: storage, + parentKey: key.stringValue, + ) + return PureYAML.Encoding.Encoder( + codingPath: codingPath + [key], + userInfo: userInfo, + storage: childStorage, + ) + } + + private func integerOutOfRange( + _ type: String, + at key: Key, + ) -> PureYAML.Encoding.Error { + .integerOutOfRange( + type: type, + path: PureYAML.Validation.Path(codingPath: codingPath + [key]), + ) + } +} diff --git a/Sources/Encoding/Encoding.UnsupportedUnkeyedContainer.swift b/Sources/Encoding/Encoding.UnsupportedUnkeyedContainer.swift new file mode 100644 index 0000000..a16c794 --- /dev/null +++ b/Sources/Encoding/Encoding.UnsupportedUnkeyedContainer.swift @@ -0,0 +1,123 @@ +struct UnsupportedUnkeyedEncodingContainer: UnkeyedEncodingContainer { + var codingPath: [any CodingKey] + var userInfo: [CodingUserInfoKey: Any] + var count: Int { + 0 + } + + mutating func encodeNil() throws { + throw unsupported() + } + + mutating func encode(_: Bool) throws { + throw unsupported() + } + + mutating func encode(_: String) throws { + throw unsupported() + } + + mutating func encode(_: Double) throws { + throw unsupported() + } + + mutating func encode(_: Float) throws { + throw unsupported() + } + + mutating func encode(_: Int) throws { + throw unsupported() + } + + mutating func encode(_: Int8) throws { + throw unsupported() + } + + mutating func encode(_: Int16) throws { + throw unsupported() + } + + mutating func encode(_: Int32) throws { + throw unsupported() + } + + mutating func encode(_: Int64) throws { + throw unsupported() + } + + mutating func encode(_: UInt) throws { + throw unsupported() + } + + mutating func encode(_: UInt8) throws { + throw unsupported() + } + + mutating func encode(_: UInt16) throws { + throw unsupported() + } + + mutating func encode(_: UInt32) throws { + throw unsupported() + } + + mutating func encode(_: UInt64) throws { + throw unsupported() + } + + mutating func encode(_: some Encodable) throws { + throw unsupported() + } + + mutating func nestedContainer( + keyedBy _: NestedKey.Type, + ) -> KeyedEncodingContainer { + KeyedEncodingContainer(UnsupportedKeyedEncodingContainer( + codingPath: codingPath + [IndexCodingKey(index: count)], + userInfo: userInfo, + )) + } + + mutating func nestedUnkeyedContainer() -> any UnkeyedEncodingContainer { + UnsupportedUnkeyedEncodingContainer( + codingPath: codingPath + [IndexCodingKey(index: count)], + userInfo: userInfo, + ) + } + + mutating func superEncoder() -> any Swift.Encoder { + PureYAML.Encoding.Encoder( + codingPath: codingPath + [IndexCodingKey(index: count)], + userInfo: userInfo, + ) + } + + private func unsupported() -> PureYAML.Encoding.Error { + .unsupportedContainer( + kind: "unkeyed", + path: PureYAML.Validation.Path( + codingPath: codingPath + [IndexCodingKey(index: count)], + ), + ) + } +} + +private struct IndexCodingKey: CodingKey { + var stringValue: String + var intValue: Int? + + init(index: Int) { + stringValue = "\(index)" + intValue = index + } + + init?(stringValue: String) { + self.stringValue = stringValue + intValue = nil + } + + init?(intValue: Int) { + stringValue = "\(intValue)" + self.intValue = intValue + } +} diff --git a/Tests/CodingTests.swift b/Tests/CodingTests.swift index 27d3ea8..218ff9c 100644 --- a/Tests/CodingTests.swift +++ b/Tests/CodingTests.swift @@ -68,16 +68,8 @@ struct CodingTests { testCase.expectFailure() } - @Test("Unsupported decoding containers report exact errors") - func test_unsupportedDecodingContainersReportExactErrors() { - expectDecodingError( - .unsupportedContainer(kind: "keyed", path: .root), - ) { - _ = try PureYAML.decode(ExampleStruct.self, from: .mapping(.init([ - .init(key: "name", value: .string("hello")), - ]))) - } - + @Test("Unsupported unkeyed decoding container reports exact errors") + func test_unsupportedUnkeyedDecodingContainerReportsExactErrors() { expectDecodingError( .unsupportedContainer(kind: "unkeyed", path: .root), ) { @@ -85,26 +77,14 @@ struct CodingTests { } } - @Test("Unsupported encoding containers report exact errors") - func test_unsupportedEncodingContainersReportExactErrors() { - expectEncodingError( - .unsupportedContainer(kind: "keyed", path: .init([.key("name")])), - ) { - _ = try PureYAML.encode(ExampleStruct(name: "hello")) - } - + @Test("Unsupported unkeyed encoding containers report exact errors") + func test_unsupportedUnkeyedEncodingContainersReportExactErrors() { expectEncodingError( .unsupportedContainer(kind: "unkeyed", path: .init([.index(0)])), ) { _ = try PureYAML.encode([1, 2]) } - expectEncodingError( - .unsupportedContainer(kind: "keyed", path: .root), - ) { - _ = try PureYAML.encode(EmptyStruct()) - } - expectEncodingError( .unsupportedContainer(kind: "unkeyed", path: .root), ) { @@ -185,12 +165,6 @@ struct CodingErrorCase: CustomStringConvertible { } } -private struct ExampleStruct: Codable, Equatable { - var name: String -} - -private struct EmptyStruct: Encodable {} - private func expectDecodingError( _ expected: PureYAML.Decoding.Error, operation: () throws -> some Any, diff --git a/Tests/KeyedCodingTests.swift b/Tests/KeyedCodingTests.swift new file mode 100644 index 0000000..351aa3f --- /dev/null +++ b/Tests/KeyedCodingTests.swift @@ -0,0 +1,376 @@ +@testable import PureYAML +import Testing + +@Suite("Keyed Coding") +struct KeyedCodingTests { + @Test("Decodes keyed mappings with scalars optionals and nesting") + func test_decodesKeyedMappingsWithScalarsOptionalsAndNesting() throws { + let decoded = try PureYAML.decode(KeyedArticle.self, from: keyedArticleValue) + + #expect(decoded == KeyedArticle( + title: "Typed YAML", + published: true, + count: 3, + ratio: 1.5, + summary: "Intro", + missing: nil, + metadata: .init(author: "Mihaela", rank: 1), + )) + } + + @Test("Parses YAML mappings before keyed decoding") + func test_parsesYAMLMappingsBeforeKeyedDecoding() throws { + let decoded = try PureYAML.decode(KeyedMetadata.self, from: """ + author: Mihaela + rank: 1 + """) + + #expect(decoded == .init(author: "Mihaela", rank: 1)) + } + + @Test("Decodes explicit null optionals without requiring missing keys") + func test_decodesExplicitNullOptionalsWithoutRequiringMissingKeys() throws { + let decoded = try PureYAML.decode(OptionalArticle.self, from: .mapping(.init([ + .init(key: "title", value: .string("Typed YAML")), + .init(key: "summary", value: .null), + ]))) + + #expect(decoded == .init(title: "Typed YAML", summary: nil, missing: nil)) + } + + @Test("Encodes keyed structs as exact ordered mappings and YAML") + func test_encodesKeyedStructsAsExactOrderedMappingsAndYAML() throws { + let encoded = try PureYAML.encode(keyedArticle) + + #expect(encoded == keyedArticleValue) + #expect(try PureYAML.encode(EmptyKeyedStruct()) == .mapping(.init())) + + let yaml = try PureYAML.encodeToYAML(keyedArticle) + #expect(yaml == """ + title: "Typed YAML" + published: true + count: 3 + ratio: 1.5 + summary: "Intro" + metadata: + author: "Mihaela" + rank: 1 + + """) + #expect(yaml.contains("title: \"Typed YAML\"")) + #expect(!yaml.contains("missing:")) + } + + @Test("Keyed decoding failures report exact errors", arguments: keyedDecodingErrorCases) + func test_keyedDecodingFailuresReportExactErrors(testCase: KeyedDecodingErrorCase) { + testCase.expectFailure() + } + + @Test("Keyed decoding validates duplicate keys before reading values") + func test_keyedDecodingValidatesDuplicateKeysBeforeReadingValues() { + let value = PureYAML.Model.Value.mapping(.init([ + .init(key: "title", value: .string("First")), + .init(key: "title", value: .string("Second")), + ])) + let expectedIssues = [ + PureYAML.Validation.Issue( + severity: .error, + reason: "Duplicate mapping key 'title'", + path: .init([.key("title")]), + ), + ] + + expectValidationError(value) { collection in + #expect(collection.issues == expectedIssues) + #expect(collection.description == "error: Duplicate mapping key 'title' at $.title") + } + } + + @Test("Direct decoders validate duplicate keys by default") + func test_directDecodersValidateDuplicateKeysByDefault() { + let value = PureYAML.Model.Value.mapping(.init([ + .init(key: "title", value: .string("First")), + .init(key: "title", value: .string("Second")), + ])) + + expectValidationError(value) { collection in + #expect(collection.issues == [ + .init( + severity: .error, + reason: "Duplicate mapping key 'title'", + path: .init([.key("title")]), + ), + ]) + } operation: { + _ = try TitleOnly(from: PureYAML.Decoding.Decoder(value: value)) + } + } + + @Test("Direct decoders prefix validation paths with coding path") + func test_directDecodersPrefixValidationPathsWithCodingPath() { + let value = PureYAML.Model.Value.mapping(.init([ + .init(key: "title", value: .string("First")), + .init(key: "title", value: .string("Second")), + ])) + + expectValidationError(value) { collection in + #expect(collection.issues == [ + .init( + severity: .error, + reason: "Duplicate mapping key 'title'", + path: .init([.key("metadata"), .key("title")]), + ), + ]) + #expect(collection.description == "error: Duplicate mapping key 'title' at $.metadata.title") + } operation: { + _ = try TitleOnly(from: PureYAML.Decoding.Decoder( + value: value, + codingPath: [TestCodingKey("metadata")], + )) + } + } + + @Test("Keyed encoding failures report exact errors") + func test_keyedEncodingFailuresReportExactErrors() { + expectEncodingError( + .unsupportedContainer(kind: "unkeyed", path: .init([.key("items"), .index(0)])), + ) { + _ = try PureYAML.encode(UnsupportedList(items: [1])) + } + + expectEncodingError( + .integerOutOfRange(type: "UInt64", path: .init([.key("value")])), + ) { + _ = try PureYAML.encode(WideInteger(value: UInt64.max)) + } + + expectEncodingError( + .unsupportedContainer(kind: "unkeyed", path: .init([.key("items")])), + ) { + _ = try PureYAML.encode(UnsupportedListThenTitle()) + } + } + + @Test("Keyed coding error descriptions are exact") + func test_keyedCodingErrorDescriptionsAreExact() { + #expect(PureYAML.Decoding.Error.keyNotFound( + key: "title", + path: .init([.key("title")]), + ).description == "Missing required key 'title' at $.title") + + #expect(PureYAML.Decoding.Error.typeMismatch( + expected: "mapping", + actual: "string", + path: .root, + ).description == "Expected mapping at $, found string") + + #expect(PureYAML.Encoding.Error.unsupportedContainer( + kind: "unkeyed", + path: .init([.key("items")]), + ).description == "Unsupported unkeyed encoding container at $.items") + } +} + +private let keyedArticle = KeyedArticle( + title: "Typed YAML", + published: true, + count: 3, + ratio: 1.5, + summary: "Intro", + missing: nil, + metadata: .init(author: "Mihaela", rank: 1), +) + +private let keyedArticleValue = PureYAML.Model.Value.mapping(.init([ + .init(key: "title", value: .string("Typed YAML")), + .init(key: "published", value: .bool(true)), + .init(key: "count", value: .int(3)), + .init(key: "ratio", value: .double(1.5)), + .init(key: "summary", value: .string("Intro")), + .init(key: "metadata", value: .mapping(.init([ + .init(key: "author", value: .string("Mihaela")), + .init(key: "rank", value: .int(1)), + ]))), +])) + +private let keyedDecodingErrorCases: [KeyedDecodingErrorCase] = [ + .init( + name: "missing required title", + value: .mapping(.init([ + .init(key: "published", value: .bool(true)), + .init(key: "count", value: .int(1)), + .init(key: "ratio", value: .double(1.0)), + .init(key: "metadata", value: .mapping(.init([ + .init(key: "author", value: .string("Mihaela")), + .init(key: "rank", value: .int(1)), + ]))), + ])), + expected: .keyNotFound(key: "title", path: .init([.key("title")])), + kind: .article, + ), + .init( + name: "title has wrong type", + value: .mapping(.init([ + .init(key: "title", value: .int(7)), + ])), + expected: .typeMismatch(expected: "String", actual: "int", path: .init([.key("title")])), + kind: .titleOnly, + ), + .init( + name: "keyed root is not mapping", + value: .string("not a mapping"), + expected: .typeMismatch(expected: "mapping", actual: "string", path: .root), + kind: .titleOnly, + ), + .init( + name: "unkeyed property remains unsupported", + value: .mapping(.init([ + .init(key: "items", value: .sequence([.int(1)])), + ])), + expected: .unsupportedContainer(kind: "unkeyed", path: .init([.key("items")])), + kind: .list, + ), +] + +private struct KeyedArticle: Codable, Equatable { + var title: String + var published: Bool + var count: Int + var ratio: Double + var summary: String? + var missing: String? + var metadata: KeyedMetadata +} + +private struct KeyedMetadata: Codable, Equatable { + var author: String + var rank: Int +} + +private struct OptionalArticle: Codable, Equatable { + var title: String + var summary: String? + var missing: String? +} + +private struct EmptyKeyedStruct: Codable, Equatable {} + +private struct TitleOnly: Codable, Equatable { + var title: String +} + +private struct UnsupportedList: Codable, Equatable { + var items: [Int] +} + +private struct WideInteger: Encodable { + var value: UInt64 +} + +private struct UnsupportedListThenTitle: Encodable { + enum CodingKeys: String, CodingKey { + case items + case title + } + + func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + _ = container.nestedUnkeyedContainer(forKey: .items) + try container.encode("after", forKey: .title) + } +} + +private struct TestCodingKey: CodingKey { + var stringValue: String + var intValue: Int? + + init(_ stringValue: String) { + self.stringValue = stringValue + intValue = nil + } + + init?(stringValue: String) { + self.stringValue = stringValue + intValue = nil + } + + init?(intValue: Int) { + stringValue = "\(intValue)" + self.intValue = intValue + } +} + +struct KeyedDecodingErrorCase: CustomStringConvertible { + enum Kind { + case article + case titleOnly + case list + } + + var name: String + var value: PureYAML.Model.Value + var expected: PureYAML.Decoding.Error + var kind: Kind + + var description: String { + name + } + + func expectFailure() { + do { + switch kind { + case .article: + _ = try PureYAML.decode(KeyedArticle.self, from: value) + case .titleOnly: + _ = try PureYAML.decode(TitleOnly.self, from: value) + case .list: + _ = try PureYAML.decode(UnsupportedList.self, from: value) + } + recordIssue("expected decoding error") + } catch let error as PureYAML.Decoding.Error { + #expect(error == expected) + #expect(error.description == expected.description) + } catch { + recordIssue("unexpected error \(error)") + } + } +} + +private func expectEncodingError( + _ expected: PureYAML.Encoding.Error, + operation: () throws -> some Any, +) { + do { + _ = try operation() + recordIssue("expected encoding error") + } catch let error as PureYAML.Encoding.Error { + #expect(error == expected) + #expect(error.description == expected.description) + } catch { + recordIssue("unexpected error \(error)") + } +} + +private func expectValidationError( + _: PureYAML.Model.Value, + check: (PureYAML.Validation.Issue.Collection) -> Void, + operation: () throws -> some Any, +) { + do { + _ = try operation() + recordIssue("expected validation error") + } catch let collection as PureYAML.Validation.Issue.Collection { + check(collection) + } catch { + recordIssue("unexpected error \(error)") + } +} + +private func expectValidationError( + _ value: PureYAML.Model.Value, + check: (PureYAML.Validation.Issue.Collection) -> Void, +) { + expectValidationError(value, check: check) { + try PureYAML.decode(TitleOnly.self, from: value) + } +} diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 3f9a465..020f11f 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -125,11 +125,16 @@ non-strict validation returns warnings while still throwing for errors. The validation corpus pins exact issue paths, descriptions, severity splits, strict/non-strict behavior, rule traversal order, and duplicate-key diagnostics. -The first typed conversion slice supports scalar single-value Decodable and -Encodable values. `PureYAML.decode(_:from:)`, `PureYAML.encode(_:)`, and +Typed conversion supports scalar single-value Decodable and Encodable values, +plus keyed mapping-backed structs with scalar, optional scalar, and nested keyed +struct fields. `PureYAML.decode(_:from:)`, `PureYAML.encode(_:)`, and `PureYAML.encodeToYAML(_:)` validate input shapes and throw exact path-aware -typed coding errors. Keyed and unkeyed containers remain planned work under the -typed conversion roadmap. +typed coding errors. Unkeyed containers remain planned work under the typed +conversion roadmap. + +Typed decoding runs default validation before Swift `Decodable` construction. +That keeps ambiguous YAML states, such as duplicate mapping keys, from being +silently collapsed by keyed property lookup. ## Planned Compatibility Work @@ -137,7 +142,7 @@ Compatibility should be added in small, test-backed slices: 1. Tag-aware collection handling and merge keys. 2. Additional built-in validation rules beyond duplicate-key behavior. -3. Codable-style decoding and encoding. +3. Unkeyed typed decoding and encoding, then broader Codable compatibility. 4. Yams corpus comparison tests in a separate compatibility suite. The private `PureYAMLResearch` repository may be used to study Yams behavior, but