plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


af9a42e — Peter John 2026-11-10T14:59:11+05:30
std: decimal becomes the Decimal type
Files changed (4) hide show
  1. docs/std.md +28 -2
  2. std/Decimal.plum +49 -34
  3. std/Float.plum +2 -2
  4. std/encoding/Json.plum +1 -1
docs/std.md CHANGED
@@ -14,6 +14,7 @@ The [game engine](game.md) has its own page.
14
14
  | [`AvlTree`, `Trie`, `Graph`, ...](#persistent-trees-heaps-and-graphs) | persistent trees, heaps and graphs |
15
15
  | [`Option`, `Result`](#option-and-result) | missing values and failures |
16
16
  | [`Json`](#json) | reading and writing JSON |
17
+ | [`Decimal`](#decimal) | exact decimal numbers, to and from `Float` |
17
18
  | [`Os`, `http`](#files-and-network) | files and the network |
18
19
  | [`Time`, `Random`, `Uuid`, `Base64`, `Aabb`, `ref`](#utilities) | utilities |
19
20
  | [`testing`](#testing) | helpers for tests |
@@ -42,7 +43,7 @@ Where wasm has the operation, std uses its instruction, compiled in line at each
42
43
 
43
44
  At the edges they follow IEEE 754. `x.logb()` is the exponent of `|x|`, floor(log2(|x|)) exactly, read from the bits (a subnormal is scaled by 2^54 first): `7.999999999999999.logb()` is `2.0`, `Float.Min.logb()` is `-1074.0`, `logb` of a zero is -Infinity, of either infinity Infinity, of NaN NaN, and the sign is ignored (`Int.logb` agrees: `Int.Min.logb()` is `63.0`). `math.cbrt` is correctly rounded (no miss in a million sampled inputs over every exponent) for every Float, subnormals and `1e300` included (`cbrt(1e300)` is `1e100`): `|x|` is split into `m * 2^(3k)` from the bits, FreeBSD's `s_cbrt.c` guess gives a 23-bit root `t` of `m`, and `t * (1 + u)^(1/3)` with `u = (m - t^3) / t^3` (the residual exact but for one rounding, by Dekker's product; the binomial series to u^4) rounds to the nearest float unless the root is within about 2^-22 ulp of halfway. It keeps the sign (`cbrt(-0.0)` is `-0.0`), and NaN and the infinities pass through. `math.sin`, `math.cos` and `math.tan` are fdlibm's (FreeBSD's `s_sin.c`, `s_cos.c`, `s_tan.c`), under 1 ulp for every finite Float: against mpmath over 89k sampled inputs (every exponent, multiples of Pi/2 and the floats next to them, subnormals) at worst 0.72, 0.74 and 0.81 ulp, with 1.4%, 1.5% and 1.7% not the nearest float (the old Taylor series after a plain subtraction of multiples of 2*Pi was up to 10^22 ulp off next to the zeros, and for |x| <= 4 36%, 68% and 68% not the nearest). `x` is reduced to `n * Pi/2 + r` with `|r| <= Pi/4`: below 2^20 * Pi/2 (about 1.6e6) by Cody and Waite's subtraction with Pi/2 in three 33-bit parts, above it by multiplying the 53-bit significand by 240 bits of 2/Pi in integers (Payne and Hanek), so `sin(1e22)` is `-0.8522008497671888` and `sin(Float.Max)` is right too; then fdlibm's kernel polynomials for sin, cos and tan on `r`. A tiny `x` (below 2^-26 for `sin`, 2^-27 for `tan`) is its own `sin` and `tan`, a subnormal included, and its `cos` is `1.0`; the infinities and NaN give NaN. `math.atan` is fdlibm's `s_atan.c` bit for bit, under 1 ulp (0.70 at worst over 40k sampled inputs against mpmath): breakpoints at 7/16, 11/16, 19/16 and 39/16, then a degree-22 odd polynomial; from 2^66 up, and at the infinities, it is `±Pi/2`. `math.atan2` is fdlibm's `e_atan2.c` (1.36 ulp at worst) with C99's special cases: `atan2(±0, x)` is `±0` for `x` above zero or `+0` and `±Pi` for `x` below zero or `-0`, `atan2(y, ±0)` for a nonzero `y` is `±Pi/2`, an infinite `x` gives `±0` or `±Pi` for a finite `y` and `±Pi/4` or `±3*Pi/4` for an infinite one, an infinite `y` gives `±Pi/2`, and a NaN on either side gives NaN. `math.asin` is `atan(x / sqrt(1 - x*x))` with `(1 - x) * (1 + x)` from `|x| = 0.5` up, and `math.acos` is `2 * atan(sqrt((1 - x) / (1 + x)))`, both within 1.8 ulp (`acos` was `Pi/2 - asin(x)`, 231 ulp off near 1). `sin(-0.0)`, `tan(-0.0)`, `asin(-0.0)` and `atan(-0.0)` are `-0.0`.
44
45
 
45
- `Int.toStr` prints every Int, `Int.Min` as `-9223372036854775808`. `Float.toStr` rounds to 6 fractional digits below 2^63; from 2^63 up (past Int's range, where every Float is whole) it prints the float's exact decimal value, so `1.0e20.toStr()` is `100000000000000000000.0` and `Float.Max` prints all 309 digits. `Float.hash` is the bits (`toBits`), so values in (-1, 1) don't collide in a `Hamt`; `0.0` and `-0.0`, which are `==`, both hash to 0, and every NaN hashes the same.
46
+ `Int.toStr` prints every Int, `Int.Min` as `-9223372036854775808`. `Float.toStr` rounds to 6 fractional digits below 2^63; from 2^63 up (past Int's range, where every Float is whole) it prints the float's exact decimal value (`Decimal.exact`), so `1.0e20.toStr()` is `100000000000000000000.0` and `Float.Max` prints all 309 digits. `Float.hash` is the bits (`toBits`), so values in (-1, 1) don't collide in a `Hamt`; `0.0` and `-0.0`, which are `==`, both hash to 0, and every NaN hashes the same.
46
47
 
47
48
  `compare(o)` gives -1, 0 or 1 as the receiver is below, equal to or above `o`; it is the order of `Map` keys and `Set` members. `Float.compare` is a total order: `-0.0` and `0.0` compare equal, and every NaN equals every other NaN and comes after `Infinity` (so `-Infinity < -1.0 < -0.0 == 0.0 < Infinity < NaN`). `Bool.compare` puts `false` first, `Byte.compare` is by value.
48
49
  - `Bool`: `toStr`, `Bool.parse`, `compare`
@@ -186,7 +187,32 @@ fun main() =
186
187
 
187
188
  The result's annotation tells `decode` which type to build. A JSON object is a `Map[Str, Json]`, so its fields come back, and are written, in key order; a later duplicate key wins. `Option` doesn't have JSON support yet, so write those conversions by hand.
188
189
 
189
- Numbers are `Float`s. Writing one gives the shortest digits that read back as the same Float, the way JavaScript writes them: `Json.encode(123)` is `123`, `0.1 + 0.2` is `0.30000000000000004`, `1e21` is `1e+21`, and NaN and the infinities are `null`. Reading one gives the Float nearest the number's exact value, so text written by any correct JSON library reads back exactly. A leading zero (`01`), a number past Float's range (`1e400`) and more than `MaxJsonDepth` (1000) nested arrays and objects are errors. Both directions are [`std/decimal`](../std/decimal.plum) (`decimal.parse(text)`, `decimal.format(x)`, `decimal.shortest(x)`), which `Float.parse` uses too: it takes an exponent (`2.5e-3`) and `Float.parse("0.3")` is `0.3`.
190
+ Numbers are `Float`s. Writing one gives the shortest digits that read back as the same Float, the way JavaScript writes them: `Json.encode(123)` is `123`, `0.1 + 0.2` is `0.30000000000000004`, `1e21` is `1e+21`, and NaN and the infinities are `null`. Reading one gives the Float nearest the number's exact value, so text written by any correct JSON library reads back exactly. A leading zero (`01`), a number past Float's range (`1e400`) and more than `MaxJsonDepth` (1000) nested arrays and objects are errors. Both directions are [`Decimal`](#decimal), which `Float.parse` uses too: it takes an exponent (`2.5e-3`) and `Float.parse("0.3")` is `0.3`.
191
+
192
+ ## Decimal
193
+
194
+ `std/Decimal` is an exact decimal number, `struct Decimal(digits: Str, exp: Int, neg: Bool)`: the value is `digits * 10^exp`, negated when `neg`. `digits` has no leading zero, and zero is `"0"` (it keeps its sign).
195
+
196
+ ```plum
197
+ import std/Int
198
+ import std/Float
199
+ import std/Str
200
+ import std/Option
201
+ import std/Decimal
202
+
203
+ fun main() =
204
+ d := Decimal.parse("12.50")! # digits "1250", exp -2: nothing is rounded
205
+ x := d.toFloat() # 12.5, the nearest Float
206
+ s := Decimal.ofFloat(0.1 + 0.2) # digits "30000000000000004", exp -17
207
+ t := s.toStr() # "0.30000000000000004"
208
+ ```
209
+
210
+ - **`Decimal.parse(text)`**: `[+-]digits[.digits][(e|E)[+-]digits]` read exactly, an `Option[Decimal]`. Trailing zeros are kept (`1.50` is 150 * 10^-2).
211
+ - **`d.toFloat()`**: the Float nearest `d`, ties to even, as IEEE 754 and every correct `strtod` give; past Float's range an infinity, below it a zero. `Decimal.parseFloat(text)` is `parse` then `toFloat` without the `Decimal` in between (an `Option[Float]`); `Float.parse` and `Json` read numbers with it.
212
+ - **`Decimal.ofFloat(x)`**: the shortest digits that convert back to `x`. **`Decimal.exact(x)`**: the value `x` holds, digit for digit (`Decimal.exact(1e23)` is 99999999999999991611392). Both need a finite `x`; a NaN or an infinity stops the program.
213
+ - **`d.toStr()`**: the way JavaScript writes a number: plain digits from 1e-6 up to 1e21, exponent notation outside (`1e+21`, `1.5e-7`), `-0` for minus zero. `d.isZero()`.
214
+
215
+ The big-integer arithmetic and the scanner behind these are statics of `Decimal` too (`Decimal.bigAdd`, `Decimal.scanDigits`, ...). Plum has no private members, so they can be called from outside, but they are not part of the API; they are no longer free functions of a module.
190
216
 
191
217
  ## Files and network
192
218
 
std/Decimal.plum CHANGED
@@ -6,6 +6,7 @@ import std/Str
6
6
  import std/Buffer
7
7
  import std/Byte
8
8
  import std/Slice
9
+ import std/Array
9
10
  import std/Option
10
11
  import std/Pair
11
12
  import std/math/math
@@ -55,6 +56,17 @@ struct Decimal(digits: Str, exp: Int, neg: Bool) =
55
56
  else
56
57
  None
57
58
 
59
+ # `Decimal.parse(text)` then `toFloat()` in one step, without building the Decimal
60
+ # between: the Float nearest the decimal `text`, or None if it isn't a number. This is
61
+ # what `Float.parse` and JSON read numbers with.
62
+ fun parseFloat(text: Str) -> Option[Float] =
63
+ sc := DecimalScan(digits: Buffer(), exp: 0, neg: false, ok: true, seen: 0, pos: 0)
64
+ if scan(text, sc)
65
+ v := digitsToFloat(sc.digits.toStr(), sc.exp)
66
+ Some(if sc.neg then -v else v)
67
+ else
68
+ None
69
+
58
70
  # The Float nearest this decimal, ties to even; an infinity past Float's range, a zero
59
71
  # below it. `-0` is `-0.0`.
60
72
  fun toFloat(self) -> Float =
@@ -96,12 +108,16 @@ struct Decimal(digits: Str, exp: Int, neg: Bool) =
96
108
  drop := if e0 >= 0 then 0 else if tz < 0 - e0 then tz else 0 - e0
97
109
  f := f0 >> drop
98
110
  e := e0 + drop
99
- if e >= 0
111
+ # The digits are worked out in base 10^9: f times 2^e, or times 5^-e.
100
- trimmed(bigToDigits(bigShl(bigOf(f), e)), 0, x < 0.0)
112
+ limbs := Array.filled(if e >= 0 then 36 else 88, 0)
101
- else
113
+ limbs.set(0, f % 1000000000)
114
+ limbs.set(1, f / 1000000000)
115
+ start := if f >= 1000000000 then 2 else 1
116
+ used := if e >= 0 then decMulPow(limbs, start, e, 29, 1 << 29, 2) else decMulPow(limbs, start, 0 - e, 12, 244140625, 5)
102
- m := bigOf(f)
117
+ out := Buffer()
118
+ out.write(Int.intToStr(limbs.get(used - 1)))
103
- bigMulPow5(m, 0 - e)
119
+ decWrite(limbs, used - 2, out)
104
- Decimal(digits: bigToDigits(m), exp: e, neg: x < 0.0)
120
+ if e >= 0 then trimmed(out.toStr(), 0, x < 0.0) else Decimal(digits: out.toStr(), exp: e, neg: x < 0.0)
105
121
 
106
122
  # The decimal as JavaScript's `String(x)` writes a number (and JSON with it): its digits
107
123
  # in plain notation from 1e-6 up to 1e21 (`0.000001`, `123.5`, `100000000000000000000`)
@@ -318,39 +334,38 @@ struct Decimal(digits: Str, exp: Int, neg: Bool) =
318
334
  fun quotientDigit(r: Slice[Int], s: Slice[Int], d: Int) -> Pair[Int, Slice[Int]] =
319
335
  if bigCmp(r, s) < 0 then Pair(first: d, second: r) else quotientDigit(bigSub(r, s), s, d + 1)
320
336
 
321
- # ---- big integer to decimal digits ----
337
+ # ---- decimal limbs: a whole number as an `Array[Int]` of base-10^9 limbs, least significant first ----
322
338
 
323
- # The decimal digits of `a` (above zero), most significant first. `a` is used up.
339
+ # Multiplies the `used` limbs by `base^n`, `step` powers at a time (`big` is `base^step`,
324
- fun bigToDigits(a: Slice[Int]) -> Str =
325
- chunks := Slice[Int]()
326
- bigChunks(a, chunks)
327
- out := Buffer()
328
- out.write(chunks.at(chunks.length() - 1).toStr())
329
- writeChunks(chunks, chunks.length() - 2, out)
340
+ # at most 2^29); returns how many limbs are used.
330
- out.toStr()
331
-
332
- # Divides `a` by 10^8 until nothing is left, pushing each remainder (eight digits, the
333
- # least significant first).
334
- fun bigChunks(a: Slice[Int], chunks: Slice[Int]) -> Unit =
341
+ fun decMulPow(limbs: Array[Int], used: Int, n: Int, step: Int, big: Int, base: Int) -> Int =
335
- if a.length() > 0
342
+ if n <= 0
343
+ used
344
+ else if n >= step
345
+ decMulPow(limbs, decMul(limbs, 0, used, big, 0), n - step, step, big, base)
346
+ else
336
- chunks.push(divSmallFrom(a, 100000000, a.length() - 1, 0))
347
+ decMul(limbs, 0, used, smallPow(base, n), 0)
337
- trimTop(a)
338
- bigChunks(a, chunks)
339
348
 
349
+ fun smallPow(base: Int, n: Int) -> Int = if n <= 0 then 1 else base * smallPow(base, n - 1)
350
+
340
- # `a = a / d` in place from limb `i` down, for 0 < d < 2^28; returns the remainder.
351
+ # limbs[i..used) times f (at most 2^29) plus `carry`; returns the new used count.
341
- fun divSmallFrom(a: Slice[Int], d: Int, i: Int, rem: Int) -> Int =
352
+ fun decMul(limbs: Array[Int], i: Int, used: Int, f: Int, carry: Int) -> Int =
342
- if i < 0
353
+ if i < used
354
+ p := limbs.get(i) * f + carry
355
+ q := p / 1000000000
356
+ limbs.set(i, p - q * 1000000000)
357
+ decMul(limbs, i + 1, used, f, q)
358
+ else if carry > 0
359
+ limbs.set(used, carry)
343
- rem
360
+ used + 1
344
361
  else
345
- cur := {rem << Decimal.LimbBits} | a.atUnchecked(i)
346
- a.putAt(i, cur / d)
362
+ used
347
- divSmallFrom(a, d, i - 1, cur % d)
348
363
 
349
- # Chunks `i` down to 0, eight digits each.
364
+ # Limbs i down to 0, nine digits each.
350
- fun writeChunks(chunks: Slice[Int], i: Int, out: Buffer) -> Unit =
365
+ fun decWrite(limbs: Array[Int], i: Int, out: Buffer) -> Unit =
351
366
  if i >= 0
352
- out.write(Int.fixedFracDigits(chunks.at(i), 10000000))
367
+ out.write(Int.fixedFracDigits(limbs.get(i), 100000000))
353
- writeChunks(chunks, i - 1, out)
368
+ decWrite(limbs, i - 1, out)
354
369
 
355
370
  # ---- big integers ----
356
371
 
std/Float.plum CHANGED
@@ -34,8 +34,8 @@ primitive Float =
34
34
  # is the Float nearest the decimal's exact value (std/Decimal), so `Float.parse("0.3")`
35
35
  # is `0.3`; past Float's range it is an infinity, and below it a zero.
36
36
  fun parse(s: Str) -> Result[Float, NumError] =
37
- match Decimal.parse(s)
37
+ match Decimal.parseFloat(s)
38
- Some(d) => Ok(d.toFloat())
38
+ Some(f) => Ok(f)
39
39
  None => Err(BadNumStr)
40
40
 
41
41
  # The 64 IEEE 754 bits of `self` as an Int (wasm's `i64.reinterpret_f64`): the sign bit is
std/encoding/Json.plum CHANGED
@@ -360,7 +360,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
360
360
  self.numberOf(self.src.sub(start, self.pos))
361
361
 
362
362
  fun numberOf(self, text: Str) -> Result[Json, JsonError] =
363
- match Decimal.parse(text).map(|d| d.toFloat())
363
+ match Decimal.parseFloat(text)
364
364
  Some(f) =>
365
365
  if f > Float.Max || f < 0.0 - Float.Max
366
366
  self.note("number out of range")