PureYAML/Sources/PureYAMLJSON/JSON.Convert.swift
Mihaela Mihaljevic a8950e118c Merge conformance/yaml-test-suite-gaps: the libyaml port becomes the engine on main
The ported engine wins every conflict: main's post-fork patches to the
hand-rolled Scanner and TokenEventParser land on deleted files and are
dropped; their behaviors are carried by the port and guarded by the
whole-suite conformance gate (402/402 passing).

Merge adaptations, all gates green (style, namespacing, forbidden
patterns, changelog, roadmap, swiftformat, swiftlint strict, build,
full test suite, whole-suite conformance sweep):

- PureYAMLJSON representability rules move onto the Check algebra,
  replacing the retired legacy Rule type.
- The permissive tag-handle pre-pass is removed; the port rejects an
  undefined handle at parse time (suite case QLJ7) and the validation
  report carries it as a parse diagnostic.
- EventStreamComposer's nested types split one-per-file per the
  namespacing gate.
- Tests pinned to old-engine behavior were re-verified against the
  reference and updated: libyaml rejects an explicit-key continuation
  ending at a value colon, and suite case QB6E requires rejecting a
  quoted continuation at column 0.
- CHANGELOG unreleased entries from both lines are preserved in two
  groups with a provenance note.

Closes #1, closes #3
2026-07-05 00:23:48 +02:00

65 lines
2.9 KiB
Swift

import PureYAML
public extension PureYAML.JSON {
/// Standalone YAML <-> JSON conversion. It depends only on the parsing/emitting
/// engine and the JSON writer; it knows nothing about any editor or UI, so it is
/// usable on its own (a CLI, a server, a build step, a test).
///
/// A conversion succeeds only when, in order:
/// 1. the source parses,
/// 2. the value is representable in the target format, and
/// 3. the emitted output parses back to a value identical to the source
/// (a lossless round-trip check that also guards against emitter defects).
///
/// JSON is a subset of YAML 1.2, so the same engine parses both the source and
/// the re-parsed output; only "to JSON" can be rejected for representability (a
/// value may use a non-string key or a non-finite number). "To YAML" still
/// rejects duplicate keys, which are legal in JSON but not in YAML.
enum Convert {
/// Convert source text to the target format, validated end to end.
public static func convert(_ source: String, to target: Format, pretty: Bool = true) throws -> String {
let value = try parse(source)
let output = try emit(value, as: target, pretty: pretty)
guard try parse(output) == value else {
throw Failure.roundTripMismatch(target)
}
return output
}
/// Emit a value tree in the target format. The value is validated for
/// representability first; the round-trip check is not run here (use
/// ``convert(_:to:pretty:)`` for the fully validated path).
public static func emit(_ value: PureYAML.Model.Value, as target: Format, pretty: Bool = true) throws -> String {
let issues = validator(for: target).collect(value).issues
guard issues.isEmpty else {
throw Failure.notRepresentable(issues)
}
switch target {
case .json:
return try PureYAML.JSON.Writer.string(from: value, options: .init(pretty: pretty, indent: 2))
case .yaml:
return PureYAML.dump(value, options: .init(scalarStyle: .plainWhenSafe, collectionStyle: .block))
}
}
/// The validator for a target format. JSON additionally requires string keys
/// and finite numbers; YAML allows complex keys but still forbids duplicates.
public static func validator(for target: Format) -> PureYAML.Validation.Validator {
switch target {
case .json:
PureYAML.JSON.Validator.representability
case .yaml:
PureYAML.Validation.Validator()
}
}
private static func parse(_ text: String) throws -> PureYAML.Model.Value {
do {
return try PureYAML.parse(text)
} catch {
throw Failure.sourceInvalid(String(describing: error))
}
}
}
}