PureYAML/Sources/Validation/Validation.swift
Mihaela Mihaljevic bf2dc4ece7 refactor(validation): rename framework to match the validation idiom
The validation module already implemented the composable-rule idiom under
its own names (Check/Issue/SubjectContext) and a value-type Validator with
duplicated traversal machinery per layer. Renamed the core types to the
canonical names (Validation/ValidationError/ValidationErrorCollection/
ValidationContext/BuiltinValidation/AnyValidation), converted Validator to
a reference-type class with the two-tier default-rule split, and genericized
it over both Subject and Document via a new Traversable protocol so the
model and tagged layers share one walk engine instead of two copies. Wired
the JSON-representability rule set into the same shape and closed the two
missing pieces (unwrap combinator, JSON coverage/config-pin tests).
2026-07-12 18:10:00 +02:00

50 lines
2.3 KiB
Swift

public extension PureYAML.Validation {
/// A type-directed validation value: a positive `description`, a `predicate` that gates
/// application, and a multi-error `check`. It is applied only to values of type `Subject`, anywhere
/// they occur in the traversed tree. `Document` is the type of the validated tree's root, the same
/// for every check a given validator runs.
struct Validation<Subject: Validatable, Document: Sendable>: Sendable {
public let description: String
public let predicate: @Sendable (ValidationContext<Subject, Document>) -> Bool
public let check: @Sendable (ValidationContext<Subject, Document>) -> [ValidationError]
/// Multi-error form: return one error per problem. Use when a subject can fail several ways.
public init(
description: String,
check: @escaping @Sendable (ValidationContext<Subject, Document>) -> [ValidationError],
when predicate: @escaping @Sendable (ValidationContext<Subject, Document>) -> Bool = { _ in true },
) {
self.description = description
self.predicate = predicate
self.check = check
}
/// Single-error Bool form: a positive description plus a check whose `false` auto-produces the
/// one error `"Failed to satisfy: <description>"`. The dominant form.
public init(
description: String,
severity: Severity = .error,
check: @escaping @Sendable (ValidationContext<Subject, Document>) -> Bool,
when predicate: @escaping @Sendable (ValidationContext<Subject, Document>) -> Bool = { _ in true },
) {
self.init(
description: description,
check: { context in
check(context)
? []
: [ValidationError(severity: severity, reason: "Failed to satisfy: \(description)", path: context.path)]
},
when: predicate,
)
}
/// Gates on the predicate, then runs the check.
public func apply(_ context: ValidationContext<Subject, Document>) -> [ValidationError] {
guard predicate(context) else {
return []
}
return check(context)
}
}
}