From 68122ad887aa1182954b80d055f6ec8556612b15 Mon Sep 17 00:00:00 2001 From: Mihaela Mihaljevic Date: Mon, 8 Jun 2026 15:45:27 +0200 Subject: [PATCH] feat(schematron): dynamic message content and phase support Two ISO Schematron gaps, the most validator-relevant first: - Dynamic messages: an assert/report message is now a template, so renders the string value of its XPath at the context node and renders the node's name. A finding can report actual values ("Age 120 must be under 100") instead of static text. - Phases: scopes which patterns run. validate(_:phase:) honors a requested phase or the schema's defaultPhase; nil or #ALL runs every pattern. let variables, abstract rules/extends, diagnostics, and key()/document() remain (the last depends on XSLT-style function injection). Part of #80 --- Sources/Validation/Schematron.swift | 48 +++++++++++--- Sources/Validation/SchematronModel.swift | 30 +++++++-- Sources/Validation/SchematronParser.swift | 51 +++++++++++--- Tests/SchematronDynamicTests.swift | 81 +++++++++++++++++++++++ 4 files changed, 187 insertions(+), 23 deletions(-) create mode 100644 Tests/SchematronDynamicTests.swift diff --git a/Sources/Validation/Schematron.swift b/Sources/Validation/Schematron.swift index e673b6c..1e9e865 100644 --- a/Sources/Validation/Schematron.swift +++ b/Sources/Validation/Schematron.swift @@ -8,23 +8,38 @@ public extension PureXML.Validation { /// warning finding. Both are ``ValidationError`` values carrying the message. /// /// Within a pattern a node is processed by the first rule whose context - /// selects it. Dynamic message content (``, ``) is rendered as - /// its static text; the message substitution itself is not evaluated. + /// selects it. Dynamic message content is evaluated: `` + /// renders the string value of its XPath at the context node, and `` + /// renders the node's name, so a finding can report actual values. A `` + /// (or the schema's `defaultPhase`) scopes which patterns run. struct Schematron { - private let patterns: [SchematronPattern] + private let schema: SchematronSchema /// Compiles a Schematron schema document. Throws if a context or test is /// not a valid XPath expression. public init(schema xml: String) throws { - patterns = try SchematronParser.parse(xml) + schema = try SchematronParser.parse(xml) } /// Validates an XML document against the schema, returning one finding per /// failed assertion and per matched report, in document order. Assertions - /// are errors and reports are warnings. - public func validate(_ xml: String) throws -> [ValidationError] { + /// are errors and reports are warnings. With `phase` (or the schema's + /// `defaultPhase`), only the patterns that phase activates run; nil or + /// `#ALL` runs every pattern. + public func validate(_ xml: String, phase: String? = nil) throws -> [ValidationError] { let node = try PureXML.parse(xml) - return Validator.blank.validating(Self.rule(patterns)).errors(for: node, in: ()) + return Validator.blank.validating(Self.rule(activePatterns(phase: phase))).errors(for: node, in: ()) + } + + /// The patterns active in the requested phase, falling back to the schema's + /// declared default phase; all patterns when no phase scopes them. + private func activePatterns(phase requested: String?) -> [SchematronPattern] { + let selected = requested ?? schema.defaultPhase + guard let selected, selected != "#ALL", let active = schema.phases[selected] else { + return schema.patterns + } + let ids = Set(active) + return schema.patterns.filter { $0.id.map(ids.contains) ?? false } } /// The schema as a single ``Validation`` over the document root, so it @@ -58,14 +73,29 @@ public extension PureXML.Validation { for assertion in assertions { let holds = (try? assertion.test.value(at: node).boolean) ?? false if assertion.isReport { - if holds { errors.append(ValidationError(reason: assertion.message, at: path, severity: .warning)) } + if holds { errors.append(ValidationError(reason: render(assertion.message, at: node), at: path, severity: .warning)) } } else if !holds { - errors.append(ValidationError(reason: assertion.message, at: path, severity: .error)) + errors.append(ValidationError(reason: render(assertion.message, at: node), at: path, severity: .error)) } } return errors } + /// Renders a message template against the context node: literal text as is, + /// `` as the string value of its XPath, `` as the node's + /// name. Whitespace runs are collapsed so the rendered message reads + /// cleanly regardless of source indentation. + private static func render(_ parts: [SchematronMessagePart], at node: PureXML.Model.TreeNode) -> String { + let joined = parts.map { part -> String in + switch part { + case let .text(text): text + case let .valueOf(query): (try? query.value(at: node).string) ?? "" + case .name: node.name?.description ?? "" + } + }.joined() + return joined.split(whereSeparator: \.isWhitespace).joined(separator: " ") + } + /// The coding path of a context node, built from the element chain to the /// root (a sibling index only when a name repeats), so each finding is /// located at the node its rule fired on rather than the document root. diff --git a/Sources/Validation/SchematronModel.swift b/Sources/Validation/SchematronModel.swift index 6c2617a..e4312ff 100644 --- a/Sources/Validation/SchematronModel.swift +++ b/Sources/Validation/SchematronModel.swift @@ -1,10 +1,20 @@ extension PureXML.Validation { - /// One `` or ``: a compiled XPath test and its message. An - /// assert flags when its test is false; a report flags when its test is true. + /// One piece of an assertion message: literal text, a `` + /// whose XPath is evaluated against the context node, or a `` rendering + /// the context node's name. Lets a finding report actual values. + enum SchematronMessagePart { + case text(String) + case valueOf(PureXML.XPath.Query) + case name + } + + /// One `` or ``: a compiled XPath test and its message + /// template. An assert flags when its test is false; a report flags when its + /// test is true. struct SchematronAssertion { let isReport: Bool let test: PureXML.XPath.Query - let message: String + let message: [SchematronMessagePart] } /// One ``: a compiled context that selects the nodes the rule fires on, @@ -14,9 +24,19 @@ extension PureXML.Validation { let assertions: [SchematronAssertion] } - /// One ``: a list of rules. A node is processed by the first rule in - /// the pattern whose context selects it (the ISO Schematron firing rule). + /// One ``: an optional id (referenced by `` in a phase) and a + /// list of rules. A node is processed by the first rule in the pattern whose + /// context selects it (the ISO Schematron firing rule). struct SchematronPattern { + let id: String? let rules: [SchematronRule] } + + /// A compiled Schematron schema: its patterns and its phases (each phase id + /// mapped to the pattern ids it activates), plus the declared default phase. + struct SchematronSchema { + let patterns: [SchematronPattern] + let phases: [String: [String]] + let defaultPhase: String? + } } diff --git a/Sources/Validation/SchematronParser.swift b/Sources/Validation/SchematronParser.swift index 25a2d40..61e0b0a 100644 --- a/Sources/Validation/SchematronParser.swift +++ b/Sources/Validation/SchematronParser.swift @@ -1,15 +1,31 @@ extension PureXML.Validation { - /// Parses a Schematron schema document into patterns. Namespace-agnostic: it - /// matches the `schema`, `pattern`, `rule`, `assert`, and `report` elements by - /// local name, so both the ISO and the legacy Schematron namespaces work. + /// Parses a Schematron schema document into patterns and phases. Namespace + /// agnostic: it matches the `schema`, `phase`, `active`, `pattern`, `rule`, + /// `assert`, and `report` elements by local name, so both the ISO and the + /// legacy Schematron namespaces work. enum SchematronParser { - static func parse(_ xml: String) throws -> [SchematronPattern] { + static func parse(_ xml: String) throws -> SchematronSchema { let root = try PureXML.parseTree(xml) - return try descendants(root, localName: "pattern").map(pattern) + let schema = descendants(root, localName: "schema").first ?? root + let patterns = try descendants(root, localName: "pattern").map(pattern) + return SchematronSchema( + patterns: patterns, + phases: phases(root), + defaultPhase: attribute(schema, "defaultPhase"), + ) + } + + private static func phases(_ root: PureXML.Model.TreeNode) -> [String: [String]] { + var result: [String: [String]] = [:] + for phase in descendants(root, localName: "phase") { + guard let id = attribute(phase, "id") else { continue } + result[id] = children(phase, localName: "active").compactMap { attribute($0, "pattern") } + } + return result } private static func pattern(_ node: PureXML.Model.TreeNode) throws -> SchematronPattern { - try SchematronPattern(rules: children(node, localName: "rule").compactMap(rule)) + try SchematronPattern(id: attribute(node, "id"), rules: children(node, localName: "rule").compactMap(rule)) } private static func rule(_ node: PureXML.Model.TreeNode) throws -> SchematronRule? { @@ -22,14 +38,31 @@ extension PureXML.Validation { private static func assertion(_ node: PureXML.Model.TreeNode) throws -> SchematronAssertion? { guard let test = attribute(node, "test") else { return nil } - let isReport = node.name?.localName == "report" return try SchematronAssertion( - isReport: isReport, + isReport: node.name?.localName == "report", test: PureXML.XPath.Query(test), - message: node.stringValue.trimmingXMLWhitespace(), + message: messageParts(node), ) } + /// Builds an assertion message template from a node's children: text nodes + /// become literal parts, `` an XPath part, and `` a + /// context-name part. The parts render against the context node at + /// validation time. + private static func messageParts(_ node: PureXML.Model.TreeNode) throws -> [SchematronMessagePart] { + var parts: [SchematronMessagePart] = [] + for child in node.children { + if child.kind == .text || child.kind == .cdata { + parts.append(.text(child.value)) + } else if child.kind == .element, child.name?.localName == "value-of", let select = attribute(child, "select") { + try parts.append(.valueOf(PureXML.XPath.Query(select))) + } else if child.kind == .element, child.name?.localName == "name" { + parts.append(.name) + } + } + return parts + } + private static func isAssertion(_ node: PureXML.Model.TreeNode) -> Bool { node.name?.localName == "assert" || node.name?.localName == "report" } diff --git a/Tests/SchematronDynamicTests.swift b/Tests/SchematronDynamicTests.swift new file mode 100644 index 0000000..a6c5e42 --- /dev/null +++ b/Tests/SchematronDynamicTests.swift @@ -0,0 +1,81 @@ +@testable import PureXML +import Testing + +@Suite("Schematron dynamic messages and phases") +struct SchematronDynamicTests { + private func validate(_ schema: String, _ xml: String, phase: String? = nil) throws -> [PureXML.Validation.ValidationError] { + try PureXML.Validation.Schematron(schema: schema).validate(xml, phase: phase) + } + + @Test("value-of renders the actual value in an assertion message") + func test_valueOf() throws { + let schema = """ + + + + Age must be under 100 + + + + """ + let errors = try validate(schema, "120") + #expect(errors.count == 1) + #expect(errors.first?.reason == "Age 120 must be under 100") + } + + @Test("name renders the context element's name") + func test_name() throws { + let schema = """ + + + + Element needs an id + + + + """ + let errors = try validate(schema, "") + #expect(errors.count == 1) + #expect(errors.first?.reason == "Element item needs an id") + } + + @Test("A phase activates only its listed patterns") + func test_phase() throws { + let schema = """ + + + + + + a is bad + + + b is bad + + + """ + let xml = "" + // The basic phase runs only p1, so only the a-rule fires. + let basic = try validate(schema, xml, phase: "basic") + #expect(basic.count == 1) + #expect(basic.first?.reason == "a is bad") + // With no phase, every pattern runs. + #expect(try validate(schema, xml).count == 2) + // #ALL runs every pattern. + #expect(try validate(schema, xml, phase: "#ALL").count == 2) + } + + @Test("defaultPhase scopes patterns when no phase is requested") + func test_defaultPhase() throws { + let schema = """ + + + a is bad + b is bad + + """ + let errors = try validate(schema, "") + #expect(errors.count == 1) + #expect(errors.first?.reason == "a is bad") + } +}