From 69678d31a12ea83ec5a1bcfaa58de2b50ac6e706 Mon Sep 17 00:00:00 2001 From: Mihaela Mihaljevic Date: Tue, 9 Jun 2026 18:31:50 +0200 Subject: [PATCH] feat(xpath): EXSLT common, math, and sets extension functions Add the EXSLT common/math/sets modules, dispatched by resolving a function's prefix to its namespace (FunctionTable.call falls back to namespace lookup), so any prefix bound to an EXSLT namespace works. math:min/max/highest/lowest/ abs/sqrt (with the NaN rule), set:distinct/difference/intersection/ has-same-node/leading/trailing (by node identity and document order), and exsl:object-type. math:power and the transcendentals are omitted (they need a C math library the Foundation-free target excludes); exsl:node-set awaits result-tree-fragment support. Part of #105 (Tier 3) --- CHANGELOG.md | 1 + README.md | 4 +- Sources/XPath/EXSLTFunctions.swift | 122 ++++++++++++++++++++++++++ Sources/XPath/EvaluationContext.swift | 15 +++- Tests/EXSLTTests.swift | 72 +++++++++++++++ 5 files changed, 209 insertions(+), 5 deletions(-) create mode 100644 Sources/XPath/EXSLTFunctions.swift create mode 100644 Tests/EXSLTTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b043ef..fa0a9f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- EXSLT extension functions (#105, Tier 3): the `common`, `math`, and `sets` EXSLT modules, dispatched by resolving a function's prefix to its namespace (so any prefix bound to an EXSLT namespace works). `math:min`, `math:max`, `math:highest`, `math:lowest`, `math:abs`, `math:sqrt` (with the EXSLT NaN rule for non-numeric nodes); `set:distinct`, `set:difference`, `set:intersection`, `set:has-same-node`, `set:leading`, `set:trailing` (by node identity and document order); `exsl:object-type`. `math:power` and the other transcendentals are omitted because they need a C math library, which the pure-Swift, Foundation-free target excludes; `exsl:node-set` awaits result-tree-fragment support. - Canonical XML 1.1 (#105, Tier 3): a `Canonical.Options.canonical11` preset and a `mergeInheritedBase` option. When canonicalizing a document subset, the `xml:base` values of the apex's omitted ancestors are merged into the apex by RFC 3986 reference resolution (vs. 1.0's nearest-ancestor rule), the apex's own relative `xml:base` is resolved against that chain, and `xml:id` is no longer inherited; `xml:lang` and `xml:space` still inherit the nearest. A self-contained RFC 3986 resolver (scheme/authority/path parsing, path merging, dot-segment removal) backs the merge. - Single-byte legacy encodings (#97): the byte decoder gains a table-based single-byte path and the full set of single-byte legacy encodings, selected by the XML declaration's `encoding` name for both the whole-buffer and streaming decoders: the complete ISO-8859 family (parts 2 through 16), Windows-1250/1251/1253/1254/1255/1256/1257/1258, and KOI8-R/U. Most are vendored verbatim from the authoritative `unicode.org` mapping files; ISO-8859-5/9/15 are derived exactly; Windows-1254 composes from Windows-1252. Multi-byte CJK encodings (#99) are tracked separately. diff --git a/README.md b/README.md index c637331..704fa4a 100644 --- a/README.md +++ b/README.md @@ -88,7 +88,7 @@ flowchart TB OutEnc["#106 output encodings: complete"]:::done StreamVal["#107 streaming validation: DTD, RELAX NG, XSD"]:::done MoreEnc["#108 encodings: ISO-2022-JP, EUC-TW"]:::done - Depth["Tier 2 conformance corpora; Tier 3 EXSLT, DTD PE depth (C14N 1.1 done); frontier #104"]:::todo + Depth["Tier 2 conformance corpora; Tier 3 DTD PE depth (C14N 1.1, EXSLT done); frontier #104"]:::todo Epic105 --> OutEnc OutEnc --> StreamVal StreamVal --> MoreEnc @@ -99,7 +99,7 @@ flowchart TB PureXML is a working, dependency-free XML library today: parse, emit, validate, query, and stream documents on macOS, Linux, Windows, and WASM. The test suite -currently runs **795 tests in 122 suites** (`swift test`). +currently runs **801 tests in 123 suites** (`swift test`). ### Shipped (libxml2-aligned surface) diff --git a/Sources/XPath/EXSLTFunctions.swift b/Sources/XPath/EXSLTFunctions.swift new file mode 100644 index 0000000..7aa6337 --- /dev/null +++ b/Sources/XPath/EXSLTFunctions.swift @@ -0,0 +1,122 @@ +extension PureXML.XPath { + /// The EXSLT extension functions (http://exslt.org/...), dispatched by the + /// namespace a function's prefix resolves to: the `math`, `sets`, and the + /// `common` modules. Registered through ``FunctionTable`` so they are + /// available wherever a prefix is bound to an EXSLT namespace. + enum EXSLT { + static let common = "http://exslt.org/common" + static let math = "http://exslt.org/math" + static let sets = "http://exslt.org/sets" + + /// The implementation for an EXSLT `local` name in namespace `uri`, or nil. + static func implementation(uri: String, local: String) -> FunctionImplementation? { + switch uri { + case math: mathFunction(local) + case sets: setsFunction(local) + case common: commonFunction(local) + default: nil + } + } + + // MARK: common + + private static func commonFunction(_ local: String) -> FunctionImplementation? { + guard local == "object-type" else { return nil } + return { arguments, _ in + switch arguments.first { + case .nodeSet: .string("node-set") + case .boolean: .string("boolean") + case .number: .string("number") + case .string, .none: .string("string") + } + } + } + + // MARK: math + + private static func mathFunction(_ local: String) -> FunctionImplementation? { + switch local { + case "min": { arguments, _ in .number(extremum(arguments.first, isMin: true)) } + case "max": { arguments, _ in .number(extremum(arguments.first, isMin: false)) } + case "highest": { arguments, _ in .nodeSet(extremeNodes(arguments.first, isMin: false)) } + case "lowest": { arguments, _ in .nodeSet(extremeNodes(arguments.first, isMin: true)) } + case "abs": { arguments, _ in .number(abs(arguments.first?.number ?? .nan)) } + case "sqrt": { arguments, _ in .number((arguments.first?.number ?? .nan).squareRoot()) } + default: nil + } + } + + /// The minimum or maximum of a node-set's numeric values; NaN for an empty + /// set or any non-numeric node (the EXSLT rule). + private static func extremum(_ value: Value?, isMin: Bool) -> Double { + guard let nodes = value?.nodes, !nodes.isEmpty else { return .nan } + let numbers = nodes.map { PureXML.XPath.Value.parseNumber($0.stringValue) } + if numbers.contains(where: \.isNaN) { return .nan } + return isMin ? numbers.min() ?? .nan : numbers.max() ?? .nan + } + + /// The nodes whose numeric value equals the set's maximum (or minimum), + /// in document order; empty when any value is NaN. + private static func extremeNodes(_ value: Value?, isMin: Bool) -> [Node] { + guard let nodes = value?.nodes, !nodes.isEmpty else { return [] } + let target = extremum(value, isMin: isMin) + guard !target.isNaN else { return [] } + return nodes + .filter { PureXML.XPath.Value.parseNumber($0.stringValue) == target } + .sorted(by: Node.precedes) + } + + // MARK: sets + + private static func setsFunction(_ local: String) -> FunctionImplementation? { + switch local { + case "distinct": { arguments, _ in .nodeSet(distinct(arguments.first)) } + case "difference": { arguments, _ in .nodeSet(difference(arguments)) } + case "intersection": { arguments, _ in .nodeSet(intersection(arguments)) } + case "has-same-node": { arguments, _ in .boolean(hasSameNode(arguments)) } + case "leading": { arguments, _ in .nodeSet(relative(arguments, leading: true)) } + case "trailing": { arguments, _ in .nodeSet(relative(arguments, leading: false)) } + default: nil + } + } + + private static func distinct(_ value: Value?) -> [Node] { + guard let nodes = value?.nodes else { return [] } + var seen: Set = [] + var result: [Node] = [] + for node in nodes.sorted(by: Node.precedes) where seen.insert(node.stringValue).inserted { + result.append(node) + } + return result + } + + private static func difference(_ arguments: [Value]) -> [Node] { + let first = arguments.first?.nodes ?? [] + let second = Set(arguments.count > 1 ? arguments[1].nodes ?? [] : []) + return first.filter { !second.contains($0) }.sorted(by: Node.precedes) + } + + private static func intersection(_ arguments: [Value]) -> [Node] { + let first = arguments.first?.nodes ?? [] + let second = Set(arguments.count > 1 ? arguments[1].nodes ?? [] : []) + return first.filter { second.contains($0) }.sorted(by: Node.precedes) + } + + private static func hasSameNode(_ arguments: [Value]) -> Bool { + let second = Set(arguments.count > 1 ? arguments[1].nodes ?? [] : []) + return (arguments.first?.nodes ?? []).contains { second.contains($0) } + } + + /// `set:leading` / `set:trailing`: the nodes of the first set that precede + /// (or follow) the first node, in document order, of the second set. + private static func relative(_ arguments: [Value], leading: Bool) -> [Node] { + let first = arguments.first?.nodes ?? [] + guard let pivot = (arguments.count > 1 ? arguments[1].nodes ?? [] : []).min(by: Node.precedes) else { + return [] + } + return first + .filter { leading ? Node.precedes($0, pivot) : Node.precedes(pivot, $0) } + .sorted(by: Node.precedes) + } + } +} diff --git a/Sources/XPath/EvaluationContext.swift b/Sources/XPath/EvaluationContext.swift index e5b24e0..387e4ec 100644 --- a/Sources/XPath/EvaluationContext.swift +++ b/Sources/XPath/EvaluationContext.swift @@ -55,10 +55,19 @@ extension PureXML.XPath { } func call(_ name: String, _ arguments: [Value], _ context: EvaluationContext) throws -> Value { - guard let implementation = table[name] else { - throw QueryError.unknownFunction(name) + if let implementation = table[name] { + return try implementation(arguments, context) } - return try implementation(arguments, context) + // A prefixed name may be an EXSLT extension function: resolve the prefix + // to its namespace URI and dispatch by namespace. + if let colon = name.firstIndex(of: ":") { + let prefix = String(name[.. PureXML.XPath.Value { + let document = try PureXML.parseTree(xml) + return try PureXML.XPath.Query(expression).value(at: document, namespaces: namespaces) + } + + @Test("math:min, max, abs, sqrt") + func test_mathScalars() throws { + let numbers = "312" + try #expect(value("math:max(//n)", numbers).number == 3) + try #expect(value("math:min(//n)", numbers).number == 1) + try #expect(value("math:abs(-5)", numbers).number == 5) + try #expect(value("math:sqrt(9)", numbers).number == 3) + // A non-numeric node makes min/max NaN (the EXSLT rule). + try #expect(value("math:max(//n)", "3x").number.isNaN) + } + + @Test("math:highest and math:lowest return the extreme nodes") + func test_mathNodes() throws { + let numbers = "313" + // Two nodes share the maximum value 3. + try #expect(value("math:highest(//n)", numbers).nodes?.count == 2) + try #expect(value("math:lowest(//n)", numbers).nodes?.count == 1) + try #expect(value("math:lowest(//n)", numbers).string == "1") + } + + @Test("set:distinct, difference, intersection, has-same-node") + func test_sets() throws { + let values = "xxy" + try #expect(value("count(set:distinct(//n))", values).number == 2) + let abc = "" + try #expect(value("count(set:difference(//r/*, //b))", abc).number == 2) // a, c + try #expect(value("count(set:intersection(//r/*, //b))", abc).number == 1) // b + try #expect(value("set:has-same-node(//a, //r/*)", abc).boolean == true) + try #expect(value("set:has-same-node(//a, //b)", abc).boolean == false) + } + + @Test("set:leading and set:trailing relative to the first node of the second set") + func test_setsRelative() throws { + let abc = "" + // Of a, b, c, those before b are [a]; those after b are [c]. + try #expect(value("count(set:leading(//r/*, //b))", abc).number == 1) + try #expect(value("count(set:trailing(//r/*, //b))", abc).number == 1) + try #expect(value("local-name(set:trailing(//r/*, //b))", abc).string == "c") + } + + @Test("exsl:object-type reports the value type") + func test_objectType() throws { + let doc = "" + try #expect(value("exsl:object-type(/r)", doc).string == "node-set") + try #expect(value("exsl:object-type(1)", doc).string == "number") + try #expect(value("exsl:object-type('s')", doc).string == "string") + try #expect(value("exsl:object-type(true())", doc).string == "boolean") + } + + @Test("An EXSLT function under an unbound prefix is an unknown function") + func test_unboundPrefix() throws { + #expect(throws: (any Error).self) { + _ = try PureXML.XPath.Query("math:max(//n)").value(at: PureXML.parseTree("1")) + } + } +}