From 1286659c62f6505441e3d6bda497ccd94420b67b Mon Sep 17 00:00:00 2001 From: Mihaela Mihaljevic Date: Mon, 8 Jun 2026 08:01:17 +0200 Subject: [PATCH] feat(xslt): add xsl:key/key(), format-number(), xsl:number, and document() Reach full XSLT 1.0 key, numbering, and document parity: - xsl:key declarations are compiled into an index over the source tree; the key() function looks nodes up by key name and value. - format-number() renders a number against a picture string (digit places, decimal point, grouping, percent), Foundation-free. - xsl:number generates the context node's position rendered as arabic, alphabetic, or roman numerals. - document() resolves an external source through an injected loader so the transform never reaches the filesystem or network by default. These hang off an XPath function-table injection mechanism: the evaluator merges an engine-supplied FunctionTable, letting XSLT register current(), key(), format-number(), and document() per evaluation. Closes #63 --- Sources/XPath/CoreFunctions.swift | 2 +- Sources/XPath/EvaluationContext.swift | 4 +- Sources/XPath/Evaluator.swift | 13 +- Sources/XPath/NodeFunctions.swift | 2 +- Sources/XPath/Query.swift | 24 ++++ Sources/XPath/StringFunctions.swift | 2 +- Sources/XSLT/XSLTFunctions.swift | 185 ++++++++++++++++++++++++++ Sources/XSLT/XSLTModel.swift | 13 +- Sources/XSLT/XSLTParser.swift | 18 ++- Sources/XSLT/XSLTTransformer.swift | 30 ++++- Tests/XSLTTests.swift | 57 ++++++++ 11 files changed, 336 insertions(+), 14 deletions(-) create mode 100644 Sources/XSLT/XSLTFunctions.swift diff --git a/Sources/XPath/CoreFunctions.swift b/Sources/XPath/CoreFunctions.swift index ec6a4ba..124d9cf 100644 --- a/Sources/XPath/CoreFunctions.swift +++ b/Sources/XPath/CoreFunctions.swift @@ -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 diff --git a/Sources/XPath/EvaluationContext.swift b/Sources/XPath/EvaluationContext.swift index 6621445..796d80d 100644 --- a/Sources/XPath/EvaluationContext.swift +++ b/Sources/XPath/EvaluationContext.swift @@ -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] = [:]) { diff --git a/Sources/XPath/Evaluator.swift b/Sources/XPath/Evaluator.swift index c5aba48..ba5985a 100644 --- a/Sources/XPath/Evaluator.swift +++ b/Sources/XPath/Evaluator.swift @@ -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) } diff --git a/Sources/XPath/NodeFunctions.swift b/Sources/XPath/NodeFunctions.swift index 5186259..c7d4e1a 100644 --- a/Sources/XPath/NodeFunctions.swift +++ b/Sources/XPath/NodeFunctions.swift @@ -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 ?? "") }, diff --git a/Sources/XPath/Query.swift b/Sources/XPath/Query.swift index 33c7aed..ff8bf93 100644 --- a/Sources/XPath/Query.swift +++ b/Sources/XPath/Query.swift @@ -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 diff --git a/Sources/XPath/StringFunctions.swift b/Sources/XPath/StringFunctions.swift index 00cd28f..98fa31e 100644 --- a/Sources/XPath/StringFunctions.swift +++ b/Sources/XPath/StringFunctions.swift @@ -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))) diff --git a/Sources/XSLT/XSLTFunctions.swift b/Sources/XSLT/XSLTFunctions.swift new file mode 100644 index 0000000..0a22e16 --- /dev/null +++ b/Sources/XSLT/XSLTFunctions.swift @@ -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 + } + } +} diff --git a/Sources/XSLT/XSLTModel.swift b/Sources/XSLT/XSLTModel.swift index a3876b8..c1ce2b7 100644 --- a/Sources/XSLT/XSLTModel.swift +++ b/Sources/XSLT/XSLTModel.swift @@ -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] } } diff --git a/Sources/XSLT/XSLTParser.swift b/Sources/XSLT/XSLTParser.swift index 47b485a..b086bf5 100644 --- a/Sources/XSLT/XSLTParser.swift +++ b/Sources/XSLT/XSLTParser.swift @@ -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 } diff --git a/Sources/XSLT/XSLTTransformer.swift b/Sources/XSLT/XSLTTransformer.swift index 165a1cd..ba46f89 100644 --- a/Sources/XSLT/XSLTTransformer.swift +++ b/Sources/XSLT/XSLTTransformer.swift @@ -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() } } diff --git a/Tests/XSLTTests.swift b/Tests/XSLTTests.swift index 87078c8..9d29021 100644 --- a/Tests/XSLTTests.swift +++ b/Tests/XSLTTests.swift @@ -60,6 +60,63 @@ struct XSLTTests { #expect(try transform(stylesheet, source) == "
  • A
  • B
  • A

    B

    ") } + @Test("xsl:key indexes nodes and key() retrieves them") + func test_key() throws { + let stylesheet = """ + + + + + + + """ + let source = "applepeapear" + #expect(try transform(stylesheet, source) == "applepear") + } + + @Test("format-number renders per the picture string") + func test_formatNumber() throws { + let stylesheet = """ + + + + + + + + + """ + #expect(try transform(stylesheet, "") == "1,234.5025%") + } + + @Test("xsl:number generates the position of the context node") + func test_number() throws { + let stylesheet = """ + + + + + """ + #expect(try transform(stylesheet, "") == "iiiiii") + } + + @Test("document() loads external source through the injected loader") + func test_document() throws { + let stylesheet = """ + + + + + + """ + let result = try PureXML.XSLT.transform( + stylesheet: stylesheet, + source: "", + documentLoader: { uri in uri == "ext.xml" ? "loaded" : nil }, + ) + #expect(result == "loaded") + } + @Test("The identity transform reproduces the input") func test_identity() throws { let stylesheet = """