feat(xslt): implement xsl:message with terminate

xsl:message instantiates its body as diagnostic text and produces no
result-tree output; terminate=yes records the text and aborts the
transform with an XSLTError.terminated, halting further instantiation.
Splits the transform entry points into XSLTTransform.swift and moves the
message case to keep within the complexity and file-length budgets.
This commit is contained in:
Mihaela Mihaljevic 2026-06-09 01:29:37 +02:00
parent ff1cdfd244
commit 367b5b9425
6 changed files with 144 additions and 46 deletions

View File

@ -9,6 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- XSLT `xsl:message` (#81). The message body is instantiated as diagnostic text;
`terminate="yes"` aborts the transformation with that text as an
`XSLTError.terminated`, and processing stops at that point. A non-terminating
message produces no result-tree output.
- XSLT `xsl:strip-space` / `xsl:preserve-space` (#81). Whitespace-only text nodes
are removed from the source tree for elements named by `strip-space` before
transformation, with `preserve-space` and a more specific name test winning over

View File

@ -59,6 +59,9 @@ public extension PureXML.XSLT {
/// `xsl:processing-instruction` whose target is `name` and whose data is
/// the instantiated body.
case processingInstruction(name: ValueTemplate, body: [Instruction])
/// `xsl:message`: instantiates its body as a diagnostic. `terminate` ends
/// the transformation with that text; it produces no result-tree output.
case message(terminate: Bool, body: [Instruction])
}
/// The `xsl:output` controls that shape serialization: the output method, and

View File

@ -54,13 +54,16 @@ private enum XSLTNode {
}
public extension PureXML.XSLT {
/// Errors compiling a stylesheet.
/// Errors compiling or running a stylesheet.
enum XSLTError: Swift.Error, Equatable, Sendable, CustomStringConvertible {
case notAStylesheet
/// An `xsl:message terminate="yes"` ended the transformation with this text.
case terminated(String)
public var description: String {
switch self {
case .notAStylesheet: "the document is not an xsl:stylesheet"
case let .terminated(message): "transformation terminated: \(message)"
}
}
}
@ -226,6 +229,7 @@ extension PureXML.XSLT {
case "text": .literalText(node.stringValue)
case "variable", "param": variable(node)
case "copy": .copy(body: body(node))
case "message": .message(terminate: XSLTNode.attribute(node, "terminate") == "yes", body: body(node))
default: nil
}
}

View File

@ -0,0 +1,48 @@
public extension PureXML.XSLT {
/// Transforms `source` with `stylesheet`, returning the serialized result.
/// `documentLoader` resolves the URI argument of the `document()` function to
/// source text; it returns `nil` (the default) when external documents are
/// not available, which keeps `document()` from reaching the filesystem or
/// network by default.
static func transform(
stylesheet: String,
source: String,
options: PureXML.Emitting.Options = .compact,
documentLoader: @escaping (String) -> String? = { _ in nil },
) throws -> String {
let sheet = try XSLTParser.parse(stylesheet, loader: documentLoader)
let root = try PureXML.parseTree(source)
Whitespace.strip(root, stylesheet: sheet)
let transformer = Transformer(stylesheet: sheet, root: root, documentLoader: documentLoader)
let result = transformer.run()
if let message = transformer.terminationMessage { throw XSLTError.terminated(message) }
if sheet.output.method == "text" { return textValue(of: result) }
return PureXML.serialize(result, options: options.applying(sheet.output))
}
/// Transforms `source` with `stylesheet`, returning the result tree.
static func transformToNode(
stylesheet: String,
source: String,
documentLoader: @escaping (String) -> String? = { _ in nil },
) throws -> PureXML.Model.Node {
let sheet = try XSLTParser.parse(stylesheet, loader: documentLoader)
let root = try PureXML.parseTree(source)
Whitespace.strip(root, stylesheet: sheet)
let transformer = Transformer(stylesheet: sheet, root: root, documentLoader: documentLoader)
let result = transformer.run()
if let message = transformer.terminationMessage { throw XSLTError.terminated(message) }
return result
}
/// The concatenated text content of a result tree, for the `text` output
/// method: character data only, with markup, comments, and PIs dropped.
private static func textValue(of node: PureXML.Model.Node) -> String {
switch node {
case let .text(value), let .cdata(value): value
case let .document(children): children.map(textValue).joined()
case let .element(element): element.children.map(textValue).joined()
case .comment, .processingInstruction: ""
}
}
}

View File

@ -13,6 +13,13 @@ private struct XSLTContext {
var variables: [String: PureXML.XPath.Value]
}
/// Shared, mutable signal that an `xsl:message terminate="yes"` fired, carrying
/// its text. A reference type so the value-semantics transformer can set it.
/// File-scope and private.
private final class Termination {
var message: String?
}
extension PureXML.XSLT {
/// Runs a compiled stylesheet against a source tree, producing a result tree
/// by the XSLT 1.0 processing model: apply templates from the root, match each
@ -23,6 +30,12 @@ extension PureXML.XSLT {
let root: PureXML.Model.TreeNode
let documentLoader: (String) -> String?
private let keyIndex: PureXML.XSLT.KeyIndex
private let termination = Termination()
/// The `xsl:message terminate="yes"` text, if one fired during `run()`.
var terminationMessage: String? {
termination.message
}
init(stylesheet: Stylesheet, root: PureXML.Model.TreeNode, documentLoader: @escaping (String) -> String? = { _ in nil }) {
self.stylesheet = stylesheet
@ -31,7 +44,7 @@ extension PureXML.XSLT {
keyIndex = PureXML.XSLT.Library.buildKeyIndex(stylesheet: stylesheet, root: root)
}
fileprivate func run() -> PureXML.Model.Node {
func run() -> PureXML.Model.Node {
var variables: [String: PureXML.XPath.Value] = [:]
let baseContext = XSLTContext(node: root, position: 1, size: 1, variables: variables)
for global in stylesheet.globals {
@ -122,6 +135,7 @@ extension PureXML.XSLT {
var items: [ResultItem] = []
var context = context
for instruction in body {
if termination.message != nil { break }
if case let .variable(name, select, varBody) = instruction {
context.variables[name] = variableValue(select, varBody, context)
} else {
@ -213,6 +227,15 @@ extension PureXML.XSLT.Transformer {
}
}
/// Instantiates an `xsl:message` body as its text; `terminate` records the
/// signal so the transform aborts with it. Produces no result-tree output.
private func message(_ terminate: Bool, _ body: [PureXML.XSLT.Instruction], _ context: XSLTContext) -> [ResultItem] {
if terminate, termination.message == nil {
termination.message = Self.text(of: instantiate(body, context))
}
return []
}
private func structuralEvaluate(_ instruction: PureXML.XSLT.Instruction, _ context: XSLTContext) -> [ResultItem] {
switch instruction {
case let .literalElement(name, attributes, body):
@ -229,6 +252,8 @@ extension PureXML.XSLT.Transformer {
[.node(.comment(Self.text(of: instantiate(body, context))))]
case let .processingInstruction(name, body):
[.node(.processingInstruction(target: avt(name, context), data: Self.text(of: instantiate(body, context))))]
case let .message(terminate, body):
message(terminate, body, context)
default:
[]
}
@ -350,47 +375,3 @@ extension PureXML.XSLT.Transformer {
return (try? query.value(at: node).string) ?? ""
}
}
public extension PureXML.XSLT {
/// Transforms `source` with `stylesheet`, returning the serialized result.
/// `documentLoader` resolves the URI argument of the `document()` function to
/// source text; it returns `nil` (the default) when external documents are
/// not available, which keeps `document()` from reaching the filesystem or
/// network by default.
static func transform(
stylesheet: String,
source: String,
options: PureXML.Emitting.Options = .compact,
documentLoader: @escaping (String) -> String? = { _ in nil },
) throws -> String {
let sheet = try XSLTParser.parse(stylesheet, loader: documentLoader)
let root = try PureXML.parseTree(source)
Whitespace.strip(root, stylesheet: sheet)
let result = Transformer(stylesheet: sheet, root: root, documentLoader: documentLoader).run()
if sheet.output.method == "text" { return textValue(of: result) }
return PureXML.serialize(result, options: options.applying(sheet.output))
}
/// Transforms `source` with `stylesheet`, returning the result tree.
static func transformToNode(
stylesheet: String,
source: String,
documentLoader: @escaping (String) -> String? = { _ in nil },
) throws -> PureXML.Model.Node {
let sheet = try XSLTParser.parse(stylesheet, loader: documentLoader)
let root = try PureXML.parseTree(source)
Whitespace.strip(root, stylesheet: sheet)
return Transformer(stylesheet: sheet, root: root, documentLoader: documentLoader).run()
}
/// The concatenated text content of a result tree, for the `text` output
/// method: character data only, with markup, comments, and PIs dropped.
private static func textValue(of node: PureXML.Model.Node) -> String {
switch node {
case let .text(value), let .cdata(value): value
case let .document(children): children.map(textValue).joined()
case let .element(element): element.children.map(textValue).joined()
case .comment, .processingInstruction: ""
}
}
}

View File

@ -0,0 +1,58 @@
@testable import PureXML
import Testing
@Suite("XSLT xsl:message")
struct XSLTMessageTests {
private let xsl = "xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\""
private func transform(_ stylesheet: String, _ source: String) throws -> String {
try PureXML.XSLT.transform(stylesheet: stylesheet, source: source)
}
@Test("A non-terminating message produces no output and does not abort")
func test_nonTerminating() throws {
let style = """
<xsl:stylesheet version="1.0" \(xsl)>
<xsl:output method="xml" omit-xml-declaration="yes"/>
<xsl:template match="/">
<xsl:message>just a note</xsl:message>
<out/>
</xsl:template>
</xsl:stylesheet>
"""
#expect(try transform(style, "<x/>") == "<out/>")
}
@Test("terminate=yes aborts the transform, carrying the message text")
func test_terminate() throws {
let style = """
<xsl:stylesheet version="1.0" \(xsl)>
<xsl:template match="/">
<out/>
<xsl:message terminate="yes">stop now</xsl:message>
</xsl:template>
</xsl:stylesheet>
"""
var thrown: PureXML.XSLT.XSLTError?
do {
_ = try transform(style, "<x/>")
} catch let error as PureXML.XSLT.XSLTError {
thrown = error
}
#expect(thrown == .terminated("stop now"))
}
@Test("A terminating message can interpolate the source via value-of")
func test_terminateDynamic() throws {
let style = """
<xsl:stylesheet version="1.0" \(xsl)>
<xsl:template match="/">
<xsl:message terminate="yes">bad value: <xsl:value-of select="r/@v"/></xsl:message>
</xsl:template>
</xsl:stylesheet>
"""
#expect(throws: PureXML.XSLT.XSLTError.terminated("bad value: 7")) {
_ = try transform(style, "<r v=\"7\"/>")
}
}
}