feat(xslt): implement xsl:attribute-set and use-attribute-sets

Named attribute sets apply to a literal result element or xsl:element via
use-attribute-sets; sets may include other sets recursively with a cycle
guard, set attributes are lowest precedence so the element's own
attributes override them, and same-named attributes collapse to the last.
Folded across xsl:include/xsl:import. Splits the element-building helpers
into XSLTElements.swift to stay within the file-length budget.
This commit is contained in:
Mihaela Mihaljevic 2026-06-09 01:39:45 +02:00
parent 0a78822845
commit 22cd88f8ba
7 changed files with 169 additions and 21 deletions

View File

@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- XSLT `xsl:attribute-set` (#81). Named attribute sets are applied to a literal
result element or `xsl:element` via `use-attribute-sets`; sets may include other
sets (recursively, with a cycle guard), set attributes are lowest precedence so
the element's own attributes override them, and same-named attributes collapse
to the last. Folded across `xsl:include`/`xsl:import`.
- 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

View File

@ -0,0 +1,31 @@
extension PureXML.XSLT.Transformer {
/// The attributes contributed by `names` and the attribute sets they include,
/// lower precedence first, with a `visiting` guard against recursive includes.
func attributeSetAttributes(_ names: [String], _ context: XSLTContext, visiting: Set<String>) -> [PureXML.Model.Attribute] {
var result: [PureXML.Model.Attribute] = []
for name in names where !visiting.contains(name) {
guard let set = stylesheet.attributeSets[name] else { continue }
result += attributeSetAttributes(set.use, context, visiting: visiting.union([name]))
for item in instantiate(set.attributes, context) {
if case let .attribute(attribute) = item { result.append(attribute) }
}
}
return result
}
/// The attributes with duplicates by name removed, keeping the last (so a
/// later attribute overrides one from an attribute set or an earlier source).
static func deduplicated(_ attributes: [PureXML.Model.Attribute]) -> [PureXML.Model.Attribute] {
var indexByName: [String: Int] = [:]
var result: [PureXML.Model.Attribute] = []
for attribute in attributes {
if let index = indexByName[attribute.name.description] {
result[index] = attribute
} else {
indexByName[attribute.name.description] = result.count
result.append(attribute)
}
}
return result
}
}

View File

@ -38,10 +38,12 @@ public extension PureXML.XSLT {
case ifInstruction(test: String, body: [Instruction])
/// `xsl:choose` with its `when` branches and optional `otherwise`.
case choose(whens: [Branch], otherwise: [Instruction])
/// A literal result element, copied to the output with its attributes.
case literalElement(name: PureXML.Model.QualifiedName, attributes: [LiteralAttribute], body: [Instruction])
/// `xsl:element` whose name is an attribute value template.
case element(name: ValueTemplate, body: [Instruction])
/// A literal result element, copied to the output with its attributes and
/// any `use-attribute-sets`.
case literalElement(name: PureXML.Model.QualifiedName, attributes: [LiteralAttribute], useAttributeSets: [String], body: [Instruction])
/// `xsl:element` whose name is an attribute value template, with any
/// `use-attribute-sets`.
case element(name: ValueTemplate, useAttributeSets: [String], body: [Instruction])
/// `xsl:attribute` whose name is an attribute value template.
case attribute(name: ValueTemplate, body: [Instruction])
/// `xsl:copy`: a shallow copy of the context node.
@ -104,6 +106,18 @@ public extension PureXML.XSLT {
}
}
/// An `xsl:attribute-set`: the `xsl:attribute` instructions it contributes and
/// the other attribute sets it includes (`use-attribute-sets`).
struct AttributeSet: Sendable {
public var attributes: [Instruction]
public var use: [String]
public init(attributes: [Instruction], use: [String]) {
self.attributes = attributes
self.use = use
}
}
/// An `xsl:key` declaration: a name, the nodes it indexes (a match pattern),
/// and the key value of each (a `use` expression).
struct Key: Sendable {
@ -152,6 +166,8 @@ public extension PureXML.XSLT {
public var stripSpace: Set<String>
/// Element name tests that keep their whitespace, overriding `stripSpace`.
public var preserveSpace: Set<String>
/// Named `xsl:attribute-set` declarations, keyed by name.
public var attributeSets: [String: AttributeSet]
public init(
templates: [Template],
@ -160,6 +176,7 @@ public extension PureXML.XSLT {
output: Output,
stripSpace: Set<String> = [],
preserveSpace: Set<String> = [],
attributeSets: [String: AttributeSet] = [:],
) {
self.templates = templates
self.globals = globals
@ -167,6 +184,7 @@ public extension PureXML.XSLT {
self.output = output
self.stripSpace = stripSpace
self.preserveSpace = preserveSpace
self.attributeSets = attributeSets
}
}
}

View File

@ -10,9 +10,18 @@ private struct Parts {
var output = PureXML.XSLT.Output()
var stripSpace: Set<String> = []
var preserveSpace: Set<String> = []
var attributeSets: [String: PureXML.XSLT.AttributeSet] = [:]
var stylesheet: PureXML.XSLT.Stylesheet {
PureXML.XSLT.Stylesheet(templates: templates, globals: globals, keys: keys, output: output, stripSpace: stripSpace, preserveSpace: preserveSpace)
PureXML.XSLT.Stylesheet(
templates: templates,
globals: globals,
keys: keys,
output: output,
stripSpace: stripSpace,
preserveSpace: preserveSpace,
attributeSets: attributeSets,
)
}
/// Folds a sub-stylesheet in: an import has lower precedence, so its globals
@ -23,6 +32,7 @@ private struct Parts {
keys += sub.keys
stripSpace.formUnion(sub.stripSpace)
preserveSpace.formUnion(sub.preserveSpace)
attributeSets.merge(sub.attributeSets) { mine, _ in mine }
globals = isImport ? sub.globals + globals : globals + sub.globals
output = isImport ? sub.output.merged(with: output) : output.merged(with: sub.output)
}
@ -109,12 +119,18 @@ extension PureXML.XSLT {
case "output": parts.output = parts.output.merged(with: parseOutput(child))
case "strip-space": parts.stripSpace.formUnion(elementNames(child))
case "preserve-space": parts.preserveSpace.formUnion(elementNames(child))
case "attribute-set": addAttributeSet(child, into: &parts)
case "include": parts.fold(load(child, loader: loader, precedence: precedence), isImport: false)
case "import": parts.fold(load(child, loader: loader, precedence: precedence - 1), isImport: true)
default: break
}
}
private static func addAttributeSet(_ child: Tree, into parts: inout Parts) {
guard let name = XSLTNode.attribute(child, "name") else { return }
parts.attributeSets[name] = AttributeSet(attributes: body(child), use: useAttributeSets(child))
}
/// The whitespace-separated element name tests of an `xsl:strip-space` or
/// `xsl:preserve-space` element's `elements` attribute.
private static func elementNames(_ node: Tree) -> Set<String> {
@ -243,7 +259,7 @@ extension PureXML.XSLT {
case "choose":
choose(node)
case "element":
.element(name: valueTemplate(XSLTNode.attribute(node, "name") ?? ""), body: body(node))
.element(name: valueTemplate(XSLTNode.attribute(node, "name") ?? ""), useAttributeSets: useAttributeSets(node), body: body(node))
case "attribute":
.attribute(name: valueTemplate(XSLTNode.attribute(node, "name") ?? ""), body: body(node))
case "number":
@ -275,10 +291,17 @@ extension PureXML.XSLT {
private static func literalElement(_ node: Tree) -> Instruction {
guard let name = node.name else { return .literalText("") }
// xmlns declarations and the special xsl:* attributes (use-attribute-sets,
// version, exclude-result-prefixes …) are not copied to the output.
let attributes = node.attributes
.filter { $0.name.prefix != "xmlns" && !($0.name.prefix == nil && $0.name.localName == "xmlns") }
.filter { $0.name.prefix != "xmlns" && !($0.name.prefix == nil && $0.name.localName == "xmlns") && $0.name.prefix != "xsl" }
.map { LiteralAttribute(name: $0.name, value: valueTemplate($0.value)) }
return .literalElement(name: name, attributes: attributes, body: body(node))
return .literalElement(name: name, attributes: attributes, useAttributeSets: useAttributeSets(node), body: body(node))
}
/// The whitespace-separated names of `[xsl:]use-attribute-sets` on `node`.
private static func useAttributeSets(_ node: Tree) -> [String] {
(XSLTNode.attribute(node, "use-attribute-sets") ?? "").split(whereSeparator: \.isWhitespace).map(String.init)
}
private static func sorts(_ node: Tree) -> [Sort] {

View File

@ -1,12 +1,14 @@
/// One produced item: a node for the result tree, or an attribute to attach to
/// the enclosing element. File-scope and private.
private enum ResultItem {
/// the enclosing element. Module-internal so the transformer's helpers can span
/// files.
enum ResultItem {
case node(PureXML.Model.Node)
case attribute(PureXML.Model.Attribute)
}
/// The evaluation context during instantiation. File-scope and private.
private struct XSLTContext {
/// The evaluation context during instantiation. Module-internal so the
/// transformer's helpers can span files.
struct XSLTContext {
var node: PureXML.Model.TreeNode
var position: Int
var size: Int
@ -131,7 +133,7 @@ extension PureXML.XSLT {
// MARK: Instantiation
fileprivate func instantiate(_ body: [Instruction], _ context: XSLTContext) -> [ResultItem] {
func instantiate(_ body: [Instruction], _ context: XSLTContext) -> [ResultItem] {
var items: [ResultItem] = []
var context = context
for instruction in body {
@ -238,10 +240,10 @@ extension PureXML.XSLT.Transformer {
private func structuralEvaluate(_ instruction: PureXML.XSLT.Instruction, _ context: XSLTContext) -> [ResultItem] {
switch instruction {
case let .literalElement(name, attributes, body):
[buildElement(name: name, literalAttributes: attributes, body: body, context)]
case let .element(nameTemplate, body):
[buildElement(name: .init(avt(nameTemplate, context)), literalAttributes: [], body: body, context)]
case let .literalElement(name, attributes, useAttributeSets, body):
[buildElement(name: name, literalAttributes: attributes, useAttributeSets: useAttributeSets, body: body, context)]
case let .element(nameTemplate, useAttributeSets, body):
[buildElement(name: .init(avt(nameTemplate, context)), literalAttributes: [], useAttributeSets: useAttributeSets, body: body, context)]
case let .attribute(nameTemplate, body):
[.attribute(.init(avt(nameTemplate, context), Self.text(of: instantiate(body, context))))]
case let .copy(body):
@ -307,7 +309,7 @@ extension PureXML.XSLT.Transformer {
private func copyInstruction(_ body: [PureXML.XSLT.Instruction], _ context: XSLTContext) -> [ResultItem] {
switch context.node.kind {
case .element:
[buildElement(name: context.node.name ?? .init(""), literalAttributes: [], body: body, context)]
[buildElement(name: context.node.name ?? .init(""), literalAttributes: [], useAttributeSets: [], body: body, context)]
case .text, .cdata:
[.node(.text(context.node.value))]
default:
@ -320,10 +322,15 @@ extension PureXML.XSLT.Transformer {
private func buildElement(
name: PureXML.Model.QualifiedName,
literalAttributes: [PureXML.XSLT.LiteralAttribute],
useAttributeSets: [String],
body: [PureXML.XSLT.Instruction],
_ context: XSLTContext,
) -> ResultItem {
var attributes = literalAttributes.map { PureXML.Model.Attribute(name: $0.name, value: avt($0.value, context)) }
// Attribute sets are lowest precedence, then the element's literal
// attributes, then its xsl:attribute body; a later same-named attribute
// replaces an earlier one.
var attributes = attributeSetAttributes(useAttributeSets, context, visiting: [])
attributes += literalAttributes.map { PureXML.Model.Attribute(name: $0.name, value: avt($0.value, context)) }
var children: [PureXML.Model.Node] = []
for item in instantiate(body, context) {
switch item {
@ -331,7 +338,7 @@ extension PureXML.XSLT.Transformer {
case let .node(node): children.append(node)
}
}
return .node(.element(.init(name: name, attributes: attributes, children: children)))
return .node(.element(.init(name: name, attributes: Self.deduplicated(attributes), children: children)))
}
private func avt(_ template: PureXML.XSLT.ValueTemplate, _ context: XSLTContext) -> String {

View File

@ -0,0 +1,64 @@
@testable import PureXML
import Testing
@Suite("XSLT xsl:attribute-set")
struct XSLTAttributeSetTests {
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("use-attribute-sets applies a named set to a literal element")
func test_literalUseAttributeSets() throws {
let style = """
<xsl:stylesheet version="1.0" \(xsl)>
<xsl:output method="xml" omit-xml-declaration="yes"/>
<xsl:attribute-set name="common">
<xsl:attribute name="class">box</xsl:attribute>
</xsl:attribute-set>
<xsl:template match="/"><div xsl:use-attribute-sets="common"/></xsl:template>
</xsl:stylesheet>
"""
#expect(try transform(style, "<x/>") == "<div class=\"box\"/>")
}
@Test("An element's own attribute overrides one from the attribute set")
func test_ownOverrides() throws {
let style = """
<xsl:stylesheet version="1.0" \(xsl)>
<xsl:output method="xml" omit-xml-declaration="yes"/>
<xsl:attribute-set name="s"><xsl:attribute name="class">base</xsl:attribute></xsl:attribute-set>
<xsl:template match="/"><div xsl:use-attribute-sets="s" class="override"/></xsl:template>
</xsl:stylesheet>
"""
#expect(try transform(style, "<x/>") == "<div class=\"override\"/>")
}
@Test("xsl:element honors use-attribute-sets")
func test_xslElement() throws {
let style = """
<xsl:stylesheet version="1.0" \(xsl)>
<xsl:output method="xml" omit-xml-declaration="yes"/>
<xsl:attribute-set name="s"><xsl:attribute name="id">1</xsl:attribute></xsl:attribute-set>
<xsl:template match="/"><xsl:element name="p" use-attribute-sets="s"/></xsl:template>
</xsl:stylesheet>
"""
#expect(try transform(style, "<x/>") == "<p id=\"1\"/>")
}
@Test("An attribute set may include another set")
func test_nestedSets() throws {
let style = """
<xsl:stylesheet version="1.0" \(xsl)>
<xsl:output method="xml" omit-xml-declaration="yes"/>
<xsl:attribute-set name="a"><xsl:attribute name="a">1</xsl:attribute></xsl:attribute-set>
<xsl:attribute-set name="b" use-attribute-sets="a"><xsl:attribute name="b">2</xsl:attribute></xsl:attribute-set>
<xsl:template match="/"><x xsl:use-attribute-sets="b"/></xsl:template>
</xsl:stylesheet>
"""
let out = try transform(style, "<x/>")
#expect(out.contains("a=\"1\""))
#expect(out.contains("b=\"2\""))
}
}

View File

@ -37,7 +37,7 @@ struct XSLTParserTests {
@Test("A literal result element carries its children and apply-templates")
func test_literalElement() throws {
let sheet = try PureXML.XSLT.XSLTParser.parse(stylesheet)
guard case let .literalElement(name, _, body) = sheet.templates[0].body.first else {
guard case let .literalElement(name, _, _, body) = sheet.templates[0].body.first else {
Issue.record("expected a literal element")
return
}