Introduce the core of the validation-rules idiom: a Check<Subject> with a positive description, a when predicate, and a Bool or multi-error check that fires only on values of its Subject type wherever they occur. AnyCheck erases the subject and dispatches by runtime type, guarding an optional or a wrong type from matching. The validator gains a checks list, a validating(_:) overload, and a traversal that offers each node the values it may specialise on. BuiltinCheck.mappingKeysAreUnique is the type-directed counterpart of the legacy rule. The machinery has its own negative tests (wrong type, optional, false predicate yield nothing; same type twice yields two errors) and the builtin ships a failing and a near-miss test. The coverage gate catches the five new public types, which are classified as validation machinery. The default validator is unchanged, so this is additive; retiring the legacy Rule, moving the default onto the check, the combinator algebra, the error rendering, and de-duplicating the Tagged validator are the remaining steps.
49 lines
2.1 KiB
Swift
49 lines
2.1 KiB
Swift
public extension PureYAML.Validation {
|
|
/// A type-directed validation value (the `Validation<Subject>` of the validation idiom): 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.
|
|
struct Check<Subject: Validatable>: Sendable {
|
|
public let description: String
|
|
public let predicate: @Sendable (SubjectContext<Subject>) -> Bool
|
|
public let check: @Sendable (SubjectContext<Subject>) -> [Issue]
|
|
|
|
/// Multi-error form: return one issue per problem. Use when a subject can fail several ways.
|
|
public init(
|
|
description: String,
|
|
check: @escaping @Sendable (SubjectContext<Subject>) -> [Issue],
|
|
when predicate: @escaping @Sendable (SubjectContext<Subject>) -> 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 issue `"Failed to satisfy: <description>"`. The dominant form.
|
|
public init(
|
|
description: String,
|
|
severity: Severity = .error,
|
|
check: @escaping @Sendable (SubjectContext<Subject>) -> Bool,
|
|
when predicate: @escaping @Sendable (SubjectContext<Subject>) -> Bool = { _ in true },
|
|
) {
|
|
self.init(
|
|
description: description,
|
|
check: { context in
|
|
check(context)
|
|
? []
|
|
: [Issue(severity: severity, reason: "Failed to satisfy: \(description)", path: context.path)]
|
|
},
|
|
when: predicate,
|
|
)
|
|
}
|
|
|
|
/// Gates on the predicate, then runs the check.
|
|
public func apply(_ context: SubjectContext<Subject>) -> [Issue] {
|
|
guard predicate(context) else {
|
|
return []
|
|
}
|
|
return check(context)
|
|
}
|
|
}
|
|
}
|