feat(validation): add predicate-gated rules
This commit is contained in:
parent
3715a16f5e
commit
66de760ff2
@ -46,8 +46,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
- Add emitter corpus tests and document the current emitter policy.
|
||||
- Add Yams and CYaml attribution without copying their implementation into
|
||||
`Sources/`.
|
||||
- Add validation-rule predicates, a boolean validation-rule initializer, and
|
||||
validator authoring rules.
|
||||
|
||||
### Changed
|
||||
|
||||
- Lower the package tools version to Swift 6.1 for hosted macOS CI compatibility
|
||||
and install Linux Swift toolchain prerequisites for the WASM CI job.
|
||||
- Harden duplicate-key validation to use set membership while preserving exact
|
||||
diagnostics.
|
||||
|
||||
@ -6,17 +6,17 @@ public extension PureYAML.Validation.Rule {
|
||||
return []
|
||||
}
|
||||
|
||||
var seen: [String] = []
|
||||
var seen = Set<String>()
|
||||
var issues: [PureYAML.Validation.Issue] = []
|
||||
for pair in mapping.pairs {
|
||||
if seen.contains(pair.key) {
|
||||
if seen.insert(pair.key).inserted {
|
||||
continue
|
||||
} else {
|
||||
issues.append(PureYAML.Validation.Issue(
|
||||
severity: .error,
|
||||
reason: "Duplicate mapping key '\(pair.key)'",
|
||||
path: context.path.appending(.key(pair.key)),
|
||||
))
|
||||
} else {
|
||||
seen.append(pair.key)
|
||||
}
|
||||
}
|
||||
return issues
|
||||
|
||||
@ -2,18 +2,47 @@ public extension PureYAML.Validation {
|
||||
/// A validation rule that can report zero or more path-aware issues.
|
||||
struct Rule: Sendable {
|
||||
public var description: String
|
||||
public var predicate: @Sendable (Context) -> Bool
|
||||
public var check: @Sendable (Context) -> [Issue]
|
||||
|
||||
public init(
|
||||
description: String,
|
||||
check: @escaping @Sendable (Context) -> [Issue],
|
||||
when predicate: @escaping @Sendable (Context) -> Bool = { _ in true },
|
||||
) {
|
||||
self.description = description
|
||||
self.predicate = predicate
|
||||
self.check = check
|
||||
}
|
||||
|
||||
public init(
|
||||
description: String,
|
||||
severity: Severity = .error,
|
||||
check: @escaping @Sendable (Context) -> Bool,
|
||||
when predicate: @escaping @Sendable (Context) -> 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,
|
||||
)
|
||||
}
|
||||
|
||||
public func apply(_ context: Context) -> [Issue] {
|
||||
check(context)
|
||||
guard predicate(context) else {
|
||||
return []
|
||||
}
|
||||
return check(context)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -124,4 +124,104 @@ struct ValidationModeTests {
|
||||
"warning: Legacy mode is not allowed at $.list[0].mode",
|
||||
])
|
||||
}
|
||||
|
||||
@Test("Validation rule predicate prevents rule from running")
|
||||
func test_validationRulePredicatePreventsRuleFromRunning() throws {
|
||||
let value = try PureYAML.parse("mode: legacy")
|
||||
let validator = PureYAML.Validation.Validator.blank.validating(
|
||||
PureYAML.Validation.Rule(
|
||||
description: "Never runs",
|
||||
check: { context in
|
||||
[
|
||||
PureYAML.Validation.Issue(
|
||||
severity: .error,
|
||||
reason: "Should not appear",
|
||||
path: context.path,
|
||||
),
|
||||
]
|
||||
},
|
||||
when: { _ in false },
|
||||
),
|
||||
)
|
||||
|
||||
let result = validator.collect(value)
|
||||
|
||||
#expect(result == PureYAML.Validation.Result())
|
||||
#expect(result.isValid)
|
||||
}
|
||||
|
||||
@Test("Validation rule predicate filters applied subjects")
|
||||
func test_validationRulePredicateFiltersAppliedSubjects() throws {
|
||||
let value = try PureYAML.parse(
|
||||
"""
|
||||
mode: modern
|
||||
nested:
|
||||
mode: legacy
|
||||
label: legacy
|
||||
""",
|
||||
)
|
||||
let validator = PureYAML.Validation.Validator.blank.validating(
|
||||
PureYAML.Validation.Rule(
|
||||
description: "Legacy mode is not allowed",
|
||||
check: { context in
|
||||
[
|
||||
PureYAML.Validation.Issue(
|
||||
severity: .error,
|
||||
reason: "Legacy mode is not allowed",
|
||||
path: context.path,
|
||||
),
|
||||
]
|
||||
},
|
||||
when: { context in
|
||||
context.path.components.last == .key("mode")
|
||||
&& context.subject == .string("legacy")
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
let result = validator.collect(value)
|
||||
|
||||
#expect(result.issues == [
|
||||
.init(
|
||||
severity: .error,
|
||||
reason: "Legacy mode is not allowed",
|
||||
path: .init([.key("nested"), .key("mode")]),
|
||||
),
|
||||
])
|
||||
#expect(!result.issues.contains(.init(
|
||||
severity: .error,
|
||||
reason: "Legacy mode is not allowed",
|
||||
path: .init([.key("nested"), .key("label")]),
|
||||
)))
|
||||
}
|
||||
|
||||
@Test("Boolean validation rule reports exact default failure reason")
|
||||
func test_booleanValidationRuleReportsExactDefaultFailureReason() throws {
|
||||
let value = try PureYAML.parse(
|
||||
"""
|
||||
title: Example
|
||||
state: draft
|
||||
""",
|
||||
)
|
||||
let validator = PureYAML.Validation.Validator.blank.validating(
|
||||
PureYAML.Validation.Rule(
|
||||
description: "State is published",
|
||||
check: { context in context.subject == .string("published") },
|
||||
when: { context in context.path.components.last == .key("state") },
|
||||
),
|
||||
)
|
||||
|
||||
expectValidationError(value, using: validator) { collection in
|
||||
#expect(collection.issues == [
|
||||
.init(
|
||||
severity: .error,
|
||||
reason: "Failed to satisfy: State is published",
|
||||
path: .init([.key("state")]),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
let valid = try PureYAML.parse("state: published")
|
||||
#expect(try PureYAML.validate(valid, using: validator).isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
@ -86,6 +86,34 @@ struct ValidationTests {
|
||||
),
|
||||
],
|
||||
),
|
||||
ValidationDuplicateKeyCase(
|
||||
name: "non-adjacent duplicate key",
|
||||
yaml: """
|
||||
title: First
|
||||
name: Example
|
||||
title: Second
|
||||
""",
|
||||
expectedIssues: [
|
||||
.init(
|
||||
severity: .error,
|
||||
reason: "Duplicate mapping key 'title'",
|
||||
path: .init([.key("title")]),
|
||||
),
|
||||
],
|
||||
),
|
||||
ValidationDuplicateKeyCase(
|
||||
name: "flow mapping duplicate key",
|
||||
yaml: """
|
||||
root: {name: First, name: Second}
|
||||
""",
|
||||
expectedIssues: [
|
||||
.init(
|
||||
severity: .error,
|
||||
reason: "Duplicate mapping key 'name'",
|
||||
path: .init([.key("root"), .key("name")]),
|
||||
),
|
||||
],
|
||||
),
|
||||
ValidationDuplicateKeyCase(
|
||||
name: "multiple duplicate keys preserve traversal order",
|
||||
yaml: """
|
||||
@ -159,4 +187,14 @@ struct ValidationTests {
|
||||
|
||||
#expect(try PureYAML.validate(value, using: .blank).isEmpty)
|
||||
}
|
||||
|
||||
@Test("Default validator exposes exact built-in rule descriptions")
|
||||
func test_defaultValidatorExposesExactBuiltInRuleDescriptions() {
|
||||
#expect(PureYAML.Validation.Validator.defaultRules.map(\.description) == [
|
||||
"Mapping keys are unique",
|
||||
])
|
||||
#expect(PureYAML.Validation.Validator().rules.map(\.description) == [
|
||||
"Mapping keys are unique",
|
||||
])
|
||||
}
|
||||
}
|
||||
|
||||
@ -6,6 +6,7 @@ Load these rules before changing code:
|
||||
- `namespacing.md`
|
||||
- `cross-platform.md`
|
||||
- `testing.md`
|
||||
- `validation.md`
|
||||
- `verification.md`
|
||||
- `commits.md`
|
||||
|
||||
|
||||
43
docs/rules/validation.md
Normal file
43
docs/rules/validation.md
Normal file
@ -0,0 +1,43 @@
|
||||
# Validation Rules
|
||||
|
||||
Rules for writing PureYAML validators and validation tests.
|
||||
|
||||
## Core Rule
|
||||
|
||||
A validator is a diagnostic contract, not just a throwing function. Every new
|
||||
validation rule must make these parts explicit:
|
||||
|
||||
- **Subject**: the YAML value shape the rule inspects.
|
||||
- **Predicate**: the condition under which the rule runs. Use `when` for
|
||||
optional or context-specific checks instead of hiding that logic in the issue
|
||||
body.
|
||||
- **Context**: use `root`, `subject`, and `path` deliberately. If a rule needs
|
||||
document-wide knowledge, read it from `root`; if it only needs the current
|
||||
node, read it from `subject`.
|
||||
- **Issue contract**: return path-aware `Issue` values with exact severity,
|
||||
reason, and path. Do not report anonymous failures.
|
||||
- **Default status**: state whether the rule belongs in
|
||||
`Validation.Validator.defaultRules` or must be opt-in.
|
||||
|
||||
## Test Contract
|
||||
|
||||
Every validator change must include Swift Testing coverage for:
|
||||
|
||||
- a document that succeeds and returns no issues;
|
||||
- a document that fails with exact issue values;
|
||||
- a case where the predicate prevents the rule from running;
|
||||
- required presence and required absence checks, so false positives are caught;
|
||||
- exact traversal order when multiple issues are possible;
|
||||
- strict and non-strict behavior when the rule can emit warnings;
|
||||
- exact thrown `Issue.Collection` contents for failure cases.
|
||||
|
||||
## Implementation Rules
|
||||
|
||||
- Keep rules as immutable values under `PureYAML.Validation.Rule`.
|
||||
- Prefer a `when` predicate over early-returning inside the rule body when the
|
||||
rule only applies to a subset of nodes.
|
||||
- Keep built-in rules deterministic and allocation-conscious. Use sets or maps
|
||||
for membership checks instead of repeated linear scans.
|
||||
- Do not add external dependencies, Foundation, C shims, or platform-specific
|
||||
code to validation.
|
||||
- Do not make validation mutate parsed values. Validation observes and reports.
|
||||
Loading…
Reference in New Issue
Block a user