feat(xslt): implement xsl:decimal-format for format-number
format-number now honors named and default decimal formats: the decimal separator, grouping separator, percent, minus sign, zero-digit (for non-Latin digit sets), NaN, and infinity symbols come from the chosen xsl:decimal-format, in both the picture and the output. FormatNumber is parameterized over the symbol set and the formats thread through the function table; folded across include/import.
This commit is contained in:
parent
2f79be18e1
commit
2d2572e265
@ -9,6 +9,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Added
|
||||
|
||||
- XSLT `xsl:decimal-format` (#81). `format-number` now honors named and default
|
||||
decimal formats: the decimal separator, grouping separator, percent, minus
|
||||
sign, zero-digit (so non-Latin digit sets render), NaN, and infinity symbols
|
||||
are taken from the chosen `xsl:decimal-format`, both in the picture and the
|
||||
output. Folded across `xsl:include`/`xsl:import`.
|
||||
- XSLT `xsl:fallback` (#81). An unrecognized XSLT element instantiates its
|
||||
`xsl:fallback` children in its place (forwards-compatible processing), or is
|
||||
dropped when it has none; a fallback under a supported instruction is ignored.
|
||||
|
||||
@ -1,32 +1,39 @@
|
||||
private typealias DecimalFormat = PureXML.XSLT.DecimalFormat
|
||||
|
||||
/// The digit-place counts and grouping derived from a format-number picture.
|
||||
/// File scope and private.
|
||||
private struct NumberLayout {
|
||||
let minInteger: Int
|
||||
let minFraction: Int
|
||||
let maxFraction: Int
|
||||
let grouping: Bool
|
||||
}
|
||||
|
||||
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.
|
||||
/// The XSLT `format-number` function. Supports `0`/`#` digit places, the
|
||||
/// decimal point, grouping, and a percent suffix, honoring the symbols of the
|
||||
/// chosen `xsl:decimal-format`. Pure Swift, no Foundation.
|
||||
enum FormatNumber {
|
||||
static func format(_ value: Double, _ picture: String) -> String {
|
||||
guard !value.isNaN else { return "NaN" }
|
||||
static func format(_ value: Double, _ picture: String, _ symbols: DecimalFormat = DecimalFormat()) -> String {
|
||||
guard !value.isNaN else { return symbols.notANumber }
|
||||
if value.isInfinite { return (value < 0 ? String(symbols.minusSign) : "") + symbols.infinity }
|
||||
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 percent = picture.contains(symbols.percent)
|
||||
let pattern = picture.filter { $0 != symbols.percent }
|
||||
let parts = pattern.split(separator: symbols.decimalSeparator, 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(",")
|
||||
let minInteger = integerPattern.count(where: { $0 == symbols.zeroDigit })
|
||||
let minFraction = fractionPattern.count(where: { $0 == symbols.zeroDigit })
|
||||
let maxFraction = fractionPattern.count(where: { $0 == symbols.zeroDigit || $0 == symbols.digit })
|
||||
let grouping = integerPattern.contains(symbols.groupingSeparator)
|
||||
|
||||
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 ? "%" : "")
|
||||
let layout = NumberLayout(minInteger: minInteger, minFraction: minFraction, maxFraction: maxFraction, grouping: grouping)
|
||||
let rendered = render(magnitude, layout, symbols)
|
||||
return (value < 0 ? String(symbols.minusSign) : "") + rendered + (percent ? String(symbols.percent) : "")
|
||||
}
|
||||
|
||||
private static func round(_ value: Double, places: Int) -> Double {
|
||||
@ -37,38 +44,43 @@ extension PureXML.XSLT {
|
||||
return (value * scale).rounded() / scale
|
||||
}
|
||||
|
||||
private static func render(
|
||||
_ value: Double,
|
||||
minInteger: Int,
|
||||
minFraction: Int,
|
||||
maxFraction: Int,
|
||||
grouping: Bool,
|
||||
) -> String {
|
||||
private static func render(_ value: Double, _ layout: NumberLayout, _ symbols: DecimalFormat) -> String {
|
||||
let integerValue = Int(value)
|
||||
var integerText = String(integerValue)
|
||||
while integerText.count < Swift.max(1, minInteger) {
|
||||
integerText = "0" + integerText
|
||||
var integerDigits = String(integerValue)
|
||||
while integerDigits.count < Swift.max(1, layout.minInteger) {
|
||||
integerDigits = "0" + integerDigits
|
||||
}
|
||||
if grouping { integerText = group(integerText) }
|
||||
var integerText = digitsToSymbols(integerDigits, symbols)
|
||||
if layout.grouping { integerText = group(integerText, symbols.groupingSeparator) }
|
||||
|
||||
var fractionValue = value - Double(integerValue)
|
||||
var fractionText = ""
|
||||
for _ in 0 ..< maxFraction {
|
||||
var fractionDigits = ""
|
||||
for _ in 0 ..< layout.maxFraction {
|
||||
fractionValue *= 10
|
||||
let digit = Int(fractionValue)
|
||||
fractionText += String(digit)
|
||||
fractionDigits += String(digit)
|
||||
fractionValue -= Double(digit)
|
||||
}
|
||||
while fractionText.count > minFraction, fractionText.hasSuffix("0") {
|
||||
fractionText.removeLast()
|
||||
while fractionDigits.count > layout.minFraction, fractionDigits.hasSuffix("0") {
|
||||
fractionDigits.removeLast()
|
||||
}
|
||||
return fractionText.isEmpty ? integerText : integerText + "." + fractionText
|
||||
let fractionText = digitsToSymbols(fractionDigits, symbols)
|
||||
return fractionText.isEmpty ? integerText : integerText + String(symbols.decimalSeparator) + fractionText
|
||||
}
|
||||
|
||||
private static func group(_ digits: String) -> String {
|
||||
/// Maps ASCII digits to the format's digit set, offset from its zero-digit.
|
||||
private static func digitsToSymbols(_ digits: String, _ symbols: DecimalFormat) -> String {
|
||||
guard symbols.zeroDigit != "0", let zero = symbols.zeroDigit.unicodeScalars.first else { return digits }
|
||||
return String(digits.map { character in
|
||||
guard let value = character.wholeNumberValue, let scalar = Unicode.Scalar(zero.value + UInt32(value)) else { return character }
|
||||
return Character(scalar)
|
||||
})
|
||||
}
|
||||
|
||||
private static func group(_ digits: String, _ separator: Character) -> String {
|
||||
var result = ""
|
||||
for (offset, character) in digits.reversed().enumerated() {
|
||||
if offset > 0, offset.isMultiple(of: 3) { result.append(",") }
|
||||
if offset > 0, offset.isMultiple(of: 3) { result.append(separator) }
|
||||
result.append(character)
|
||||
}
|
||||
return String(result.reversed())
|
||||
@ -88,13 +100,16 @@ extension PureXML.XSLT {
|
||||
current: PureXML.Model.TreeNode,
|
||||
keys: KeyIndex,
|
||||
loader: @escaping (String) -> String?,
|
||||
decimalFormats: [String: PureXML.XSLT.DecimalFormat] = [:],
|
||||
) -> PureXML.XPath.FunctionTable {
|
||||
PureXML.XPath.FunctionTable()
|
||||
.adding("current") { _, _ in .nodeSet([.tree(current)]) }
|
||||
.adding("format-number") { arguments, _ in
|
||||
.string(FormatNumber.format(
|
||||
let name = arguments.count > 2 ? arguments[2].string : ""
|
||||
return .string(FormatNumber.format(
|
||||
arguments.first?.number ?? .nan,
|
||||
arguments.count > 1 ? arguments[1].string : "",
|
||||
decimalFormats[name] ?? PureXML.XSLT.DecimalFormat(),
|
||||
))
|
||||
}
|
||||
.adding("key") { arguments, _ in
|
||||
|
||||
@ -112,6 +112,23 @@ public extension PureXML.XSLT {
|
||||
}
|
||||
}
|
||||
|
||||
/// The symbols an `xsl:decimal-format` sets for `format-number`: those used in
|
||||
/// the picture (digit places, separators, percent) and in the output. The
|
||||
/// defaults are the XSLT standard format.
|
||||
struct DecimalFormat: Sendable {
|
||||
public var decimalSeparator: Character = "."
|
||||
public var groupingSeparator: Character = ","
|
||||
public var percent: Character = "%"
|
||||
public var zeroDigit: Character = "0"
|
||||
public var digit: Character = "#"
|
||||
public var patternSeparator: Character = ";"
|
||||
public var minusSign: Character = "-"
|
||||
public var infinity: String = "Infinity"
|
||||
public var notANumber: String = "NaN"
|
||||
|
||||
public init() {}
|
||||
}
|
||||
|
||||
/// An `xsl:attribute-set`: the `xsl:attribute` instructions it contributes and
|
||||
/// the other attribute sets it includes (`use-attribute-sets`).
|
||||
struct AttributeSet: Sendable {
|
||||
@ -174,6 +191,9 @@ public extension PureXML.XSLT {
|
||||
public var preserveSpace: Set<String>
|
||||
/// Named `xsl:attribute-set` declarations, keyed by name.
|
||||
public var attributeSets: [String: AttributeSet]
|
||||
/// `xsl:decimal-format` declarations for `format-number`, keyed by name; the
|
||||
/// empty key is the default (unnamed) format.
|
||||
public var decimalFormats: [String: DecimalFormat]
|
||||
|
||||
public init(
|
||||
templates: [Template],
|
||||
@ -183,6 +203,7 @@ public extension PureXML.XSLT {
|
||||
stripSpace: Set<String> = [],
|
||||
preserveSpace: Set<String> = [],
|
||||
attributeSets: [String: AttributeSet] = [:],
|
||||
decimalFormats: [String: DecimalFormat] = [:],
|
||||
) {
|
||||
self.templates = templates
|
||||
self.globals = globals
|
||||
@ -191,6 +212,7 @@ public extension PureXML.XSLT {
|
||||
self.stripSpace = stripSpace
|
||||
self.preserveSpace = preserveSpace
|
||||
self.attributeSets = attributeSets
|
||||
self.decimalFormats = decimalFormats
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -11,6 +11,7 @@ private struct Parts {
|
||||
var stripSpace: Set<String> = []
|
||||
var preserveSpace: Set<String> = []
|
||||
var attributeSets: [String: PureXML.XSLT.AttributeSet] = [:]
|
||||
var decimalFormats: [String: PureXML.XSLT.DecimalFormat] = [:]
|
||||
|
||||
var stylesheet: PureXML.XSLT.Stylesheet {
|
||||
PureXML.XSLT.Stylesheet(
|
||||
@ -21,6 +22,7 @@ private struct Parts {
|
||||
stripSpace: stripSpace,
|
||||
preserveSpace: preserveSpace,
|
||||
attributeSets: attributeSets,
|
||||
decimalFormats: decimalFormats,
|
||||
)
|
||||
}
|
||||
|
||||
@ -33,6 +35,7 @@ private struct Parts {
|
||||
stripSpace.formUnion(sub.stripSpace)
|
||||
preserveSpace.formUnion(sub.preserveSpace)
|
||||
attributeSets.merge(sub.attributeSets) { mine, _ in mine }
|
||||
decimalFormats.merge(sub.decimalFormats) { mine, _ in mine }
|
||||
globals = isImport ? sub.globals + globals : globals + sub.globals
|
||||
output = isImport ? sub.output.merged(with: output) : output.merged(with: sub.output)
|
||||
}
|
||||
@ -112,6 +115,17 @@ extension PureXML.XSLT {
|
||||
}
|
||||
|
||||
private static func absorb(_ child: Tree, into parts: inout Parts, loader: (String) -> String?, precedence: Int) {
|
||||
if absorbDeclaration(child, into: &parts, precedence: precedence) { return }
|
||||
switch XSLTNode.localName(child) {
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// Absorbs a non-composition top-level declaration, returning whether it
|
||||
/// was one (so the caller can then try `include`/`import`).
|
||||
private static func absorbDeclaration(_ child: Tree, into parts: inout Parts, precedence: Int) -> Bool {
|
||||
switch XSLTNode.localName(child) {
|
||||
case "template": parts.templates.append(template(child, precedence: precedence))
|
||||
case "variable", "param": parts.globals.append(variable(child))
|
||||
@ -120,15 +134,10 @@ extension PureXML.XSLT {
|
||||
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
|
||||
case "decimal-format": parts.decimalFormats[XSLTNode.attribute(child, "name") ?? ""] = decimalFormat(child)
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
|
||||
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))
|
||||
return true
|
||||
}
|
||||
|
||||
/// The whitespace-separated element name tests of an `xsl:strip-space` or
|
||||
@ -360,3 +369,31 @@ extension PureXML.XSLT {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Top-level declaration helpers for ``XSLTParser``, kept in an extension so the
|
||||
/// parser enum stays within the type-body length budget.
|
||||
private extension PureXML.XSLT.XSLTParser {
|
||||
static func addAttributeSet(_ child: Tree, into parts: inout Parts) {
|
||||
guard let name = XSLTNode.attribute(child, "name") else { return }
|
||||
parts.attributeSets[name] = PureXML.XSLT.AttributeSet(attributes: body(child), use: useAttributeSets(child))
|
||||
}
|
||||
|
||||
/// Reads an `xsl:decimal-format`'s symbol overrides; each unset attribute
|
||||
/// keeps the XSLT standard default.
|
||||
static func decimalFormat(_ node: Tree) -> PureXML.XSLT.DecimalFormat {
|
||||
var format = PureXML.XSLT.DecimalFormat()
|
||||
func char(_ name: String, _ keyPath: WritableKeyPath<PureXML.XSLT.DecimalFormat, Character>) {
|
||||
if let value = XSLTNode.attribute(node, name)?.first { format[keyPath: keyPath] = value }
|
||||
}
|
||||
char("decimal-separator", \.decimalSeparator)
|
||||
char("grouping-separator", \.groupingSeparator)
|
||||
char("percent", \.percent)
|
||||
char("zero-digit", \.zeroDigit)
|
||||
char("digit", \.digit)
|
||||
char("pattern-separator", \.patternSeparator)
|
||||
char("minus-sign", \.minusSign)
|
||||
if let infinity = XSLTNode.attribute(node, "infinity") { format.infinity = infinity }
|
||||
if let notANumber = XSLTNode.attribute(node, "NaN") { format.notANumber = notANumber }
|
||||
return format
|
||||
}
|
||||
}
|
||||
|
||||
@ -147,7 +147,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),
|
||||
functions: PureXML.XSLT.Library.table(current: context.node, keys: keyIndex, loader: documentLoader, decimalFormats: stylesheet.decimalFormats),
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
65
Tests/XSLTDecimalFormatTests.swift
Normal file
65
Tests/XSLTDecimalFormatTests.swift
Normal file
@ -0,0 +1,65 @@
|
||||
@testable import PureXML
|
||||
import Testing
|
||||
|
||||
@Suite("XSLT xsl:decimal-format")
|
||||
struct XSLTDecimalFormatTests {
|
||||
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)
|
||||
}
|
||||
|
||||
private func formatNumber(_ select: String, decimalFormats: String = "") -> String {
|
||||
"""
|
||||
<xsl:stylesheet version="1.0" \(xsl)>
|
||||
<xsl:output method="text"/>
|
||||
\(decimalFormats)
|
||||
<xsl:template match="/"><xsl:value-of select="\(select)"/></xsl:template>
|
||||
</xsl:stylesheet>
|
||||
"""
|
||||
}
|
||||
|
||||
@Test("The default format still works")
|
||||
func test_default() throws {
|
||||
#expect(try transform(formatNumber("format-number(1234.5, '#,##0.00')"), "<x/>") == "1,234.50")
|
||||
}
|
||||
|
||||
@Test("A named European format swaps the decimal and grouping separators")
|
||||
func test_european() throws {
|
||||
let style = formatNumber(
|
||||
"format-number(1234.5, '#.##0,00', 'eu')",
|
||||
decimalFormats: "<xsl:decimal-format name=\"eu\" decimal-separator=\",\" grouping-separator=\".\"/>",
|
||||
)
|
||||
#expect(try transform(style, "<x/>") == "1.234,50")
|
||||
}
|
||||
|
||||
@Test("A custom percent and minus sign are honored")
|
||||
func test_percentMinus() throws {
|
||||
let style = formatNumber(
|
||||
"format-number(-0.25, '0%', 'p')",
|
||||
decimalFormats: "<xsl:decimal-format name=\"p\" minus-sign=\"!\"/>",
|
||||
)
|
||||
#expect(try transform(style, "<x/>") == "!25%")
|
||||
}
|
||||
|
||||
@Test("A custom NaN string is used for non-numbers")
|
||||
func test_nan() throws {
|
||||
let style = formatNumber(
|
||||
"format-number(number('abc'), '0', 'n')",
|
||||
decimalFormats: "<xsl:decimal-format name=\"n\" NaN=\"not-a-number\"/>",
|
||||
)
|
||||
#expect(try transform(style, "<x/>") == "not-a-number")
|
||||
}
|
||||
|
||||
@Test("The unnamed decimal-format overrides the global default")
|
||||
func test_unnamedDefault() throws {
|
||||
let style = formatNumber(
|
||||
"format-number(5, '0')",
|
||||
decimalFormats: "<xsl:decimal-format zero-digit=\"0\" minus-sign=\"~\"/>",
|
||||
)
|
||||
// 5 formats plainly; a negative shows the overridden minus sign.
|
||||
#expect(try transform(style, "<x/>") == "5")
|
||||
let neg = formatNumber("format-number(-5, '0')", decimalFormats: "<xsl:decimal-format minus-sign=\"~\"/>")
|
||||
#expect(try transform(neg, "<x/>") == "~5")
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user