feat(xslt): full format-number picture parsing
The picture parses into affixes, number part, and the negative subpattern: literal prefixes and suffixes pass through, the negative subpattern's affixes apply (with the default minus when it has no distinguishing ones), per-mille and percent multiply and stay literal, the grouping size derives from the pattern's last grouping separator, colliding decimal/grouping separators read as grouping, and U+00A4 renders as the en-US currency symbol. Digit extraction now uses one scaled rounding and integer arithmetic, eliminating per-digit float drift. Xalan numberformat 30 -> 1; baseline 475 -> 446.
This commit is contained in:
parent
2134a23c41
commit
38bbb349c5
@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
|
||||
### Added
|
||||
|
||||
- format-number picture parsing in full, third xalan burn-down (#130): the picture now parses JDK DecimalFormat-style into literal prefix/suffix affixes around the number part, the negative subpattern after the pattern separator (its affixes apply; without distinguishing ones the minus sign still prefixes, the Xalan resolution, which also covers colliding decimal/grouping separators by reading every occurrence as grouping), per-mille (with a custom symbol via the new `per-mille` attribute) and percent as multipliers kept literally in the output, the grouping size taken from the last grouping separator's distance to the decimal point instead of a fixed 3, and the generic currency sign U+00A4 rendering as this processor's en-US `$`. Digit extraction is rewritten over one scaled rounding plus pure integer arithmetic, so 0.4812 renders 4812 rather than re-accumulating float error per digit. The xalan numberformat category drops 30 to 1 (the survivor is a namespace-copy case); baseline 475 to 446.
|
||||
- Full xsl:number per XSLT 1.0 section 7.7, second xalan burn-down (#130): `level` single/multiple/any with `count` and `from` as real patterns matched through the transform's match cache (default count: same node type and expanded name; single finds the nearest matching ancestor-or-self and numbers it among matching preceding siblings, multiple numbers every matching ancestor-or-self outermost first, any counts matching nodes at or before this one in document order with `from` as the boundary, always yielding a number so an unmatched count renders 0); the `value` expression evaluates and rounds, bypassing formatting below one; and the full format-token engine (leading/trailing punctuation, alternating alphanumeric tokens and separators with last-token and last-separator reuse, zero-padded decimal widths, `a`/`A`/`i`/`I` and the Greek alphabetic sequence, `grouping-separator`/`grouping-size` digit grouping). A single/multiple level whose count matches nothing renders as the empty string, punctuation included. The xalan baseline drops from 557 to 475 (numbering 84 to 7, the rest pattern-engine prefixed/key/id cases).
|
||||
- `document()` is stable per transform (#130): the same URI reference now returns the identical document object across calls within one transform, per the XSLT `document()` definition, via a per-transformer document cache; previously each call re-parsed, so node identity, and with it `generate-id()` uniqueness against live nodes, could be violated when an address was reused (the idkey49 flake).
|
||||
- XSLT namespaced name creation and result fixup, first xalan burn-down (#130): xsl:attribute and xsl:element honor the `namespace` attribute and resolve a prefixed `name` against the instruction's own in-scope stylesheet declarations (7.1.2/7.1.3, captured at parse time so AVT names resolve correctly); xsl:copy applies `use-attribute-sets`; and a namespace-fixup pass runs over the result tree before serialization, declaring every namespace a created element or attribute name carries, reusing an existing binding for the same URI or generating `ns0`, `ns1`, ... prefixes when the carried prefix is absent or taken, and undeclaring an inherited default namespace that would capture an unqualified name. The xalan baseline drops from 604 to 557 (attribset 52 to 20, namespace 123 to 92, axes 68 to 35); one namespace-alias unit test updated to expect the now-declared result namespace.
|
||||
|
||||
@ -125,7 +125,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 **950 tests in 165 suites** (`swift test`).
|
||||
currently runs **955 tests in 165 suites** (`swift test`).
|
||||
|
||||
### Shipped (libxml2-aligned surface)
|
||||
|
||||
|
||||
@ -1,12 +1,15 @@
|
||||
private typealias DecimalFormat = PureXML.XSLT.DecimalFormat
|
||||
|
||||
/// The digit-place counts and grouping derived from a format-number picture.
|
||||
/// File scope and private.
|
||||
/// The digit-place counts, grouping, affixes, and multiplier derived from a
|
||||
/// format-number subpattern. File scope and private.
|
||||
private struct NumberLayout {
|
||||
let minInteger: Int
|
||||
let minFraction: Int
|
||||
let maxFraction: Int
|
||||
let grouping: Bool
|
||||
var prefix = ""
|
||||
var suffix = ""
|
||||
var minInteger = 0
|
||||
var minFraction = 0
|
||||
var maxFraction = 0
|
||||
var groupingSize = 0
|
||||
var multiplier = 1.0
|
||||
}
|
||||
|
||||
extension PureXML.XSLT {
|
||||
@ -16,51 +19,112 @@ extension PureXML.XSLT {
|
||||
enum FormatNumber {
|
||||
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(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 == 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 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) : "")
|
||||
let subpatterns = picture.split(separator: symbols.patternSeparator, maxSplits: 1, omittingEmptySubsequences: false)
|
||||
let positive = parse(String(subpatterns[0]), symbols)
|
||||
// The negative subpattern contributes only its affixes; digit
|
||||
// places, grouping, and multiplier come from the positive one.
|
||||
// Without one the default negative prefix is the minus sign.
|
||||
var layout = positive
|
||||
if value < 0 {
|
||||
let negative = subpatterns.count > 1 ? parse(String(subpatterns[1]), symbols) : nil
|
||||
if let negative, !(negative.prefix.isEmpty && negative.suffix.isEmpty) {
|
||||
layout.prefix = negative.prefix
|
||||
layout.suffix = negative.suffix
|
||||
} else {
|
||||
// No negative subpattern, or one with no distinguishing
|
||||
// affixes: the default negative prefix is the minus sign.
|
||||
layout.prefix = String(symbols.minusSign) + layout.prefix
|
||||
}
|
||||
}
|
||||
if value.isInfinite { return layout.prefix + symbols.infinity + layout.suffix }
|
||||
let magnitude = Swift.abs(value) * positive.multiplier
|
||||
return layout.prefix + render(magnitude, layout, symbols) + layout.suffix
|
||||
}
|
||||
|
||||
private static func round(_ value: Double, places: Int) -> Double {
|
||||
var scale = 1.0
|
||||
for _ in 0 ..< places {
|
||||
scale *= 10
|
||||
/// Splits one subpattern into prefix, number part, and suffix, reading
|
||||
/// the digit places, the grouping size (digits after the last grouping
|
||||
/// separator), and the percent/per-mille multiplier from it.
|
||||
private static func parse(_ subpattern: String, _ symbols: DecimalFormat) -> NumberLayout {
|
||||
var layout = NumberLayout()
|
||||
// When the decimal and grouping separators collide, every
|
||||
// occurrence reads as grouping (the Xalan resolution).
|
||||
let decimal: Character? = symbols.decimalSeparator == symbols.groupingSeparator ? nil : symbols.decimalSeparator
|
||||
let numberCharacters = Set([symbols.zeroDigit, symbols.digit, symbols.groupingSeparator, symbols.decimalSeparator])
|
||||
var phase = 0 // 0 prefix, 1 number, 2 suffix
|
||||
var inFraction = false
|
||||
var sinceGrouping: Int?
|
||||
for character in subpattern {
|
||||
if character == symbols.percent || character == symbols.perMille {
|
||||
layout.multiplier = character == symbols.percent ? 100 : 1000
|
||||
if phase == 1 { phase = 2 }
|
||||
appendAffix(character, phase, &layout)
|
||||
continue
|
||||
}
|
||||
if numberCharacters.contains(character), phase < 2 {
|
||||
phase = 1
|
||||
if character == decimal {
|
||||
inFraction = true
|
||||
} else {
|
||||
countPlace(character, inFraction, symbols, &layout, &sinceGrouping)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if phase == 1 { phase = 2 }
|
||||
appendAffix(character, phase, &layout)
|
||||
}
|
||||
layout.groupingSize = sinceGrouping ?? 0
|
||||
return layout
|
||||
}
|
||||
|
||||
/// Tallies one digit-area character into the layout's place counts and
|
||||
/// the running last-grouping-interval width.
|
||||
private static func countPlace(
|
||||
_ character: Character,
|
||||
_ inFraction: Bool,
|
||||
_ symbols: DecimalFormat,
|
||||
_ layout: inout NumberLayout,
|
||||
_ sinceGrouping: inout Int?,
|
||||
) {
|
||||
if character == symbols.groupingSeparator {
|
||||
if !inFraction { sinceGrouping = 0 }
|
||||
} else if inFraction {
|
||||
layout.maxFraction += 1
|
||||
if character == symbols.zeroDigit { layout.minFraction += 1 }
|
||||
} else {
|
||||
if character == symbols.zeroDigit { layout.minInteger += 1 }
|
||||
sinceGrouping = sinceGrouping.map { $0 + 1 }
|
||||
}
|
||||
}
|
||||
|
||||
private static func appendAffix(_ character: Character, _ phase: Int, _ layout: inout NumberLayout) {
|
||||
// The generic currency sign renders as this processor's (en-US)
|
||||
// currency symbol, the JDK affix substitution.
|
||||
let resolved: Character = character == "\u{A4}" ? "$" : character
|
||||
if phase == 0 {
|
||||
layout.prefix.append(resolved)
|
||||
} else {
|
||||
layout.suffix.append(resolved)
|
||||
}
|
||||
return (value * scale).rounded() / scale
|
||||
}
|
||||
|
||||
private static func render(_ value: Double, _ layout: NumberLayout, _ symbols: DecimalFormat) -> String {
|
||||
let integerValue = Int(value)
|
||||
var integerDigits = String(integerValue)
|
||||
while integerDigits.count < Swift.max(1, layout.minInteger) {
|
||||
integerDigits = "0" + integerDigits
|
||||
}
|
||||
var integerText = digitsToSymbols(integerDigits, symbols)
|
||||
if layout.grouping { integerText = group(integerText, symbols.groupingSeparator) }
|
||||
|
||||
var fractionValue = value - Double(integerValue)
|
||||
var fractionDigits = ""
|
||||
// One scaled rounding, then pure integer digit extraction: repeated
|
||||
// float multiplication would re-introduce representation error
|
||||
// (0.4812 must render 4812, not 481199...).
|
||||
var scale = 1.0
|
||||
for _ in 0 ..< layout.maxFraction {
|
||||
fractionValue *= 10
|
||||
let digit = Int(fractionValue)
|
||||
fractionDigits += String(digit)
|
||||
fractionValue -= Double(digit)
|
||||
scale *= 10
|
||||
}
|
||||
let (integerDigits, allFractionDigits) = digits(value, scale: scale, places: layout.maxFraction)
|
||||
var paddedInteger = integerDigits
|
||||
while paddedInteger.count < Swift.max(1, layout.minInteger) {
|
||||
paddedInteger = "0" + paddedInteger
|
||||
}
|
||||
var integerText = digitsToSymbols(paddedInteger, symbols)
|
||||
if layout.groupingSize > 0 { integerText = group(integerText, symbols.groupingSeparator, layout.groupingSize) }
|
||||
|
||||
var fractionDigits = allFractionDigits
|
||||
while fractionDigits.count > layout.minFraction, fractionDigits.hasSuffix("0") {
|
||||
fractionDigits.removeLast()
|
||||
}
|
||||
@ -68,6 +132,23 @@ extension PureXML.XSLT {
|
||||
return fractionText.isEmpty ? integerText : integerText + String(symbols.decimalSeparator) + fractionText
|
||||
}
|
||||
|
||||
/// The integer and fraction digit strings of `value` carried to
|
||||
/// `places` fraction digits, via a single scaled rounding when the
|
||||
/// magnitude fits an Int exactly.
|
||||
private static func digits(_ value: Double, scale: Double, places: Int) -> (String, String) {
|
||||
let scaled = (value * scale).rounded()
|
||||
guard scaled < 9_007_199_254_740_992 else { // 2^53: beyond it Double has no fraction anyway
|
||||
return (String(Int(value)), String(repeating: "0", count: places))
|
||||
}
|
||||
let total = Int(scaled)
|
||||
let divisor = Int(scale)
|
||||
var fraction = String(total % divisor)
|
||||
while fraction.count < places {
|
||||
fraction = "0" + fraction
|
||||
}
|
||||
return (String(total / divisor), places > 0 ? fraction : "")
|
||||
}
|
||||
|
||||
/// 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 }
|
||||
@ -77,10 +158,10 @@ extension PureXML.XSLT {
|
||||
})
|
||||
}
|
||||
|
||||
private static func group(_ digits: String, _ separator: Character) -> String {
|
||||
private static func group(_ digits: String, _ separator: Character, _ size: Int) -> String {
|
||||
var result = ""
|
||||
for (offset, character) in digits.reversed().enumerated() {
|
||||
if offset > 0, offset.isMultiple(of: 3) { result.append(separator) }
|
||||
if offset > 0, offset.isMultiple(of: size) { result.append(separator) }
|
||||
result.append(character)
|
||||
}
|
||||
return String(result.reversed())
|
||||
|
||||
@ -175,6 +175,7 @@ public extension PureXML.XSLT {
|
||||
public var decimalSeparator: Character = "."
|
||||
public var groupingSeparator: Character = ","
|
||||
public var percent: Character = "%"
|
||||
public var perMille: Character = "\u{2030}"
|
||||
public var zeroDigit: Character = "0"
|
||||
public var digit: Character = "#"
|
||||
public var patternSeparator: Character = ";"
|
||||
|
||||
@ -362,6 +362,7 @@ private extension PureXML.XSLT.XSLTParser {
|
||||
char("decimal-separator", \.decimalSeparator)
|
||||
char("grouping-separator", \.groupingSeparator)
|
||||
char("percent", \.percent)
|
||||
char("per-mille", \.perMille)
|
||||
char("zero-digit", \.zeroDigit)
|
||||
char("digit", \.digit)
|
||||
char("pattern-separator", \.patternSeparator)
|
||||
|
||||
@ -305,36 +305,7 @@ node/node15
|
||||
node/node16
|
||||
node/node17
|
||||
node/node19
|
||||
numberformat/numberformat01
|
||||
numberformat/numberformat02
|
||||
numberformat/numberformat03
|
||||
numberformat/numberformat04
|
||||
numberformat/numberformat06
|
||||
numberformat/numberformat07
|
||||
numberformat/numberformat08
|
||||
numberformat/numberformat09
|
||||
numberformat/numberformat11
|
||||
numberformat/numberformat12
|
||||
numberformat/numberformat16
|
||||
numberformat/numberformat17
|
||||
numberformat/numberformat19
|
||||
numberformat/numberformat20
|
||||
numberformat/numberformat21
|
||||
numberformat/numberformat22
|
||||
numberformat/numberformat23
|
||||
numberformat/numberformat24
|
||||
numberformat/numberformat25
|
||||
numberformat/numberformat27
|
||||
numberformat/numberformat28
|
||||
numberformat/numberformat29
|
||||
numberformat/numberformat30
|
||||
numberformat/numberformat31
|
||||
numberformat/numberformat34
|
||||
numberformat/numberformat35
|
||||
numberformat/numberformat36
|
||||
numberformat/numberformat41
|
||||
numberformat/numberformat43
|
||||
numberformat/numberformat44
|
||||
numbering/numbering63
|
||||
numbering/numbering86
|
||||
numbering/numbering87
|
||||
|
||||
@ -62,4 +62,32 @@ struct XSLTDecimalFormatTests {
|
||||
let neg = formatNumber("format-number(-5, '0')", decimalFormats: "<xsl:decimal-format minus-sign=\"~\"/>")
|
||||
#expect(try transform(neg, "<x/>") == "~5")
|
||||
}
|
||||
|
||||
@Test("Literal affixes pass through around the number part")
|
||||
func test_affixes() throws {
|
||||
#expect(try transform(formatNumber("format-number(95.4857, 'PRE###.####SUF')"), "<x/>") == "PRE95.4857SUF")
|
||||
#expect(try transform(formatNumber("format-number(26931.4, '+#,###.#')"), "<x/>") == "+26,931.4")
|
||||
}
|
||||
|
||||
@Test("The negative subpattern supplies its affixes; without distinguishing ones the minus sign applies")
|
||||
func test_negativeSubpattern() throws {
|
||||
#expect(try transform(formatNumber("format-number(-26931.4, '#,###.#;(#,###.#)')"), "<x/>") == "(26,931.4)")
|
||||
#expect(try transform(formatNumber("format-number(-26931.4, '#,###.#;#,###.#')"), "<x/>") == "-26,931.4")
|
||||
#expect(try transform(formatNumber("format-number(-87504.4812, '000,000.000###')"), "<x/>") == "-087,504.4812")
|
||||
}
|
||||
|
||||
@Test("Per-mille multiplies by a thousand and keeps the symbol")
|
||||
func test_perMille() throws {
|
||||
#expect(try transform(formatNumber("format-number(0.4857, '###.###\u{2030}')"), "<x/>") == "485.7\u{2030}")
|
||||
}
|
||||
|
||||
@Test("The grouping size comes from the pattern's last grouping separator")
|
||||
func test_groupingSize() throws {
|
||||
#expect(try transform(formatNumber("format-number(987654321, '###,##0,00.00')"), "<x/>") == "9,87,65,43,21.00")
|
||||
}
|
||||
|
||||
@Test("Fraction digits render exactly, without float drift")
|
||||
func test_fractionExact() throws {
|
||||
#expect(try transform(formatNumber("format-number(87504.4812, '000,000.000###')"), "<x/>") == "087,504.4812")
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user