feat(tagged): add typed constructor policy
This commit is contained in:
parent
697b9cc519
commit
91a2c24901
@ -21,6 +21,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- Add `PureYAML.parseTagged(_:)` and `PureYAML.parseTaggedStream(_:)` for
|
||||
tag-preserving node trees, plus tagged validation rules for unsupported
|
||||
built-in tags and tags applied to the wrong node kind.
|
||||
- Add `PureYAML.Tagged.Constructor` for caller-owned tagged construction with
|
||||
exact missing-handler and kind-mismatch errors, recursive path context, and an
|
||||
explicit model-value fallback that preserves mapping order and duplicates
|
||||
while erasing tags.
|
||||
- Add first-class complex mapping keys through `Model.Pair.keyNode`, including
|
||||
parsing, deterministic validation paths, duplicate-key checks, and block/flow
|
||||
dumping for sequence and mapping keys.
|
||||
|
||||
24
README.md
24
README.md
@ -57,12 +57,14 @@ It is not yet a full YAML 1.2 implementation. The internal event parser now
|
||||
recognizes anchors, aliases, tags, flow collections, and block scalar styles from
|
||||
scanner tokens, and the public value parser composes those events into
|
||||
`PureYAML.Model.Value`. The tagged parser preserves explicit scalar and
|
||||
collection tags without adding Foundation-backed constructors; use normal
|
||||
parsing when semantic merge-key expansion is required. Directives beyond the
|
||||
selected compatibility subset, automatic `Data`/`Date` construction, and custom
|
||||
decoding are planned work. Unsupported gaps are pinned by executable tests so
|
||||
they produce exact errors, exact validation issues, or exact fallback value
|
||||
trees instead of silent parser drift.
|
||||
collection tags without adding Foundation-backed constructors; callers can opt
|
||||
into `PureYAML.Tagged.Constructor` when they want a typed, project-owned
|
||||
construction policy. Use normal parsing when semantic merge-key expansion is
|
||||
required. Directives beyond the selected compatibility subset and automatic
|
||||
`Data`/`Date` construction remain out of scope for the library target.
|
||||
Unsupported gaps are pinned by executable tests so they produce exact errors,
|
||||
exact validation issues, or exact fallback value trees instead of silent parser
|
||||
drift.
|
||||
|
||||
## Attribution
|
||||
|
||||
@ -111,6 +113,16 @@ value: !!timestamp 2001-01-23
|
||||
let tagIssues = PureYAML.Tagged.Validator().collect(tagged)
|
||||
```
|
||||
|
||||
Use `PureYAML.Tagged.Constructor` when a project owns a custom tag policy:
|
||||
|
||||
```swift
|
||||
let env = try PureYAML.Tagged.Constructor<String>()
|
||||
.constructingScalar(tag: .init("!Env")) { scalar, _ in
|
||||
scalar.rawValue
|
||||
}
|
||||
.construct(try PureYAML.parseTagged("!Env DATABASE_URL"))
|
||||
```
|
||||
|
||||
Use `parseStream(_:)` when the input may contain more than one YAML document.
|
||||
Each returned document carries its stream index, and validation preserves that
|
||||
index when reporting issues:
|
||||
|
||||
30
Sources/Tagged/Tagged.ConstructionContext.swift
Normal file
30
Sources/Tagged/Tagged.ConstructionContext.swift
Normal file
@ -0,0 +1,30 @@
|
||||
public extension PureYAML.Tagged {
|
||||
/// Context passed to a tagged-node construction handler.
|
||||
struct ConstructionContext<Output>: Sendable {
|
||||
public var root: Node
|
||||
public var subject: Node
|
||||
public var path: PureYAML.Validation.Path
|
||||
|
||||
let constructValue: @Sendable (Node, PureYAML.Validation.Path) throws -> Output
|
||||
|
||||
init(
|
||||
root: Node,
|
||||
subject: Node,
|
||||
path: PureYAML.Validation.Path,
|
||||
constructValue: @escaping @Sendable (Node, PureYAML.Validation.Path) throws -> Output,
|
||||
) {
|
||||
self.root = root
|
||||
self.subject = subject
|
||||
self.path = path
|
||||
self.constructValue = constructValue
|
||||
}
|
||||
|
||||
/// Constructs another node with the same constructor policy.
|
||||
public func construct(
|
||||
_ node: Node,
|
||||
at path: PureYAML.Validation.Path,
|
||||
) throws -> Output {
|
||||
try constructValue(node, path)
|
||||
}
|
||||
}
|
||||
}
|
||||
42
Sources/Tagged/Tagged.ConstructionError.swift
Normal file
42
Sources/Tagged/Tagged.ConstructionError.swift
Normal file
@ -0,0 +1,42 @@
|
||||
public extension PureYAML.Tagged {
|
||||
/// Error returned when a tagged node cannot be constructed by a caller policy.
|
||||
enum ConstructionError: Swift.Error, Equatable, Sendable, CustomStringConvertible {
|
||||
case noConstructor(
|
||||
tag: Tag?,
|
||||
kind: NodeKind,
|
||||
path: PureYAML.Validation.Path,
|
||||
)
|
||||
case kindMismatch(
|
||||
tag: Tag,
|
||||
expected: [NodeKind],
|
||||
actual: NodeKind,
|
||||
path: PureYAML.Validation.Path,
|
||||
)
|
||||
|
||||
public var description: String {
|
||||
switch self {
|
||||
case let .kindMismatch(tag, expected, actual, path):
|
||||
"Constructor for tag '\(tag)' expects \(expected.kindListDescription), found \(actual) at \(path)"
|
||||
case let .noConstructor(.some(tag), kind, path):
|
||||
"No constructor for tag '\(tag)' on \(kind) at \(path)"
|
||||
case let .noConstructor(nil, kind, path):
|
||||
"No constructor for untagged \(kind) at \(path)"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension [PureYAML.Tagged.NodeKind] {
|
||||
var kindListDescription: String {
|
||||
switch count {
|
||||
case 0:
|
||||
"no node kind"
|
||||
case 1:
|
||||
self[0].description
|
||||
case 2:
|
||||
"\(self[0]) or \(self[1])"
|
||||
default:
|
||||
"\(dropLast().map(\.description).joined(separator: ", ")), or \(last?.description ?? "unknown")"
|
||||
}
|
||||
}
|
||||
}
|
||||
139
Sources/Tagged/Tagged.Constructor.swift
Normal file
139
Sources/Tagged/Tagged.Constructor.swift
Normal file
@ -0,0 +1,139 @@
|
||||
public extension PureYAML.Tagged {
|
||||
/// Caller-owned conversion policy from tagged YAML nodes into typed values.
|
||||
struct Constructor<Output>: Sendable {
|
||||
var handlers: [Handler<Output>]
|
||||
var fallback: (@Sendable (Node, ConstructionContext<Output>) throws -> Output)?
|
||||
|
||||
public init() {
|
||||
handlers = []
|
||||
fallback = nil
|
||||
}
|
||||
|
||||
/// Constructs one tagged node from the root path.
|
||||
public func construct(_ node: Node) throws -> Output {
|
||||
try construct(root: node, subject: node, path: .root)
|
||||
}
|
||||
|
||||
/// Registers a scalar handler for an exact tag.
|
||||
public func constructingScalar(
|
||||
tag: Tag,
|
||||
_ build: @escaping @Sendable (Scalar, ConstructionContext<Output>) throws -> Output,
|
||||
) -> Self {
|
||||
appending(.init(tag: tag, kind: .scalar) { node, context in
|
||||
guard case let .scalar(scalar) = node else {
|
||||
throw PureYAML.Tagged.ConstructionError.kindMismatch(
|
||||
tag: tag,
|
||||
expected: [.scalar],
|
||||
actual: node.kind,
|
||||
path: context.path,
|
||||
)
|
||||
}
|
||||
return try build(scalar, context)
|
||||
})
|
||||
}
|
||||
|
||||
/// Registers a sequence handler for an exact tag.
|
||||
public func constructingSequence(
|
||||
tag: Tag,
|
||||
_ build: @escaping @Sendable (Sequence, ConstructionContext<Output>) throws -> Output,
|
||||
) -> Self {
|
||||
appending(.init(tag: tag, kind: .sequence) { node, context in
|
||||
guard case let .sequence(sequence) = node else {
|
||||
throw PureYAML.Tagged.ConstructionError.kindMismatch(
|
||||
tag: tag,
|
||||
expected: [.sequence],
|
||||
actual: node.kind,
|
||||
path: context.path,
|
||||
)
|
||||
}
|
||||
return try build(sequence, context)
|
||||
})
|
||||
}
|
||||
|
||||
/// Registers a mapping handler for an exact tag.
|
||||
public func constructingMapping(
|
||||
tag: Tag,
|
||||
_ build: @escaping @Sendable (Mapping, ConstructionContext<Output>) throws -> Output,
|
||||
) -> Self {
|
||||
appending(.init(tag: tag, kind: .mapping) { node, context in
|
||||
guard case let .mapping(mapping) = node else {
|
||||
throw PureYAML.Tagged.ConstructionError.kindMismatch(
|
||||
tag: tag,
|
||||
expected: [.mapping],
|
||||
actual: node.kind,
|
||||
path: context.path,
|
||||
)
|
||||
}
|
||||
return try build(mapping, context)
|
||||
})
|
||||
}
|
||||
|
||||
/// Registers an explicit fallback for nodes with no matching tag handler.
|
||||
public func fallingBackTo(
|
||||
_ build: @escaping @Sendable (Node, ConstructionContext<Output>) throws -> Output,
|
||||
) -> Self {
|
||||
var copy = self
|
||||
copy.fallback = build
|
||||
return copy
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension PureYAML.Tagged.Constructor {
|
||||
struct Handler<Value> {
|
||||
var tag: PureYAML.Tagged.Tag
|
||||
var kind: PureYAML.Tagged.NodeKind
|
||||
var build: @Sendable (
|
||||
PureYAML.Tagged.Node,
|
||||
PureYAML.Tagged.ConstructionContext<Value>,
|
||||
) throws -> Value
|
||||
}
|
||||
|
||||
func construct(
|
||||
root: PureYAML.Tagged.Node,
|
||||
subject: PureYAML.Tagged.Node,
|
||||
path: PureYAML.Validation.Path,
|
||||
) throws -> Output {
|
||||
let context = PureYAML.Tagged.ConstructionContext<Output>(
|
||||
root: root,
|
||||
subject: subject,
|
||||
path: path,
|
||||
) { node, childPath in
|
||||
try construct(root: root, subject: node, path: childPath)
|
||||
}
|
||||
|
||||
if let tag = subject.tag {
|
||||
let matches = handlers.filter { $0.tag == tag }
|
||||
if let match = matches.first(where: { $0.kind == subject.kind }) {
|
||||
return try match.build(subject, context)
|
||||
}
|
||||
if !matches.isEmpty {
|
||||
throw PureYAML.Tagged.ConstructionError.kindMismatch(
|
||||
tag: tag,
|
||||
expected: matches.map(\.kind),
|
||||
actual: subject.kind,
|
||||
path: path,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if let fallback {
|
||||
return try fallback(subject, context)
|
||||
}
|
||||
|
||||
throw PureYAML.Tagged.ConstructionError.noConstructor(
|
||||
tag: subject.tag,
|
||||
kind: subject.kind,
|
||||
path: path,
|
||||
)
|
||||
}
|
||||
|
||||
func appending(_ handler: Handler<Output>) -> Self {
|
||||
var copy = self
|
||||
copy.handlers.removeAll { existing in
|
||||
existing.tag == handler.tag && existing.kind == handler.kind
|
||||
}
|
||||
copy.handlers.append(handler)
|
||||
return copy
|
||||
}
|
||||
}
|
||||
24
Sources/Tagged/Tagged.Node.ModelValue.swift
Normal file
24
Sources/Tagged/Tagged.Node.ModelValue.swift
Normal file
@ -0,0 +1,24 @@
|
||||
public extension PureYAML.Tagged.Node {
|
||||
/// Converts a tagged node into a model value while explicitly erasing tags.
|
||||
var modelValueErasingTags: PureYAML.Model.Value {
|
||||
switch self {
|
||||
case let .mapping(mapping):
|
||||
.mapping(.init(mapping.pairs.map { pair in
|
||||
.init(key: pair.key, value: pair.value.modelValueErasingTags)
|
||||
}))
|
||||
case let .scalar(scalar):
|
||||
scalar.value
|
||||
case let .sequence(sequence):
|
||||
.sequence(sequence.values.map(\.modelValueErasingTags))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public extension PureYAML.Tagged.Constructor where Output == PureYAML.Model.Value {
|
||||
/// Explicit fallback constructor that preserves order and duplicates while erasing tags.
|
||||
static var modelValueErasingTags: Self {
|
||||
Self().fallingBackTo { node, _ in
|
||||
node.modelValueErasingTags
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -112,6 +112,18 @@ struct DocumentationExampleTests {
|
||||
#expect(tagIssues.issues == expectedIssues)
|
||||
}
|
||||
|
||||
@Test("README tagged constructor example stays executable")
|
||||
func test_readmeTaggedConstructorExample() throws {
|
||||
let tagged = try PureYAML.parseTagged("!Env DATABASE_URL")
|
||||
let constructor = PureYAML.Tagged.Constructor<String>()
|
||||
.constructingScalar(tag: .init("!Env")) { scalar, _ in
|
||||
scalar.rawValue
|
||||
}
|
||||
let env = try constructor.construct(tagged)
|
||||
|
||||
#expect(env == "DATABASE_URL")
|
||||
}
|
||||
|
||||
@Test("README emitter options example stays executable")
|
||||
func test_readmeEmitterOptionsExample() throws {
|
||||
let document = PureYAML.Model.Value.mapping(.init([
|
||||
|
||||
284
Tests/TaggedConstructorTests.swift
Normal file
284
Tests/TaggedConstructorTests.swift
Normal file
@ -0,0 +1,284 @@
|
||||
@testable import PureYAML
|
||||
import Testing
|
||||
|
||||
@Suite("Tagged Constructor")
|
||||
struct TaggedConstructorTests {
|
||||
@Test("Constructs a custom scalar tag exactly")
|
||||
func test_constructsCustomScalarTagExactly() throws {
|
||||
let tag = PureYAML.Tagged.Tag("!Env")
|
||||
let node = try PureYAML.parseTagged("!Env DATABASE_URL")
|
||||
let constructor = PureYAML.Tagged.Constructor<String>()
|
||||
.constructingScalar(tag: tag) { scalar, context in
|
||||
#expect(context.path == .root)
|
||||
#expect(context.subject == node)
|
||||
return "env:\(scalar.rawValue)"
|
||||
}
|
||||
|
||||
#expect(try constructor.construct(node) == "env:DATABASE_URL")
|
||||
}
|
||||
|
||||
@Test("Constructs a custom sequence tag without changing element order")
|
||||
func test_constructsCustomSequenceTagWithoutChangingElementOrder() throws {
|
||||
let tag = PureYAML.Tagged.Tag("!Words")
|
||||
let node = try PureYAML.parseTagged("!Words [one, two, three]")
|
||||
let constructor = PureYAML.Tagged.Constructor<[String]>()
|
||||
.constructingSequence(tag: tag) { sequence, _ in
|
||||
try sequence.values.map { node in
|
||||
let scalar = try requireTaggedScalar(node)
|
||||
return scalar.rawValue
|
||||
}
|
||||
}
|
||||
|
||||
#expect(try constructor.construct(node) == ["one", "two", "three"])
|
||||
}
|
||||
|
||||
@Test("Constructs a custom mapping tag without dictionary collapse")
|
||||
func test_constructsCustomMappingTagWithoutDictionaryCollapse() throws {
|
||||
let tag = PureYAML.Tagged.Tag("!Service")
|
||||
let node = try PureYAML.parseTagged(
|
||||
"""
|
||||
!Service
|
||||
name: api
|
||||
name: worker
|
||||
replicas: 2
|
||||
""",
|
||||
)
|
||||
let constructor = PureYAML.Tagged.Constructor<[String]>()
|
||||
.constructingMapping(tag: tag) { mapping, _ in
|
||||
mapping.pairs.map(\.key)
|
||||
}
|
||||
|
||||
#expect(try constructor.construct(node) == ["name", "name", "replicas"])
|
||||
}
|
||||
|
||||
@Test("Rejects unsupported constructors exactly")
|
||||
func test_rejectsUnsupportedConstructorsExactly() throws {
|
||||
let tag = PureYAML.Tagged.Tag("!Env")
|
||||
let node = try PureYAML.parseTagged("!Env DATABASE_URL")
|
||||
let expected = PureYAML.Tagged.ConstructionError.noConstructor(
|
||||
tag: tag,
|
||||
kind: .scalar,
|
||||
path: .root,
|
||||
)
|
||||
|
||||
expectConstructionError(expected, description: "No constructor for tag '!Env' on scalar at $") {
|
||||
try PureYAML.Tagged.Constructor<String>().construct(node)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Rejects untagged nodes without a fallback exactly")
|
||||
func test_rejectsUntaggedNodesWithoutFallbackExactly() throws {
|
||||
let node = try PureYAML.parseTagged("DATABASE_URL")
|
||||
let expected = PureYAML.Tagged.ConstructionError.noConstructor(
|
||||
tag: nil,
|
||||
kind: .scalar,
|
||||
path: .root,
|
||||
)
|
||||
|
||||
expectConstructionError(expected, description: "No constructor for untagged scalar at $") {
|
||||
try PureYAML.Tagged.Constructor<String>().construct(node)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Rejects tags registered for multiple wrong kinds exactly")
|
||||
func test_rejectsTagsRegisteredForMultipleWrongKindsExactly() throws {
|
||||
let tag = PureYAML.Tagged.Tag("!Flexible")
|
||||
let node = try PureYAML.parseTagged("!Flexible {name: api}")
|
||||
let expected = PureYAML.Tagged.ConstructionError.kindMismatch(
|
||||
tag: tag,
|
||||
expected: [.scalar, .sequence],
|
||||
actual: .mapping,
|
||||
path: .root,
|
||||
)
|
||||
let constructor = PureYAML.Tagged.Constructor<String>()
|
||||
.constructingScalar(tag: tag) { scalar, _ in
|
||||
scalar.rawValue
|
||||
}
|
||||
.constructingSequence(tag: tag) { sequence, _ in
|
||||
"\(sequence.values.count)"
|
||||
}
|
||||
|
||||
expectConstructionError(
|
||||
expected,
|
||||
description: "Constructor for tag '!Flexible' expects scalar or sequence, found mapping at $",
|
||||
) {
|
||||
try constructor.construct(node)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Uses explicit fallback for unmatched tagged nodes")
|
||||
func test_usesExplicitFallbackForUnmatchedTaggedNodes() throws {
|
||||
let node = try PureYAML.parseTagged("!Name Mihaela")
|
||||
let constructor = PureYAML.Tagged.Constructor<String>()
|
||||
.fallingBackTo { node, context in
|
||||
#expect(context.path == .root)
|
||||
#expect(context.subject == node)
|
||||
return "fallback:\(node.kind)"
|
||||
}
|
||||
|
||||
#expect(try constructor.construct(node) == "fallback:scalar")
|
||||
}
|
||||
|
||||
@Test("Rejects wrong node kind with recursive path context exactly")
|
||||
func test_rejectsWrongNodeKindWithRecursivePathContextExactly() throws {
|
||||
let boxTag = PureYAML.Tagged.Tag("!Box")
|
||||
let envTag = PureYAML.Tagged.Tag("!Env")
|
||||
let node = try PureYAML.parseTagged("!Box {value: !Env {name: DATABASE_URL}}")
|
||||
let expected = PureYAML.Tagged.ConstructionError.kindMismatch(
|
||||
tag: envTag,
|
||||
expected: [.scalar],
|
||||
actual: .mapping,
|
||||
path: .init([.key("value")]),
|
||||
)
|
||||
let constructor = PureYAML.Tagged.Constructor<String>()
|
||||
.constructingScalar(tag: envTag) { scalar, _ in
|
||||
scalar.rawValue
|
||||
}
|
||||
.constructingMapping(tag: boxTag) { mapping, context in
|
||||
guard let value = mapping["value"] else {
|
||||
throw TaggedConstructorFixtureError.invalidShape("missing value")
|
||||
}
|
||||
return try context.construct(value, at: context.path.appending(.key("value")))
|
||||
}
|
||||
|
||||
expectConstructionError(
|
||||
expected,
|
||||
description: "Constructor for tag '!Env' expects scalar, found mapping at $.value",
|
||||
) {
|
||||
try constructor.construct(node)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Propagates invalid tagged values from caller handlers exactly")
|
||||
func test_propagatesInvalidTaggedValuesFromCallerHandlersExactly() throws {
|
||||
let tag = PureYAML.Tagged.Tag("!Port")
|
||||
let node = try PureYAML.parseTagged("!Port nope")
|
||||
let constructor = PureYAML.Tagged.Constructor<Int>()
|
||||
.constructingScalar(tag: tag) { scalar, context in
|
||||
guard case let .int(port) = scalar.value else {
|
||||
throw TaggedConstructorFixtureError.invalidPort(
|
||||
rawValue: scalar.rawValue,
|
||||
path: context.path,
|
||||
)
|
||||
}
|
||||
return port
|
||||
}
|
||||
|
||||
expectTaggedConstructorFixtureError(.invalidPort(rawValue: "nope", path: .root)) {
|
||||
try constructor.construct(node)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("Explicit model fallback preserves duplicate keys and erases tags")
|
||||
func test_explicitModelFallbackPreservesDuplicateKeysAndErasesTags() throws {
|
||||
let node = try PureYAML.parseTagged(
|
||||
"""
|
||||
!Root
|
||||
title: one
|
||||
title: !Local two
|
||||
""",
|
||||
)
|
||||
let value = try PureYAML.Tagged.Constructor<PureYAML.Model.Value>
|
||||
.modelValueErasingTags
|
||||
.construct(node)
|
||||
let mapping = requireMapping(value)
|
||||
let expectedIssues = [
|
||||
PureYAML.Validation.Issue(
|
||||
severity: .error,
|
||||
reason: "Duplicate mapping key 'title'",
|
||||
path: .init([.key("title")]),
|
||||
),
|
||||
]
|
||||
|
||||
#expect(mapping?.pairs.map(\.key) == ["title", "title"])
|
||||
#expect(mapping?.pairs.map(\.value) == [.string("one"), .string("two")])
|
||||
#expect(value == node.modelValueErasingTags)
|
||||
#expect(PureYAML.Validation.Validator().collect(value).issues == expectedIssues)
|
||||
}
|
||||
|
||||
@Test("Constructors do not run tagged validation implicitly")
|
||||
func test_constructorsDoNotRunTaggedValidationImplicitly() throws {
|
||||
let node = try PureYAML.parseTagged("!!timestamp 2001-01-23")
|
||||
let value = try PureYAML.Tagged.Constructor<PureYAML.Model.Value>
|
||||
.modelValueErasingTags
|
||||
.construct(node)
|
||||
let expectedIssues = [
|
||||
PureYAML.Validation.Issue(
|
||||
severity: .error,
|
||||
reason: "Unsupported built-in tag 'tag:yaml.org,2002:timestamp'",
|
||||
path: .root,
|
||||
),
|
||||
]
|
||||
|
||||
#expect(value == .string("2001-01-23"))
|
||||
#expect(PureYAML.Tagged.Validator().collect(node).issues == expectedIssues)
|
||||
}
|
||||
|
||||
@Test("Tagged construction keeps complex mapping keys out of the tagged layer")
|
||||
func test_taggedConstructionKeepsComplexMappingKeysOutOfTheTaggedLayer() {
|
||||
expectError(PureYAML.Parsing.ParseError.expectedScalarKey(line: 1, column: 3)) {
|
||||
try PureYAML.parseTagged(
|
||||
"""
|
||||
? [a, b]
|
||||
: value
|
||||
""",
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private enum TaggedConstructorFixtureError: Swift.Error, Equatable, CustomStringConvertible {
|
||||
case invalidPort(rawValue: String, path: PureYAML.Validation.Path)
|
||||
case invalidShape(String)
|
||||
|
||||
var description: String {
|
||||
switch self {
|
||||
case let .invalidPort(rawValue, path):
|
||||
"Invalid port '\(rawValue)' at \(path)"
|
||||
case let .invalidShape(message):
|
||||
message
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func requireTaggedScalar(
|
||||
_ node: PureYAML.Tagged.Node?,
|
||||
_ message: String = "expected tagged scalar",
|
||||
) throws -> PureYAML.Tagged.Scalar {
|
||||
guard case let .scalar(scalar)? = node else {
|
||||
recordIssue(message)
|
||||
throw TaggedConstructorFixtureError.invalidShape(message)
|
||||
}
|
||||
return scalar
|
||||
}
|
||||
|
||||
private func expectConstructionError(
|
||||
_ expected: PureYAML.Tagged.ConstructionError,
|
||||
description: String,
|
||||
operation: () throws -> some Any,
|
||||
) {
|
||||
do {
|
||||
_ = try operation()
|
||||
recordIssue("expected construction error \(expected)")
|
||||
} catch let error as PureYAML.Tagged.ConstructionError {
|
||||
#expect(error == expected)
|
||||
#expect(error.description == description)
|
||||
} catch {
|
||||
recordIssue("unexpected error \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
private func expectTaggedConstructorFixtureError(
|
||||
_ expected: TaggedConstructorFixtureError,
|
||||
operation: () throws -> some Any,
|
||||
) {
|
||||
do {
|
||||
_ = try operation()
|
||||
recordIssue("expected fixture error \(expected)")
|
||||
} catch let error as TaggedConstructorFixtureError {
|
||||
#expect(error == expected)
|
||||
#expect(error.description == expected.description)
|
||||
} catch {
|
||||
recordIssue("unexpected error \(error)")
|
||||
}
|
||||
}
|
||||
@ -134,15 +134,25 @@ returns `PureYAML.Stream.Document` values with stable zero-based indexes.
|
||||
|
||||
`PureYAML.parseTagged(_:)` and `PureYAML.parseTaggedStream(_:)` reuse the same
|
||||
scanner and event parser but compose `PureYAML.Tagged.Node` values that preserve
|
||||
explicit tags on scalar, sequence, and mapping nodes. Tagged parsing is an
|
||||
analysis surface, not a constructor surface: it deliberately does not construct
|
||||
Foundation values for `!!timestamp` or `!!binary`, and project-specific tags are
|
||||
preserved for caller-owned conversion. It preserves source shape for diagnostics;
|
||||
normal parsing is the semantic surface that expands merge keys into
|
||||
explicit tags on scalar, sequence, and mapping nodes. Tagged parsing deliberately
|
||||
does not construct Foundation values for `!!timestamp` or `!!binary`, and
|
||||
project-specific tags are preserved for caller-owned conversion. It preserves
|
||||
source shape for diagnostics; normal parsing is the semantic surface that
|
||||
expands merge keys into
|
||||
`Model.Value`. `PureYAML.Tagged.Validator` reports
|
||||
unsupported built-in tags and built-in tags applied to the wrong node kind with
|
||||
the same path and stream issue types used by the main validator.
|
||||
|
||||
`PureYAML.Tagged.Constructor<Output>` is the explicit construction boundary for
|
||||
projects that want to turn tagged nodes into domain values. It starts empty,
|
||||
registers handlers by exact tag and node kind, and reports path-aware
|
||||
`ConstructionError` values when no handler exists or a tag appears on the wrong
|
||||
node kind. Handler context carries the root node, current subject, path, and a
|
||||
recursive construction method so nested conversion keeps exact diagnostics. The
|
||||
model fallback is deliberately named `modelValueErasingTags`: it preserves
|
||||
mapping order and duplicate keys, then erases tag metadata only when the caller
|
||||
has opted into that lossy boundary.
|
||||
|
||||
Mappings are ordered pairs. String keys remain the common path through
|
||||
`Model.Pair.key`, `Model.Mapping` string lookup, validation dot/bracket paths,
|
||||
and keyed `Codable`. Complex keys are represented by `Model.Key` and stored on
|
||||
@ -205,19 +215,18 @@ also includes Foundation-specific scalar conversions, which would break the
|
||||
dependency-free and WASM-compatible library boundary.
|
||||
|
||||
Application code may project `Model.Value` or `Tagged.Node` into JSON-like or
|
||||
domain-specific values after validation, but that projection must own the
|
||||
data-loss and constructor policy explicitly.
|
||||
domain-specific values after validation. `Tagged.Constructor` is the supported
|
||||
typed form of that projection, while dictionary-shaped `Any` projection remains
|
||||
outside the library because it must own data-loss policy explicitly.
|
||||
|
||||
## Planned Compatibility Work
|
||||
|
||||
Compatibility should be added in small, test-backed slices:
|
||||
|
||||
1. Multi-document stream dumping.
|
||||
2. Explicit constructor APIs for caller-owned tagged conversion if a
|
||||
dependency-free design proves worthwhile (#39).
|
||||
3. Additional built-in validation rules beyond duplicate-key behavior.
|
||||
4. Broader Codable compatibility beyond scalar, keyed, and unkeyed containers.
|
||||
5. Yams corpus comparison tests in a separate compatibility suite.
|
||||
2. Additional built-in validation rules beyond duplicate-key behavior.
|
||||
3. Broader Codable compatibility beyond scalar, keyed, and unkeyed containers.
|
||||
4. Yams corpus comparison tests in a separate compatibility suite.
|
||||
|
||||
The private `PureYAMLResearch` repository may be used to study Yams behavior, but
|
||||
the public implementation must be written in Swift and must not copy C parser
|
||||
|
||||
@ -29,6 +29,7 @@ See [../ATTRIBUTION.md](../ATTRIBUTION.md) for the project attribution.
|
||||
| Validate document structure | `PureYAML.validate(_:using:strict:)` | Default rule reports duplicate mapping keys with exact paths. |
|
||||
| Validate every document in a stream | `PureYAML.validate(_:using:strict:)` with stream documents | Reports `PureYAML.Stream.Issue` values that preserve document indexes. |
|
||||
| Validate explicit tag usage | `PureYAML.Tagged.Validator` | Reports unsupported built-in tags and kind-inconsistent built-in tags with exact paths. |
|
||||
| Construct caller-owned values from explicit tags | `PureYAML.Tagged.Constructor` | Empty by default; callers register exact tag/kind handlers or an explicit fallback. |
|
||||
| Load arbitrary `Any` dictionaries and arrays | Use `Model.Value` or typed `Codable` | There is deliberately no public arbitrary `Any` conversion API. Dictionary-shaped values erase YAML diagnostics. |
|
||||
|
||||
## Arbitrary Any Decision
|
||||
@ -53,7 +54,9 @@ For unknown schemas, use `PureYAML.Model.Value` and validate before projecting
|
||||
into project-specific values. For known schemas, use typed `Codable`. If a
|
||||
caller truly needs a JSON-like dictionary after validation, build that projection
|
||||
in the application layer where duplicate-key and unsupported-shape policies are
|
||||
explicit.
|
||||
explicit. If a caller needs custom tag construction, use
|
||||
`PureYAML.Tagged.Constructor` so unsupported tags, wrong-kind tags, and
|
||||
tag-erasing fallbacks stay explicit.
|
||||
|
||||
## Supported Today
|
||||
|
||||
@ -76,6 +79,7 @@ add a fixture beside the closest existing suite.
|
||||
| Built-in scalar tags | `!!str`, `!!int`, `!!float`, `!!bool`, and `!!null` are applied when valid. | `ScalarCompatibilityFixtures` |
|
||||
| Tag-preserving parsing | `parseTagged(_:)` and `parseTaggedStream(_:)` preserve explicit scalar and collection tags for compatibility analysis. | `TaggedCompatibilityTests` |
|
||||
| Tagged validation | Unsupported built-in tags and built-in tags applied to the wrong node kind are reported with exact paths. Project-specific tags are allowed by default. | `TaggedCompatibilityTests` |
|
||||
| Tagged construction | `PureYAML.Tagged.Constructor` supports scalar, sequence, and mapping handlers, exact missing-constructor errors, exact kind-mismatch errors, recursive path-aware construction, and an explicit model-value fallback that erases tags without collapsing duplicate keys. | `TaggedConstructorTests` |
|
||||
| Complex mapping keys | Sequence and mapping keys parse into `Model.Pair.keyNode`, validate with exact paths, and dump as explicit YAML keys. String-keyed APIs remain string-keyed. | `ComplexMappingKeyParsingTests`, `ComplexMappingKeyValidationTests`, `ComplexMappingKeyDumperTests`, `ComplexMappingKeyCodableTests` |
|
||||
| Emitting | Deterministic block output by default, with opt-in flow collections and conservative literal blocks. | `DumperTests`, `EmitterCorpusTests` |
|
||||
| Typed conversion | Scalar, keyed, unkeyed, nested, sequence, dynamic-key, and super-coder cases are covered. | `CodingTests`, `CodableCompatibilityTests` |
|
||||
@ -98,7 +102,7 @@ explicit fallback value tree. This avoids silent compatibility drift.
|
||||
| Invalid merge values | Throws `invalidMergeValue` when `<<` is not followed by a mapping or sequence of mappings. | `MergeKeyCompatibilityTests` |
|
||||
| Unsupported built-in tags such as `!!timestamp`, `!!binary`, `!!set`, and `!!omap` | `parse(_:)` keeps parseable value trees without special tag construction. `parseTagged(_:)` preserves the tags, and tagged validation reports them as unsupported built-in tags. | `UnsupportedYAMLGapsFixtures.fallbackValues`, `TaggedCompatibilityTests` |
|
||||
| Sexagesimal-style scalars and date-looking plain scalars | Keep string values for currently unsupported spellings such as `1:20`, `2002-04-28`, and `09`. | `ScalarCompatibilityFixtures.unsupportedScalars` |
|
||||
| Custom constructors, custom resolvers, and environment expansion | Not implemented. Build project-specific conversion on top of `Model.Value`, tagged nodes, or typed `Codable`. | #39 |
|
||||
| Custom resolvers and environment expansion | Not implemented. Build project-specific conversion on top of `Model.Value`, tagged nodes, typed `Codable`, or `PureYAML.Tagged.Constructor`. | Future compatibility work |
|
||||
| Foundation-specific scalar conversions such as `Data`, `Date`, or `URL` strategies | Not special-cased in the library target. Tags stay visible through `parseTagged(_:)`; callers own conversion. | `TaggedCompatibilityTests` |
|
||||
|
||||
## Migration Checklist
|
||||
@ -120,7 +124,7 @@ Do not migrate a caller yet if it requires:
|
||||
- multi-document stream dumping;
|
||||
- binary or timestamp conversion into Foundation types;
|
||||
- arbitrary `Any` load and dump APIs;
|
||||
- custom scalar constructors or resolvers;
|
||||
- custom resolvers;
|
||||
- a full YAML 1.2 compliance claim.
|
||||
|
||||
In those cases, add a fixture and a child issue before changing production call
|
||||
|
||||
@ -45,6 +45,7 @@ Those tests are the executable contract for the short-form examples.
|
||||
| Parse a YAML stream into indexed documents | `PureYAML.parseStream(_:)` | `[PureYAML.Stream.Document]` |
|
||||
| Parse YAML while preserving explicit tags | `PureYAML.parseTagged(_:)` | `PureYAML.Tagged.Node` |
|
||||
| Parse a YAML stream while preserving explicit tags | `PureYAML.parseTaggedStream(_:)` | `[PureYAML.Tagged.Document]` |
|
||||
| Construct typed values from tagged nodes | `PureYAML.Tagged.Constructor` | Caller-owned output type |
|
||||
| Emit YAML from a value tree | `PureYAML.dump(_:options:)` | `String` |
|
||||
| Validate a value tree | `PureYAML.validate(_:using:strict:)` | `[PureYAML.Validation.Issue]` or a thrown issue collection |
|
||||
| Validate stream documents | `PureYAML.validate(_:using:strict:)` with `[PureYAML.Stream.Document]` | `[PureYAML.Stream.Issue]` or a thrown stream issue collection |
|
||||
@ -142,6 +143,37 @@ PureYAML deliberately does not construct Foundation values for tags such as
|
||||
ordinary strings in `Model.Value`; callers own any `Date`, `Data`, or
|
||||
domain-specific conversion.
|
||||
|
||||
Use `PureYAML.Tagged.Constructor` when the application owns that conversion. A
|
||||
constructor is empty by default, so unsupported tags fail with an exact
|
||||
`ConstructionError` instead of silently becoming `Any` dictionaries:
|
||||
|
||||
```swift
|
||||
let value = try PureYAML.Tagged.Constructor<String>()
|
||||
.constructingScalar(tag: .init("!Env")) { scalar, _ in
|
||||
scalar.rawValue
|
||||
}
|
||||
.construct(try PureYAML.parseTagged("!Env DATABASE_URL"))
|
||||
```
|
||||
|
||||
Handlers can be registered for scalar, sequence, and mapping nodes. The context
|
||||
passed to each handler includes the root node, current node, path, and a
|
||||
recursive `construct(_:at:)` method that keeps nested construction diagnostics
|
||||
path-aware.
|
||||
|
||||
When a caller intentionally wants to drop tag metadata, use the explicit
|
||||
fallback:
|
||||
|
||||
```swift
|
||||
let model = try PureYAML.Tagged.Constructor<PureYAML.Model.Value>
|
||||
.modelValueErasingTags
|
||||
.construct(tagged)
|
||||
```
|
||||
|
||||
That fallback preserves mapping order and duplicate keys, then erases scalar,
|
||||
sequence, mapping, and key tags. It does not run tagged validation implicitly;
|
||||
call `PureYAML.Tagged.Validator` first when unsupported built-in tags should
|
||||
block construction.
|
||||
|
||||
## Typed Conversion
|
||||
|
||||
Use typed conversion when the YAML shape is already known. Current coverage
|
||||
|
||||
Loading…
Reference in New Issue
Block a user