Merge epic/63-xslt-keys: xsl:key, format-number, xsl:number, document()

This commit is contained in:
Mihaela Mihaljevic 2026-06-08 08:01:30 +02:00
commit 8350b13896
11 changed files with 336 additions and 14 deletions

View File

@ -4,7 +4,7 @@ extension PureXML.XPath {
/// and `string`. The broader library (string, node, and number functions)
/// extends this table.
enum CoreFunctions {
static let table = FunctionTable([
nonisolated(unsafe) static let table = FunctionTable([
"last": { _, context in .number(Double(context.size)) },
"position": { _, context in .number(Double(context.position)) },
"count": { arguments, _ in

View File

@ -1,7 +1,7 @@
extension PureXML.XPath {
/// One XPath function: it receives its already-evaluated argument values and
/// the evaluation context, and returns a value.
typealias FunctionImplementation = @Sendable (_ arguments: [Value], _ context: EvaluationContext) throws -> Value
typealias FunctionImplementation = (_ arguments: [Value], _ context: EvaluationContext) throws -> Value
/// The evaluation context an expression is evaluated against: the context
/// node, its position and size within the current node-set, the variable
@ -29,7 +29,7 @@ extension PureXML.XPath {
/// The XPath function library: a name-to-implementation table. The core set is
/// built in; further functions extend it.
struct FunctionTable: Sendable {
struct FunctionTable {
private var table: [String: FunctionImplementation]
init(_ table: [String: FunctionImplementation] = [:]) {

View File

@ -5,7 +5,7 @@ extension PureXML.XPath {
enum Evaluator {
/// The full XPath 1.0 function library: the core functions plus the
/// string, node, and number families.
static let library = CoreFunctions.table
nonisolated(unsafe) static let library = CoreFunctions.table
.merging(StringFunctions.table)
.merging(NodeFunctions.table)
@ -32,13 +32,17 @@ extension PureXML.XPath {
/// Evaluates a node-set expression against a pre-built tree and returns the
/// matched tree nodes in document order (attribute and namespace results
/// are dropped). Lets a caller build the tree once and query it repeatedly.
static func nodes(_ expression: Expression, over root: PureXML.Model.TreeNode) -> [PureXML.Model.TreeNode] {
static func nodes(
_ expression: Expression,
over root: PureXML.Model.TreeNode,
functions: FunctionTable = FunctionTable(),
) -> [PureXML.Model.TreeNode] {
let context = EvaluationContext(
node: .tree(root),
position: 1,
size: 1,
variables: [:],
functions: library,
functions: library.merging(functions),
)
guard let value = try? eval(expression, context), case let .nodeSet(nodes) = value else {
return []
@ -55,13 +59,14 @@ extension PureXML.XPath {
position: Int,
size: Int,
variables: [String: Value],
functions: FunctionTable = FunctionTable(),
) throws -> Value {
let context = EvaluationContext(
node: .tree(node),
position: position,
size: size,
variables: variables,
functions: library,
functions: library.merging(functions),
)
return try eval(expression, context)
}

View File

@ -7,7 +7,7 @@ extension PureXML.XPath {
/// ID, so `id()` matches elements by an attribute named `id` or `xml:id`, the
/// near-universal convention.
enum NodeFunctions {
static let table = FunctionTable([
nonisolated(unsafe) static let table = FunctionTable([
"local-name": { arguments, context in .string(named(arguments, context)?.localName ?? "") },
"name": { arguments, context in .string(named(arguments, context)?.description ?? "") },
"namespace-uri": { arguments, context in .string(named(arguments, context)?.namespaceURI ?? "") },

View File

@ -60,6 +60,30 @@ public extension PureXML.XPath {
try Evaluator.value(expression, at: node, position: position, size: size, variables: variables)
}
/// Like ``value(at:position:size:variables:)`` but with an extra function
/// table merged in (for engine-specific functions such as XSLT's `key`).
func value(
at node: PureXML.Model.TreeNode,
position: Int,
size: Int,
variables: [String: Value],
functions: FunctionTable,
) throws -> Value {
try Evaluator.value(
expression,
at: node,
position: position,
size: size,
variables: variables,
functions: functions,
)
}
/// Like ``nodes(over:)`` but with an extra function table merged in.
func nodes(over root: PureXML.Model.TreeNode, functions: FunctionTable) -> [PureXML.Model.TreeNode] {
Evaluator.nodes(expression, over: root, functions: functions)
}
/// Evaluates the query and coerces the result to a number.
public func number(over node: PureXML.Model.Node, variables: [String: Value] = [:]) throws -> Double {
try value(over: node, variables: variables).number

View File

@ -3,7 +3,7 @@ extension PureXML.XPath {
/// `substring-before`, `substring-after`, `substring`, `string-length`,
/// `normalize-space`, and `translate`.
enum StringFunctions {
static let table = FunctionTable([
nonisolated(unsafe) static let table = FunctionTable([
"concat": { arguments, _ in .string(arguments.map(\.string).joined()) },
"starts-with": { arguments, _ in
.boolean(argument(arguments, 0).hasPrefix(argument(arguments, 1)))

View File

@ -0,0 +1,185 @@
extension PureXML.XSLT {
/// The XSLT `format-number` function over the default decimal format. Supports
/// `0`/`#` digit places, `.` for the decimal point, `,` grouping, and a `%`
/// percent suffix. Pure Swift, no Foundation.
enum FormatNumber {
static func format(_ value: Double, _ picture: String) -> String {
guard !value.isNaN else { return "NaN" }
guard !picture.isEmpty else { return PureXML.XPath.Value.format(value) }
let percent = picture.contains("%")
let pattern = picture.filter { $0 != "%" }
let parts = pattern.split(separator: ".", maxSplits: 1, omittingEmptySubsequences: false)
let integerPattern = String(parts.first ?? "")
let fractionPattern = parts.count > 1 ? String(parts[1]) : ""
let minInteger = integerPattern.count(where: { $0 == "0" })
let minFraction = fractionPattern.count(where: { $0 == "0" })
let maxFraction = fractionPattern.count(where: { $0 == "0" || $0 == "#" })
let grouping = integerPattern.contains(",")
var magnitude = Swift.abs(percent ? value * 100 : value)
magnitude = round(magnitude, places: maxFraction)
let rendered = render(
magnitude,
minInteger: minInteger,
minFraction: minFraction,
maxFraction: maxFraction,
grouping: grouping,
)
return (value < 0 ? "-" : "") + rendered + (percent ? "%" : "")
}
private static func round(_ value: Double, places: Int) -> Double {
var scale = 1.0
for _ in 0 ..< places {
scale *= 10
}
return (value * scale).rounded() / scale
}
private static func render(
_ value: Double,
minInteger: Int,
minFraction: Int,
maxFraction: Int,
grouping: Bool,
) -> String {
let integerValue = Int(value)
var integerText = String(integerValue)
while integerText.count < Swift.max(1, minInteger) {
integerText = "0" + integerText
}
if grouping { integerText = group(integerText) }
var fractionValue = value - Double(integerValue)
var fractionText = ""
for _ in 0 ..< maxFraction {
fractionValue *= 10
let digit = Int(fractionValue)
fractionText += String(digit)
fractionValue -= Double(digit)
}
while fractionText.count > minFraction, fractionText.hasSuffix("0") {
fractionText.removeLast()
}
return fractionText.isEmpty ? integerText : integerText + "." + fractionText
}
private static func group(_ digits: String) -> String {
var result = ""
for (offset, character) in digits.reversed().enumerated() {
if offset > 0, offset.isMultiple(of: 3) { result.append(",") }
result.append(character)
}
return String(result.reversed())
}
}
/// The `xsl:key` index: each key name maps a key value to the nodes indexed
/// under it.
typealias KeyIndex = [String: [String: [PureXML.Model.TreeNode]]]
/// The XSLT extensions to the XPath function library: `current`, `key`,
/// `format-number`, and `document`, plus the `xsl:key` index they read.
enum Library {
/// The XSLT functions for an evaluation whose current node is `current`,
/// reading the prebuilt `keys` index and the injected `document` loader.
static func table(
current: PureXML.Model.TreeNode,
keys: KeyIndex,
loader: @escaping (String) -> String?,
) -> PureXML.XPath.FunctionTable {
PureXML.XPath.FunctionTable()
.adding("current") { _, _ in .nodeSet([.tree(current)]) }
.adding("format-number") { arguments, _ in
.string(FormatNumber.format(
arguments.first?.number ?? .nan,
arguments.count > 1 ? arguments[1].string : "",
))
}
.adding("key") { arguments, _ in
let name = arguments.first?.string ?? ""
let value = arguments.count > 1 ? arguments[1].string : ""
return .nodeSet((keys[name]?[value] ?? []).map { .tree($0) })
}
.adding("document") { arguments, _ in
guard let uri = arguments.first?.string, let text = loader(uri),
let parsed = try? PureXML.parseTree(text) else { return .nodeSet([]) }
return .nodeSet([.tree(parsed)])
}
}
/// Builds the `xsl:key` index: each declared key maps every node matching
/// its pattern to its `use` value.
static func buildKeyIndex(stylesheet: Stylesheet, root: PureXML.Model.TreeNode) -> KeyIndex {
var index: KeyIndex = [:]
for key in stylesheet.keys {
let path = key.match.hasPrefix("/") ? key.match : "//" + key.match
guard let matchQuery = try? PureXML.XPath.Query(path),
let useQuery = try? PureXML.XPath.Query(key.use) else { continue }
for node in matchQuery.nodes(over: root) {
let value = (try? useQuery.value(at: node).string) ?? ""
index[key.name, default: [:]][value, default: []].append(node)
}
}
return index
}
}
/// The `xsl:number` numbering machinery: a node's position rendered per a
/// format token (`1` arabic, `A`/`a` alphabetic, `I`/`i` roman).
enum Numbering {
/// The number for `node`: its 1-based position among preceding siblings of
/// the same name (or the `count` name), rendered per `format`.
static func value(of node: PureXML.Model.TreeNode, count: String?, format: String) -> String {
let target = count ?? node.name?.localName
var position = 1
if let parent = node.parent {
for sibling in parent.children {
if sibling === node { break }
if sibling.kind == .element, sibling.name?.localName == target { position += 1 }
}
}
return render(position, format)
}
private static func render(_ number: Int, _ format: String) -> String {
switch format.first {
case "A": alphabetic(number, base: 65)
case "a": alphabetic(number, base: 97)
case "I": roman(number).uppercased()
case "i": roman(number)
default: String(number)
}
}
private static func alphabetic(_ number: Int, base: UInt32) -> String {
var value = number
var result = ""
while value > 0 {
let remainder = UInt32((value - 1) % 26)
if let scalar = Unicode.Scalar(base + remainder) {
result = String(Character(scalar)) + result
}
value = (value - 1) / 26
}
return result
}
private static func roman(_ number: Int) -> String {
let table: [(Int, String)] = [
(1000, "m"), (900, "cm"), (500, "d"), (400, "cd"), (100, "c"), (90, "xc"),
(50, "l"), (40, "xl"), (10, "x"), (9, "ix"), (5, "v"), (4, "iv"), (1, "i"),
]
var value = number
var result = ""
for (amount, numeral) in table {
while value >= amount {
result += numeral
value -= amount
}
}
return result
}
}
}

View File

@ -52,6 +52,16 @@ public extension PureXML.XSLT {
case callTemplate(name: String, parameters: [Binding])
/// `xsl:variable` bound for the rest of the sequence constructor.
case variable(name: String, select: String?, body: [Instruction])
/// `xsl:number`: a generated sequence number for the context node.
case number(count: String?, from: String?, format: String)
}
/// 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 {
public var name: String
public var match: String
public var use: String
}
/// One `xsl:when` branch of a choose.
@ -79,9 +89,10 @@ public extension PureXML.XSLT {
public var body: [Instruction]
}
/// A compiled stylesheet: its template rules and global variables.
/// A compiled stylesheet: its template rules, global variables, and keys.
struct Stylesheet: Sendable {
public var templates: [Template]
public var globals: [Instruction]
public var keys: [Key]
}
}

View File

@ -53,14 +53,24 @@ extension PureXML.XSLT {
}
var templates: [Template] = []
var globals: [Instruction] = []
var keys: [Key] = []
for child in XSLTNode.elementChildren(top) where XSLTNode.isXSL(child) {
switch XSLTNode.localName(child) {
case "template": templates.append(template(child))
case "variable", "param": globals.append(variable(child))
case "key": keys.append(key(child))
default: break
}
}
return Stylesheet(templates: templates, globals: globals)
return Stylesheet(templates: templates, globals: globals, keys: keys)
}
private static func key(_ node: Tree) -> Key {
Key(
name: XSLTNode.attribute(node, "name") ?? "",
match: XSLTNode.attribute(node, "match") ?? "",
use: XSLTNode.attribute(node, "use") ?? ".",
)
}
// MARK: Templates
@ -158,6 +168,12 @@ extension PureXML.XSLT {
.element(name: valueTemplate(XSLTNode.attribute(node, "name") ?? ""), body: body(node))
case "attribute":
.attribute(name: valueTemplate(XSLTNode.attribute(node, "name") ?? ""), body: body(node))
case "number":
.number(
count: XSLTNode.attribute(node, "count"),
from: XSLTNode.attribute(node, "from"),
format: XSLTNode.attribute(node, "format") ?? "1",
)
default:
nil
}

View File

@ -21,6 +21,15 @@ extension PureXML.XSLT {
struct Transformer {
let stylesheet: Stylesheet
let root: PureXML.Model.TreeNode
let documentLoader: (String) -> String?
private let keyIndex: PureXML.XSLT.KeyIndex
init(stylesheet: Stylesheet, root: PureXML.Model.TreeNode, documentLoader: @escaping (String) -> String? = { _ in nil }) {
self.stylesheet = stylesheet
self.root = root
self.documentLoader = documentLoader
keyIndex = PureXML.XSLT.Library.buildKeyIndex(stylesheet: stylesheet, root: root)
}
fileprivate func run() -> PureXML.Model.Node {
var variables: [String: PureXML.XPath.Value] = [:]
@ -133,6 +142,7 @@ extension PureXML.XSLT {
position: context.position,
size: context.size,
variables: context.variables,
functions: PureXML.XSLT.Library.table(current: context.node, keys: keyIndex, loader: documentLoader),
)
}
@ -210,6 +220,8 @@ extension PureXML.XSLT.Transformer {
[.attribute(.init(avt(nameTemplate, context), Self.text(of: instantiate(body, context))))]
case let .copy(body):
copyInstruction(body, context)
case let .number(count, _, format):
[.node(.text(PureXML.XSLT.Numbering.value(of: context.node, count: count, format: format)))]
default:
[]
}
@ -334,18 +346,30 @@ extension PureXML.XSLT.Transformer {
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 {
try PureXML.serialize(transformToNode(stylesheet: stylesheet, source: source), options: options)
try PureXML.serialize(
transformToNode(stylesheet: stylesheet, source: source, documentLoader: documentLoader),
options: options,
)
}
/// Transforms `source` with `stylesheet`, returning the result tree.
static func transformToNode(stylesheet: String, source: String) throws -> PureXML.Model.Node {
static func transformToNode(
stylesheet: String,
source: String,
documentLoader: @escaping (String) -> String? = { _ in nil },
) throws -> PureXML.Model.Node {
let sheet = try XSLTParser.parse(stylesheet)
let root = try PureXML.parseTree(source)
return Transformer(stylesheet: sheet, root: root).run()
return Transformer(stylesheet: sheet, root: root, documentLoader: documentLoader).run()
}
}

View File

@ -60,6 +60,63 @@ struct XSLTTests {
#expect(try transform(stylesheet, source) == "<toc><li>A</li><li>B</li></toc><body><h1>A</h1><h1>B</h1></body>")
}
@Test("xsl:key indexes nodes and key() retrieves them")
func test_key() throws {
let stylesheet = """
<xsl:stylesheet \(xsl)>
<xsl:key name="byCat" match="item" use="@cat"/>
<xsl:template match="/">
<out><xsl:for-each select="key('byCat', 'fruit')"><n><xsl:value-of select="."/></n></xsl:for-each></out>
</xsl:template>
</xsl:stylesheet>
"""
let source = "<r><item cat=\"fruit\">apple</item><item cat=\"veg\">pea</item><item cat=\"fruit\">pear</item></r>"
#expect(try transform(stylesheet, source) == "<out><n>apple</n><n>pear</n></out>")
}
@Test("format-number renders per the picture string")
func test_formatNumber() throws {
let stylesheet = """
<xsl:stylesheet \(xsl)>
<xsl:template match="/">
<out>
<a><xsl:value-of select="format-number(1234.5, '#,##0.00')"/></a>
<b><xsl:value-of select="format-number(0.25, '0%')"/></b>
</out>
</xsl:template>
</xsl:stylesheet>
"""
#expect(try transform(stylesheet, "<x/>") == "<out><a>1,234.50</a><b>25%</b></out>")
}
@Test("xsl:number generates the position of the context node")
func test_number() throws {
let stylesheet = """
<xsl:stylesheet \(xsl)>
<xsl:template match="/"><out><xsl:apply-templates select="r/i"/></out></xsl:template>
<xsl:template match="i"><n><xsl:number format="i"/></n></xsl:template>
</xsl:stylesheet>
"""
#expect(try transform(stylesheet, "<r><i/><i/><i/></r>") == "<out><n>i</n><n>ii</n><n>iii</n></out>")
}
@Test("document() loads external source through the injected loader")
func test_document() throws {
let stylesheet = """
<xsl:stylesheet \(xsl)>
<xsl:template match="/">
<out><xsl:value-of select="document('ext.xml')/data/v"/></out>
</xsl:template>
</xsl:stylesheet>
"""
let result = try PureXML.XSLT.transform(
stylesheet: stylesheet,
source: "<x/>",
documentLoader: { uri in uri == "ext.xml" ? "<data><v>loaded</v></data>" : nil },
)
#expect(result == "<out>loaded</out>")
}
@Test("The identity transform reproduces the input")
func test_identity() throws {
let stylesheet = """