From 66de760ff23f48fae3f7970d44f889a0b437eafb Mon Sep 17 00:00:00 2001 From: Mihaela Mihaljevic Date: Fri, 5 Jun 2026 11:21:23 +0200 Subject: [PATCH] feat(validation): add predicate-gated rules --- CHANGELOG.md | 4 + Sources/Validation/Rule.Builtins.swift | 8 +- Sources/Validation/Rule.swift | 31 +++++++- Tests/ValidationModeTests.swift | 100 +++++++++++++++++++++++++ Tests/ValidationTests.swift | 38 ++++++++++ docs/rules/README.md | 1 + docs/rules/validation.md | 43 +++++++++++ 7 files changed, 220 insertions(+), 5 deletions(-) create mode 100644 docs/rules/validation.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 43c2498..2645c59 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/Sources/Validation/Rule.Builtins.swift b/Sources/Validation/Rule.Builtins.swift index d494a09..642c9e9 100644 --- a/Sources/Validation/Rule.Builtins.swift +++ b/Sources/Validation/Rule.Builtins.swift @@ -6,17 +6,17 @@ public extension PureYAML.Validation.Rule { return [] } - var seen: [String] = [] + var seen = Set() 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 diff --git a/Sources/Validation/Rule.swift b/Sources/Validation/Rule.swift index 26de992..f4c46e9 100644 --- a/Sources/Validation/Rule.swift +++ b/Sources/Validation/Rule.swift @@ -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) } } } diff --git a/Tests/ValidationModeTests.swift b/Tests/ValidationModeTests.swift index b5eb52c..89f26c9 100644 --- a/Tests/ValidationModeTests.swift +++ b/Tests/ValidationModeTests.swift @@ -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) + } } diff --git a/Tests/ValidationTests.swift b/Tests/ValidationTests.swift index a4955f1..021c05e 100644 --- a/Tests/ValidationTests.swift +++ b/Tests/ValidationTests.swift @@ -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", + ]) + } } diff --git a/docs/rules/README.md b/docs/rules/README.md index 3bfe8fc..ea84aeb 100644 --- a/docs/rules/README.md +++ b/docs/rules/README.md @@ -6,6 +6,7 @@ Load these rules before changing code: - `namespacing.md` - `cross-platform.md` - `testing.md` +- `validation.md` - `verification.md` - `commits.md` diff --git a/docs/rules/validation.md b/docs/rules/validation.md new file mode 100644 index 0000000..9eab7f4 --- /dev/null +++ b/docs/rules/validation.md @@ -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.