plum

#treesitter#compiler#wasm

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

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


3586bfb — Peter John 2026-11-10T10:53:40+05:30
std numbers: exact decimal parse and shortest format (std/decimal), Json numbers, Int.parse overflow, tanh
docs/std.md CHANGED
@@ -163,6 +163,8 @@ fun main() =
163
163
 
164
164
  The result's annotation tells `decode` which type to build. `Option` doesn't have JSON support yet, so write those conversions by hand.
165
165
 
166
+ 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`.
167
+
166
168
  ## Files and network
167
169
 
168
170
  All of these need an `Io` and return a `Result`.
std/Float.plum CHANGED
@@ -3,6 +3,7 @@ module std
3
3
  import std/Str
4
4
  import std/Int
5
5
  import std/math
6
+ import std/decimal
6
7
  import std/Option
7
8
  import std/Result
8
9
 
@@ -27,51 +28,14 @@ primitive Float =
27
28
  HalfPi = 1.5707963267948966f # Pi / 2
28
29
  Tau = 6.283185307179586f # 2 * Pi
29
30
 
30
- # Parses a decimal float, with an optional leading `+`/`-` and an optional
31
+ # Parses a decimal float: an optional leading `+`/`-`, digits with an optional `.`
32
+ # (digits on at least one side), and an optional exponent (`1e5`, `2.5E-3`). The result
33
+ # is the Float nearest the decimal's exact value (std/decimal), so `Float.parse("0.3")`
31
- # `.` fractional part (no exponent notation).
34
+ # is `0.3`; past Float's range it is an infinity, and below it a zero.
32
35
  fun parse(s: Str) -> Result[Float, NumError] =
36
+ match decimal.parse(s)
33
- len := s.length()
37
+ Some(f) => Ok(f)
34
- if len == 0
35
- Err(BadNumStr)
38
+ None => Err(BadNumStr)
36
- else
37
- neg := s.byteAt(0) == 45
38
- start := if neg || s.byteAt(0) == 43 then 1 else 0
39
- if start >= len
40
- Err(BadNumStr)
41
- else
42
- parseWhole(s, start, len, 0.0f, false, neg)
43
-
44
- # `Float.parse`'s integer-part loop: digits of `s` from `i` up to the `.` (or the end).
45
- fun parseWhole(s: Str, i: Int, len: Int, whole: Float, sawDigit: Bool, neg: Bool) -> Result[Float, NumError] =
46
- if i < len && s.byteAt(i) != 46
47
- b := s.byteAt(i)
48
- if b < 48 || b > 57
49
- Err(BadNumStr)
50
- else
51
- parseWhole(s, i + 1, len, whole * 10.0f + Float(b - 48), true, neg)
52
- else if i < len
53
- parseFrac(s, i + 1, len, whole, 0.0f, 1.0f, sawDigit, neg)
54
- else
55
- parseDone(whole, 0.0f, sawDigit, neg)
56
-
57
- # `Float.parse`'s fractional loop: digits after the `.`, `scale` the current place value.
58
- fun parseFrac(s: Str, i: Int, len: Int, whole: Float, frac: Float, scale: Float, sawDigit: Bool, neg: Bool) -> Result[Float, NumError] =
59
- if i >= len
60
- parseDone(whole, frac, sawDigit, neg)
61
- else
62
- b := s.byteAt(i)
63
- if b < 48 || b > 57
64
- Err(BadNumStr)
65
- else
66
- nextScale := scale / 10.0f
67
- parseFrac(s, i + 1, len, whole, frac + Float(b - 48) * nextScale, nextScale, true, neg)
68
-
69
- fun parseDone(whole: Float, frac: Float, sawDigit: Bool, neg: Bool) -> Result[Float, NumError] =
70
- if !sawDigit
71
- Err(BadNumStr)
72
- else
73
- value := whole + frac
74
- Ok(if neg then -value else value)
75
39
 
76
40
  # The 64 IEEE 754 bits of `self` as an Int (wasm's `i64.reinterpret_f64`): the sign bit is
77
41
  # bit 63, then 11 exponent bits, then 52 fraction bits. `{-0.0}.toBits()` is `Int.Min`, a
@@ -180,8 +144,20 @@ primitive Float =
180
144
  fun cosh(self) -> Float =
181
145
  {math.exp(self) + math.exp(-self)} / 2.0f
182
146
 
147
+ # 1 - 2 / (e^(2|x|) + 1) with the sign of x: no overflow (sinh / cosh is NaN from about
148
+ # |x| = 710), so `tanh(800.0)` is 1.0. Small |x| uses x itself or sinh / cosh, which
149
+ # keep their relative precision there.
183
150
  fun tanh(self) -> Float =
151
+ ax := if self < 0.0f then -self else self
152
+ if self != self
153
+ self
154
+ else if ax < 1e-8f
155
+ self
156
+ else if ax < 0.5f
184
- self.sinh() / self.cosh()
157
+ self.sinh() / self.cosh()
158
+ else
159
+ t := 1.0f - 2.0f / {math.exp(2.0f * ax) + 1.0f}
160
+ if self < 0.0f then -t else t
185
161
 
186
162
  # Inverse hyperbolic sine: asinh(x) = ln(x + sqrt(x^2 + 1)).
187
163
  fun asinh(self) -> Float =
std/Int.plum CHANGED
@@ -8,8 +8,8 @@ import std/Option
8
8
  import std/Result
9
9
  import std/Array
10
10
 
11
- # Why `Int.parse` / `Float.parse` failed.
11
+ # Why `Int.parse` / `Float.parse` failed: not a number, or one past Int's range.
12
- enum NumError = BadNumStr
12
+ enum NumError = BadNumStr | NumOverflow
13
13
 
14
14
  # The API of the built-in `Int` type: associated constants, `Int.parse`, the
15
15
  # numeric methods (`x.abs()`, `x.min(y)`, ...) and the `for i := range n` loop
@@ -31,16 +31,25 @@ primitive Int =
31
31
  else
32
32
  parseDigits(s, start, len, 0, neg)
33
33
 
34
- # `Int.parse`'s loop: the digits of `s` from `i` on, `value` so far.
34
+ # `Int.parse`'s loop: the digits of `s` from `i` on. `value` is the number so far,
35
+ # negated (Int's range reaches one further below 0, so `Int.Min` parses too); a digit
36
+ # that would take it past the range is `NumOverflow`.
35
37
  fun parseDigits(s: Str, i: Int, len: Int, value: Int, neg: Bool) -> Result[Int, NumError] =
36
38
  if i >= len
39
+ if neg
40
+ Ok(value)
37
- Ok(if neg then -value else value)
41
+ else if value == Int.Min
42
+ Err(NumOverflow)
43
+ else
44
+ Ok(-value)
38
45
  else
39
46
  b := s.byteAt(i)
40
47
  if b < 48 || b > 57
41
48
  Err(BadNumStr)
49
+ else if value < -922337203685477580 || value == -922337203685477580 && b - 48 > 8
50
+ Err(NumOverflow)
42
51
  else
43
- parseDigits(s, i + 1, len, value * 10 + b - 48, neg)
52
+ parseDigits(s, i + 1, len, value * 10 - {b - 48}, neg)
44
53
 
45
54
  fun abs(self) -> Int =
46
55
  if self < 0 then -self else self
std/Json.plum CHANGED
@@ -9,6 +9,7 @@ import std/Str
9
9
  import std/Buffer
10
10
  import std/Option
11
11
  import std/Result
12
+ import std/decimal
12
13
 
13
14
  # Placement rule for built-in `toJson` / `fromJson`: they live HERE, in this
14
15
  # file, as extension blocks at the bottom (`primitive Int =`, `primitive Slice[T] =`),
@@ -48,13 +49,13 @@ enum Json =
48
49
  # matching `Int.fromStr`/`Float.fromStr`'s naming. Errors carry no data: to
49
50
  # learn where and why a parse failed use `Json.parse(s)` instead.
50
51
  fun fromStr(s: Str) -> Result[Json, JsonError] =
51
- parser := JsonParser(src: s, pos: 0, text: "")
52
+ parser := JsonParser(src: s, pos: 0, text: "", depth: 0)
52
53
  parser.parseDocument()
53
54
 
54
55
  # Like `fromStr`, but the outcome is an ordinary value: `Parsed` with the
55
56
  # document, or `Failed` with the position and message of the failure.
56
57
  fun parse(s: Str) -> JsonParse =
57
- parser := JsonParser(src: s, pos: 0, text: "")
58
+ parser := JsonParser(src: s, pos: 0, text: "", depth: 0)
58
59
  match parser.parseDocument()
59
60
  Ok(v) => Parsed(value: v)
60
61
  Err(e) => Failed(pos: parser.pos, text: parser.text)
@@ -66,7 +67,7 @@ enum Json =
66
67
  match self
67
68
  JsonNull => "null"
68
69
  JsonBool(value) => if value then "true" else "false"
69
- JsonNum(value) => value.toStr()
70
+ JsonNum(value) => numberText(value)
70
71
  JsonStr(value) => "\"" + escapeJsonStr(value) + "\""
71
72
  JsonArr(items) => "[" + items.join(",") + "]"
72
73
  JsonObj(fields) => "{{" + jsonMapToStr(fields) + "}}"
@@ -164,6 +165,12 @@ enum Json =
164
165
  buf.write("\":")
165
166
  buf.write(v.toStr())
166
167
 
168
+ # A number as JSON writes it: the shortest digits that read back as the same Float, as
169
+ # JavaScript writes them (`123`, `0.1`, `1e+21`, `1.5e-7`). JSON has no NaN or Infinity,
170
+ # so those are written `null`, as `JSON.stringify` does.
171
+ fun numberText(x: Float) -> Str =
172
+ if x != x || x > Float.Max || x < 0.0 - Float.Max then "null" else decimal.format(x)
173
+
167
174
  fun escapeJsonStr(s: Str) -> Str =
168
175
  buf := Buffer()
169
176
  escapeFrom(s, buf, 0)
@@ -220,13 +227,17 @@ enum Json =
220
227
  15 => "f"
221
228
  _ => "0"
222
229
 
230
+ # How many arrays and objects a document may nest: deeper ones are an error, not a stack
231
+ # overflow (the parser recurses once per level).
232
+ MaxJsonDepth = 1000
233
+
223
234
  # The outcome of `Json.parse`: the document, or where and why parsing failed.
224
235
  enum JsonParse = Parsed(value: Json) | Failed(pos: Int, text: Str)
225
236
 
226
237
  # A recursive-descent parser over a `Str` source, tracking its read position
227
238
  # in `pos`. It reads directly from a `Str`, the same way every other stdlib
228
239
  # parser (e.g. `Int.parse`) does.
229
- struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
240
+ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
230
241
 
231
242
  # Records why parsing is about to fail at the current position; the caller
232
243
  # then fails with `InvalidJson`.
@@ -301,12 +312,17 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
301
312
  self.pos = self.pos + n
302
313
  Ok(value)
303
314
 
315
+ # `-?(0|[1-9][0-9]*)(.[0-9]+)?([eE][+-]?[0-9]+)?`: a leading zero stands alone. The value
316
+ # is the Float nearest the number (std/decimal), and one past Float's range is an error,
317
+ # since JSON has no Infinity.
304
318
  fun parseNumber(self) -> Result[Json, JsonError] =
305
319
  start := self.pos
306
320
  if self.peek() == 45
307
321
  self.advance()
308
322
  if !isDigit(self.peek())
323
+ Err(self.badNumber())
324
+ else if self.peek() == 48 && isDigit(self.peekAt(1))
309
- self.note("invalid number")
325
+ self.note("invalid number: leading zero")
310
326
  Err(InvalidJson)
311
327
  else
312
328
  self.skipDigits()
@@ -322,8 +338,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
322
338
  if self.peek() == 46
323
339
  self.advance()
324
340
  if !isDigit(self.peek())
325
- self.note("invalid number")
326
- Err(InvalidJson)
341
+ Err(self.badNumber())
327
342
  else
328
343
  self.skipDigits()
329
344
  self.parseExponent(start)
@@ -337,26 +352,22 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
337
352
  if self.peek() == 43 || self.peek() == 45
338
353
  self.advance()
339
354
  if !isDigit(self.peek())
340
- self.note("invalid number")
341
- Err(InvalidJson)
355
+ Err(self.badNumber())
342
356
  else
343
357
  self.skipDigits()
344
- self.parseNumberText(self.src.sub(start, self.pos))
358
+ self.numberOf(self.src.sub(start, self.pos))
345
359
  else
346
- self.parseNumberText(self.src.sub(start, self.pos))
360
+ self.numberOf(self.src.sub(start, self.pos))
347
-
348
- # `Float.fromStr` (`libs/std/float.plum`) doesn't understand exponent
361
+
349
- # notation, so a number that has one is split into its mantissa and
350
- # exponent around the `e`/`E` and recombined here instead.
351
- fun parseNumberText(self, text: Str) -> Result[Json, JsonError] =
362
+ fun numberOf(self, text: Str) -> Result[Json, JsonError] =
352
- e_index := exponentIndex(text)
363
+ match decimal.parse(text)
353
- if e_index < 0
364
+ Some(f) =>
354
- f := Float.parse(text).mapErr(|e| self.badNumber())?
365
+ if f > Float.Max || f < 0.0 - Float.Max
366
+ self.note("number out of range")
367
+ Err(InvalidJson)
368
+ else
355
- Ok(JsonNum(value: f))
369
+ Ok(JsonNum(value: f))
356
- else
357
- mv := Float.parse(text.sub(0, e_index)).mapErr(|e| self.badNumber())?
370
+ None => Err(self.badNumber())
358
- ev := Int.parse(text.sub(e_index + 1, text.length())).mapErr(|e| self.badNumber())?
359
- Ok(JsonNum(value: mv * 10.pow(Float(ev))))
360
371
 
361
372
  fun parseString(self) -> Result[Str, JsonError] =
362
373
  self.advance()
@@ -457,15 +468,28 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
457
468
  buf.writeRune(cp)
458
469
  Ok(Unit)
459
470
 
471
+ # Whether one more array or object fits under `MaxJsonDepth`; notes why not.
472
+ fun deeper(self) -> Bool =
473
+ if self.depth >= MaxJsonDepth
474
+ self.note("nested too deeply (more than {MaxJsonDepth} arrays and objects)")
475
+ false
476
+ else
477
+ self.depth = self.depth + 1
478
+ true
479
+
460
480
  fun parseArray(self) -> Result[Json, JsonError] =
461
- self.advance()
462
- self.skipSpace()
463
- items := Slice[Json]()
464
- if self.peek() == 93
481
+ if !self.deeper()
465
- self.advance()
482
+ Err(InvalidJson)
466
- Ok(JsonArr(items: items))
467
483
  else
484
+ self.advance()
485
+ self.skipSpace()
486
+ items := Slice[Json]()
487
+ if self.peek() == 93
488
+ self.advance()
489
+ self.depth = self.depth - 1
490
+ Ok(JsonArr(items: items))
491
+ else
468
- self.parseArrayItems(items)
492
+ self.parseArrayItems(items)
469
493
 
470
494
  # `parseArray`'s loop: the values up to the closing bracket, pushed onto `items`.
471
495
  fun parseArrayItems(self, items: Slice[Json]) -> Result[Json, JsonError] =
@@ -476,6 +500,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
476
500
  c := self.peek()
477
501
  if c == 93
478
502
  self.advance()
503
+ self.depth = self.depth - 1
479
504
  Ok(JsonArr(items: items))
480
505
  else if c != 44
481
506
  self.note("expected ',' or ']'")
@@ -485,14 +510,18 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
485
510
  self.parseArrayItems(items)
486
511
 
487
512
  fun parseObject(self) -> Result[Json, JsonError] =
488
- self.advance()
489
- self.skipSpace()
490
- pairs: Map[Str, Json] := Map.empty()
491
- if self.peek() == 125
513
+ if !self.deeper()
492
- self.advance()
514
+ Err(InvalidJson)
493
- Ok(JsonObj(fields: pairs))
494
515
  else
516
+ self.advance()
517
+ self.skipSpace()
518
+ pairs: Map[Str, Json] := Map.empty()
519
+ if self.peek() == 125
520
+ self.advance()
521
+ self.depth = self.depth - 1
522
+ Ok(JsonObj(fields: pairs))
523
+ else
495
- self.parsePairs(pairs)
524
+ self.parsePairs(pairs)
496
525
 
497
526
  # `parseObject`'s loop: the `key: value` pairs up to the closing brace, set into `pairs`.
498
527
  fun parsePairs(self, pairs: Map[Str, Json]) -> Result[Json, JsonError] =
@@ -515,6 +544,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
515
544
  c := self.peek()
516
545
  if c == 125
517
546
  self.advance()
547
+ self.depth = self.depth - 1
518
548
  Ok(JsonObj(fields: pairs))
519
549
  else if c != 44
520
550
  self.note("expected ',' or '}}'")
@@ -523,10 +553,6 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
523
553
  self.advance()
524
554
  self.parsePairs(pairs)
525
555
 
526
- fun exponentIndex(text: Str) -> Int =
527
- e := text.indexOf("e")
528
- if e >= 0 then e else text.indexOf("E")
529
-
530
556
  fun hexDigitValue(b: Int) -> Int =
531
557
  if b >= 48 && b <= 57
532
558
  b - 48
@@ -752,13 +778,13 @@ test "escapes a 50000 character string of quotes and newlines"
752
778
 
753
779
 
754
780
  test "extension: Int.toJson encodes a number"
755
- assert 42.toJson().toStr() == "42.0"
781
+ assert 42.toJson().toStr() == "42"
756
782
 
757
783
  test "extension: Slice.toJson encodes an array"
758
- assert [1, 2, 3].toSlice().toJson().toStr() == "[1.0,2.0,3.0]"
784
+ assert [1, 2, 3].toSlice().toJson().toStr() == "[1,2,3]"
759
785
 
760
786
  test "extension: nested Slice.toJson recurses through T.toJson"
761
- assert [[1].toSlice(), [2, 3].toSlice()].toSlice().toJson().toStr() == "[[1.0],[2.0,3.0]]"
787
+ assert [[1].toSlice(), [2, 3].toSlice()].toSlice().toJson().toStr() == "[[1],[2,3]]"
762
788
 
763
789
  test "api: field missing, wrong container, optField"
764
790
  o := Json.fromStr("{{\"a\":1}}")!
@@ -784,7 +810,7 @@ test "nested_list_of_lists round-trips"
784
810
  v := jsonTestDecodeNested("[[1,2],[3],[]]")!
785
811
  assert v.length() == 3
786
812
  assert v.get(0)!.get(1)! == 2
787
- assert Json.encode(v) == "[[1.0,2.0],[3.0],[]]"
813
+ assert Json.encode(v) == "[[1,2],[3],[]]"
788
814
  assert jsonTestDecodeNested("[[1,\"x\"]]").unwrapOr(Slice[Slice[Int]]()).length() == 0
789
815
 
790
816
  test "map_non_object_rejected"
std/decimal.plum ADDED
@@ -0,0 +1,436 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Str
6
+ import std/Buffer
7
+ import std/Byte
8
+ import std/Slice
9
+ import std/Option
10
+ import std/math
11
+
12
+ # Exact conversion between decimal text and Float, on small unsigned big integers.
13
+ #
14
+ # - `decimal.parse(text)` reads `[+-]digits[.digits][(e|E)[+-]digits]` (digits on at least
15
+ # one side of the point) as the Float nearest its exact value, ties to even, as IEEE 754
16
+ # and every correct `strtod` give: `0.3` is the Float literal `0.3`, `1e400` is Infinity,
17
+ # `1e-400` is 0.0. Up to 15 digits and a power of ten up to 22 it is one Float multiply
18
+ # or divide (both exact operands, so rounded once); otherwise a Float estimate is stepped
19
+ # to the nearest Float by comparing the exact value with the halfway points between
20
+ # Floats in big integer arithmetic.
21
+ # - `decimal.shortest(x)` is the shortest digits that parse back to `x` (Burger and Dybvig's
22
+ # free-format algorithm, exact in big integers), and `decimal.format(x)` writes them the
23
+ # way JavaScript's `String(x)` does: `0.1`, `123`, `1e+21`, `1.5e-7`.
24
+ #
25
+ # A big integer is a `Slice[Int]` of 28-bit limbs, least significant first, with no zero
26
+ # limb on top (zero is the empty slice). Products of two limbs fit an Int with room for a
27
+ # carry.
28
+
29
+ LimbBits = 28
30
+ LimbMask = 0xFFF_FFFF
31
+
32
+ # ---- big integers ----
33
+
34
+ fun bigOf(n: Int) -> Slice[Int] =
35
+ out := Slice[Int]()
36
+ pushLimbs(out, n)
37
+ out
38
+
39
+ # Appends the limbs of `n` (n >= 0) on top of `out`.
40
+ fun pushLimbs(out: Slice[Int], n: Int) -> Unit =
41
+ if n > 0
42
+ out.push(n & LimbMask)
43
+ pushLimbs(out, n >> LimbBits)
44
+
45
+ fun bigCopy(a: Slice[Int]) -> Slice[Int] = a.sublist(0, a.length())
46
+
47
+ # `a = a * f + add` in place, for 0 < f < 2^28 and 0 <= add < 2^28.
48
+ fun bigMulAdd(a: Slice[Int], f: Int, add: Int) -> Unit =
49
+ pushLimbs(a, mulAddFrom(a, f, 0, add))
50
+
51
+ fun mulAddFrom(a: Slice[Int], f: Int, i: Int, carry: Int) -> Int =
52
+ if i >= a.length()
53
+ carry
54
+ else
55
+ p := a.atUnchecked(i) * f + carry
56
+ a.putAt(i, p & LimbMask)
57
+ mulAddFrom(a, f, i + 1, p >> LimbBits)
58
+
59
+ # `a * 5^k`, in place.
60
+ fun bigMulPow5(a: Slice[Int], k: Int) -> Unit =
61
+ if k >= 12
62
+ bigMulAdd(a, 244140625, 0)
63
+ bigMulPow5(a, k - 12)
64
+ else if k > 0
65
+ bigMulAdd(a, pow5(k), 0)
66
+
67
+ fun pow5(k: Int) -> Int = if k <= 0 then 1 else 5 * pow5(k - 1)
68
+
69
+ # A new big integer: `a * 2^k` (k >= 0).
70
+ fun bigShl(a: Slice[Int], k: Int) -> Slice[Int] =
71
+ if a.isEmpty() || k == 0
72
+ bigCopy(a)
73
+ else
74
+ b := bigCopy(a)
75
+ bigMulAdd(b, 1 << {k % LimbBits}, 0)
76
+ out := Slice[Int]()
77
+ for _ := range k / LimbBits
78
+ out.push(0)
79
+ out.add(b)
80
+ out
81
+
82
+ # A new big integer: `a * 10^k` (k >= 0).
83
+ fun bigMulPow10(a: Slice[Int], k: Int) -> Slice[Int] =
84
+ b := bigCopy(a)
85
+ bigMulPow5(b, k)
86
+ bigShl(b, k)
87
+
88
+ # -1, 0 or 1 as `a` is below, equal to or above `b`.
89
+ fun bigCmp(a: Slice[Int], b: Slice[Int]) -> Int =
90
+ if a.length() != b.length()
91
+ if a.length() < b.length() then -1 else 1
92
+ else
93
+ cmpFrom(a, b, a.length() - 1)
94
+
95
+ fun cmpFrom(a: Slice[Int], b: Slice[Int], i: Int) -> Int =
96
+ if i < 0
97
+ 0
98
+ else
99
+ x := a.atUnchecked(i)
100
+ y := b.atUnchecked(i)
101
+ if x != y
102
+ if x < y then -1 else 1
103
+ else
104
+ cmpFrom(a, b, i - 1)
105
+
106
+ # A new big integer: `a + b`.
107
+ fun bigAdd(a: Slice[Int], b: Slice[Int]) -> Slice[Int] =
108
+ out := Slice[Int]()
109
+ n := if a.length() > b.length() then a.length() else b.length()
110
+ addFrom(a, b, out, 0, n, 0)
111
+ out
112
+
113
+ fun addFrom(a: Slice[Int], b: Slice[Int], out: Slice[Int], i: Int, n: Int, carry: Int) -> Unit =
114
+ if i < n
115
+ s := limbAt(a, i) + limbAt(b, i) + carry
116
+ out.push(s & LimbMask)
117
+ addFrom(a, b, out, i + 1, n, s >> LimbBits)
118
+ else if carry > 0
119
+ out.push(carry)
120
+
121
+ # A new big integer: `a - b`, for a >= b.
122
+ fun bigSub(a: Slice[Int], b: Slice[Int]) -> Slice[Int] =
123
+ out := Slice[Int]()
124
+ subFrom(a, b, out, 0, 0)
125
+ trimTop(out)
126
+ out
127
+
128
+ fun subFrom(a: Slice[Int], b: Slice[Int], out: Slice[Int], i: Int, borrow: Int) -> Unit =
129
+ if i < a.length()
130
+ d := a.atUnchecked(i) - limbAt(b, i) - borrow
131
+ out.push(if d < 0 then d + {1 << LimbBits} else d)
132
+ subFrom(a, b, out, i + 1, if d < 0 then 1 else 0)
133
+
134
+ fun limbAt(a: Slice[Int], i: Int) -> Int = if i < a.length() then a.atUnchecked(i) else 0
135
+
136
+ # Drops zero limbs from the top.
137
+ fun trimTop(a: Slice[Int]) -> Unit =
138
+ if a.length() > 0 && a.atUnchecked(a.length() - 1) == 0
139
+ _ := a.pop()
140
+ trimTop(a)
141
+
142
+ # The big integer of the decimal digits `ds[i..j)`, eight digits per step.
143
+ fun bigOfDigits(ds: Str, i: Int, j: Int, acc: Slice[Int]) -> Slice[Int] =
144
+ if i >= j
145
+ acc
146
+ else
147
+ k := if j - i < 8 then j - i else 8
148
+ v := digitsValue(ds, i, i + k, 0)
149
+ bigMulAdd(acc, pow10Int(k), 0)
150
+ bigAddSmall(acc, v)
151
+ bigOfDigits(ds, i + k, j, acc)
152
+
153
+ # `a + v` in place, for 0 <= v < 2^28.
154
+ fun bigAddSmall(a: Slice[Int], v: Int) -> Unit =
155
+ pushLimbs(a, addSmallFrom(a, 0, v))
156
+
157
+ fun addSmallFrom(a: Slice[Int], i: Int, carry: Int) -> Int =
158
+ if carry == 0 || i >= a.length()
159
+ carry
160
+ else
161
+ s := a.atUnchecked(i) + carry
162
+ a.putAt(i, s & LimbMask)
163
+ addSmallFrom(a, i + 1, s >> LimbBits)
164
+
165
+ fun digitsValue(ds: Str, i: Int, j: Int, acc: Int) -> Int =
166
+ if i >= j then acc else digitsValue(ds, i + 1, j, acc * 10 + ds.byteAtUnchecked(i) - 48)
167
+
168
+ fun pow10Int(k: Int) -> Int = if k <= 0 then 1 else 10 * pow10Int(k - 1)
169
+
170
+ # 10^k as a Float, exact for 0 <= k <= 22.
171
+ fun pow10Exact(k: Int) -> Float = match k
172
+ 0 => 1.0
173
+ 1 => 10.0
174
+ 2 => 100.0
175
+ 3 => 1000.0
176
+ 4 => 10000.0
177
+ 5 => 100000.0
178
+ 6 => 1000000.0
179
+ 7 => 10000000.0
180
+ 8 => 100000000.0
181
+ 9 => 1000000000.0
182
+ 10 => 10000000000.0
183
+ 11 => 100000000000.0
184
+ 12 => 1000000000000.0
185
+ 13 => 10000000000000.0
186
+ 14 => 100000000000000.0
187
+ 15 => 1000000000000000.0
188
+ 16 => 10000000000000000.0
189
+ 17 => 100000000000000000.0
190
+ 18 => 1000000000000000000.0
191
+ 19 => 10000000000000000000.0
192
+ 20 => 100000000000000000000.0
193
+ 21 => 1000000000000000000000.0
194
+ _ => 10000000000000000000000.0
195
+
196
+ # x * 10^k, approximately (a few ulps), for any k: in steps that stay in Float's range.
197
+ fun scaleApprox(x: Float, k: Int) -> Float =
198
+ if k > 22
199
+ scaleApprox(x * 1e22, k - 22)
200
+ else if k >= 0
201
+ x * pow10Exact(k)
202
+ else if k < -22
203
+ scaleApprox(x / 1e22, k + 22)
204
+ else
205
+ x / pow10Exact(0 - k)
206
+
207
+ # ---- decimal text to Float ----
208
+
209
+ # What `parse` reads off the text: the significant digits (no point), the power of ten they
210
+ # are scaled by, the sign, and whether the text was a number at all.
211
+ struct Scan(mut digits: Buffer, mut exp: Int, mut neg: Bool, mut ok: Bool, mut seen: Int, mut pos: Int)
212
+
213
+ # The Float nearest the decimal `text`, or None if it isn't one (see the top of the file).
214
+ fun parse(text: Str) -> Option[Float] =
215
+ sc := Scan(digits: Buffer(), exp: 0, neg: false, ok: true, seen: 0, pos: 0)
216
+ n := text.length()
217
+ if n > 0 && {text.byteAt(0) == 45 || text.byteAt(0) == 43}
218
+ sc.neg = text.byteAt(0) == 45
219
+ sc.pos = 1
220
+ scanDigits(text, sc, false)
221
+ if sc.pos < n && text.byteAt(sc.pos) == 46
222
+ sc.pos = sc.pos + 1
223
+ scanDigits(text, sc, true)
224
+ if sc.seen == 0
225
+ sc.ok = false
226
+ if sc.ok && sc.pos < n && {text.byteAt(sc.pos) == 101 || text.byteAt(sc.pos) == 69}
227
+ sc.pos = sc.pos + 1
228
+ eneg := sc.pos < n && text.byteAt(sc.pos) == 45
229
+ if sc.pos < n && {text.byteAt(sc.pos) == 45 || text.byteAt(sc.pos) == 43}
230
+ sc.pos = sc.pos + 1
231
+ start := sc.pos
232
+ e := expDigits(text, sc, 0)
233
+ if sc.pos == start
234
+ sc.ok = false
235
+ sc.exp = sc.exp + {if eneg then 0 - e else e}
236
+ if !sc.ok || sc.pos != n
237
+ None
238
+ else
239
+ v := toFloat(sc.digits.toStr(), sc.exp)
240
+ Some(if sc.neg then -v else v)
241
+
242
+ # Reads digits from `sc.pos` on into `sc.digits` (leading zeros of the number skipped); a
243
+ # digit after the point lowers the exponent by one.
244
+ fun scanDigits(text: Str, sc: Scan, frac: Bool) -> Unit =
245
+ if sc.pos < text.length()
246
+ b := text.byteAtUnchecked(sc.pos)
247
+ if b >= 48 && b <= 57
248
+ if b != 48 || sc.digits.length() > 0
249
+ sc.digits.writeByte(Byte(b))
250
+ if frac
251
+ sc.exp = sc.exp - 1
252
+ sc.seen = sc.seen + 1
253
+ sc.pos = sc.pos + 1
254
+ scanDigits(text, sc, frac)
255
+
256
+ # The exponent's digits from `sc.pos` on, held at a million (far past any Float).
257
+ fun expDigits(text: Str, sc: Scan, acc: Int) -> Int =
258
+ if sc.pos < text.length() && text.byteAtUnchecked(sc.pos) >= 48 && text.byteAtUnchecked(sc.pos) <= 57
259
+ d := text.byteAtUnchecked(sc.pos) - 48
260
+ sc.pos = sc.pos + 1
261
+ expDigits(text, sc, if acc > 1000000 then acc else acc * 10 + d)
262
+ else
263
+ acc
264
+
265
+ # The Float nearest `digits * 10^exp`, for a string of decimal digits (zeros allowed at
266
+ # either end, or none at all: zero).
267
+ fun toFloat(digits: Str, exp: Int) -> Float =
268
+ a := firstNonZero(digits, 0)
269
+ if a >= digits.length()
270
+ 0.0
271
+ else
272
+ b := lastNonZero(digits, digits.length() - 1)
273
+ ds := digits.sub(a, b + 1)
274
+ e := exp + {digits.length() - 1 - b}
275
+ n := ds.length()
276
+ if n + e > 310
277
+ 1.0 / 0.0
278
+ else if n + e < -324
279
+ 0.0
280
+ else if n <= 15 && e >= -22 && e <= 22
281
+ m := Float(digitsValue(ds, 0, n, 0))
282
+ if e >= 0 then m * pow10Exact(e) else m / pow10Exact(0 - e)
283
+ else
284
+ k := if n < 18 then n else 18
285
+ guess := scaleApprox(Float(digitsValue(ds, 0, k, 0)), e + n - k)
286
+ big := bigOfDigits(ds, 0, n, Slice[Int]())
287
+ left := if e >= 0 then bigMulPow10(big, e) else big
288
+ nearest(left, if e >= 0 then 0 else e, guess)
289
+
290
+ fun firstNonZero(s: Str, i: Int) -> Int =
291
+ if i < s.length() && s.byteAtUnchecked(i) == 48 then firstNonZero(s, i + 1) else i
292
+
293
+ fun lastNonZero(s: Str, i: Int) -> Int =
294
+ if i > 0 && s.byteAtUnchecked(i) == 48 then lastNonZero(s, i - 1) else i
295
+
296
+ # The exact value is `left * 10^e` (e <= 0; with e = 0 `left` already holds the whole
297
+ # value). Steps `z` one Float at a time until it is the one nearest that value.
298
+ fun nearest(left: Slice[Int], e: Int, z: Float) -> Float =
299
+ if z > Float.Max
300
+ z
301
+ else
302
+ bits := z.toBits()
303
+ expo := {bits >> 52} & 0x7FF
304
+ frac := bits & 0xF_FFFF_FFFF_FFFF
305
+ mz := if expo == 0 then frac else frac | 0x10_0000_0000_0000
306
+ ez := if expo == 0 then -1074 else expo - 1075
307
+ up := cmpExact(left, e, 2 * mz + 1, ez - 1)
308
+ if up > 0
309
+ nearest(left, e, Float.fromBits(bits + 1))
310
+ else if up == 0
311
+ if mz % 2 == 0 then z else Float.fromBits(bits + 1)
312
+ else if mz == 0
313
+ z
314
+ else
315
+ down := if frac == 0 && expo > 1 then cmpExact(left, e, 4 * mz - 1, ez - 2) else cmpExact(left, e, 2 * mz - 1, ez - 1)
316
+ if down < 0
317
+ nearest(left, e, Float.fromBits(bits - 1))
318
+ else if down == 0
319
+ if mz % 2 == 0 then z else Float.fromBits(bits - 1)
320
+ else
321
+ z
322
+
323
+ # The sign of `left * 10^e - m * 2^s`, exactly (e <= 0, m > 0).
324
+ fun cmpExact(left: Slice[Int], e: Int, m: Int, s: Int) -> Int =
325
+ right := bigOf(m)
326
+ bigMulPow5(right, 0 - e)
327
+ # left * 2^e against right * 2^s.
328
+ d := e - s
329
+ if d >= 0 then bigCmp(bigShl(left, d), right) else bigCmp(left, bigShl(right, 0 - d))
330
+
331
+ # ---- Float to the shortest decimal ----
332
+
333
+ # The shortest digits of `x` that parse back to it, with `point`, their decimal exponent:
334
+ # x = 0.d1d2...dn * 10^point. `x` must be finite and above 0.
335
+ struct Digits(digits: Str, point: Int)
336
+
337
+ fun shortest(x: Float) -> Digits =
338
+ bits := x.toBits()
339
+ expo := {bits >> 52} & 0x7FF
340
+ frac := bits & 0xF_FFFF_FFFF_FFFF
341
+ f := if expo == 0 then frac else frac | 0x10_0000_0000_0000
342
+ e := if expo == 0 then -1074 else expo - 1075
343
+ even := f % 2 == 0
344
+ # Twice the value and the gaps to the neighbouring Floats, as r / s, mp / s and mm / s.
345
+ lowGap := frac == 0 && expo > 1
346
+ r0 := if e >= 0
347
+ if lowGap then bigShl(bigOf(f), e + 2) else bigShl(bigOf(f), e + 1)
348
+ else
349
+ if lowGap then bigOf(4 * f) else bigOf(2 * f)
350
+ s0 := if e >= 0
351
+ if lowGap then bigOf(4) else bigOf(2)
352
+ else
353
+ if lowGap then bigShl(bigOf(1), 2 - e) else bigShl(bigOf(1), 1 - e)
354
+ mp0 := if e >= 0
355
+ if lowGap then bigShl(bigOf(1), e + 1) else bigShl(bigOf(1), e)
356
+ else
357
+ if lowGap then bigOf(2) else bigOf(1)
358
+ mm0 := if e >= 0 then bigShl(bigOf(1), e) else bigOf(1)
359
+ bitLen := 64 - f.leadingZeros()
360
+ k := Int({Float(e + bitLen - 1) * 0.30102999566398114 - 0.0000000001}.ceil())
361
+ r := if k >= 0 then r0 else bigMulPow10(r0, 0 - k)
362
+ s := if k >= 0 then bigMulPow10(s0, k) else s0
363
+ mp := if k >= 0 then mp0 else bigMulPow10(mp0, 0 - k)
364
+ mm := if k >= 0 then mm0 else bigMulPow10(mm0, 0 - k)
365
+ high := bigCmp(bigAdd(r, mp), s)
366
+ out := Buffer()
367
+ if high > 0 || even && high == 0
368
+ generate(r, s, mp, mm, even, out)
369
+ Digits(digits: out.toStr(), point: k + 1)
370
+ else
371
+ generate(bigMulPow10(r, 1), s, bigMulPow10(mp, 1), bigMulPow10(mm, 1), even, out)
372
+ Digits(digits: out.toStr(), point: k)
373
+
374
+ # Writes the digits of r / s into `out` until the digits so far are within the gaps
375
+ # (inclusive when `even`: a tie parses to the even Float, which is `x`).
376
+ fun generate(r: Slice[Int], s: Slice[Int], mp: Slice[Int], mm: Slice[Int], even: Bool, out: Buffer) -> Unit =
377
+ q := quotientDigit(r, s, 0)
378
+ rest := q.second
379
+ d := q.first
380
+ low := bigCmp(rest, mm)
381
+ tc1 := low < 0 || even && low == 0
382
+ high := bigCmp(bigAdd(rest, mp), s)
383
+ tc2 := high > 0 || even && high == 0
384
+ if !tc1 && !tc2
385
+ out.writeByte(Byte(48 + d))
386
+ generate(bigMulPow10(rest, 1), s, bigMulPow10(mp, 1), bigMulPow10(mm, 1), even, out)
387
+ else if tc1 && !tc2
388
+ out.writeByte(Byte(48 + d))
389
+ else if !tc1 && tc2
390
+ out.writeByte(Byte(49 + d))
391
+ else
392
+ half := bigCmp(bigShl(rest, 1), s)
393
+ out.writeByte(Byte(if half < 0 then 48 + d else 49 + d))
394
+
395
+ struct QR(first: Int, second: Slice[Int])
396
+
397
+ # r / s as a digit 0..9 and the remainder, by subtracting (r < 10 s).
398
+ fun quotientDigit(r: Slice[Int], s: Slice[Int], d: Int) -> QR =
399
+ if bigCmp(r, s) < 0 then QR(first: d, second: r) else quotientDigit(bigSub(r, s), s, d + 1)
400
+
401
+ # `x` as JavaScript's `String(x)` writes it (and JSON with it): the shortest digits that
402
+ # parse back to `x`, in plain notation from 1e-6 up to 1e21 (`0.000001`, `123.5`,
403
+ # `100000000000000000000`) and in exponent notation outside it (`1e+21`, `1.5e-7`). `-0`
404
+ # for minus zero, `NaN`, `Infinity` and `-Infinity` for the rest.
405
+ fun format(x: Float) -> Str =
406
+ if x != x
407
+ "NaN"
408
+ else if x > Float.Max
409
+ "Infinity"
410
+ else if x < 0.0 - Float.Max
411
+ "-Infinity"
412
+ else if x == 0.0
413
+ if 1.0 / x < 0.0 then "-0" else "0"
414
+ else if x < 0.0
415
+ "-" + formatPositive(0.0 - x)
416
+ else
417
+ formatPositive(x)
418
+
419
+ fun formatPositive(x: Float) -> Str =
420
+ if x < 9007199254740992.0 && x.trunc() == x
421
+ Int(x).toStr()
422
+ else
423
+ sh := shortest(x)
424
+ ds := sh.digits
425
+ n := ds.length()
426
+ k := sh.point
427
+ if k >= n && k <= 21
428
+ ds + "0".repeat(k - n)
429
+ else if k > 0 && k <= 21
430
+ ds.sub(0, k) + "." + ds.sub(k, n)
431
+ else if k > -6 && k <= 0
432
+ "0." + "0".repeat(0 - k) + ds
433
+ else
434
+ mant := if n == 1 then ds else ds.sub(0, 1) + "." + ds.sub(1, n)
435
+ x10 := k - 1
436
+ mant + "e" + {if x10 < 0 then "-" else "+"} + {if x10 < 0 then 0 - x10 else x10}.toStr()
tests/std/decimal.plum ADDED
@@ -0,0 +1,52 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Str
4
+ import std/Option
5
+ import std/decimal
6
+ import std/Pair
7
+
8
+ fun roundTrips(bits: Int) -> Bool =
9
+ x := Float.fromBits(bits & 0x7FFF_FFFF_FFFF_FFFF)
10
+ if x != x || x > Float.Max
11
+ true
12
+ else
13
+ decimal.parse(decimal.format(x))! == x && decimal.parse(decimal.format(0.0 - x))! == 0.0 - x
14
+
15
+ test "decimal.parse: nearest Float, edges, bad text"
16
+ assert decimal.parse("0.3")! == 0.3
17
+ assert decimal.parse("123.456")! == 123.456
18
+ assert decimal.parse("0.1234567890123")! == 0.1234567890123
19
+ assert decimal.parse("1e400")! > Float.Max
20
+ assert decimal.parse("1e-400")! == 0.0
21
+ assert decimal.parse("2.2250738585072014e-308")! == 2.2250738585072014e-308
22
+ assert decimal.parse("4.9406564584124654e-324")! == 4.9406564584124654e-324
23
+ assert decimal.parse("9007199254740993")! == 9007199254740992.0
24
+ assert decimal.parse("9007199254740995")! == 9007199254740996.0
25
+ assert decimal.parse("1.7976931348623157e308")! == Float.Max
26
+ assert decimal.parse("3.14159265358979")! == 3.14159265358979
27
+ assert decimal.parse("x").isNone()
28
+ assert decimal.parse("1e").isNone()
29
+ assert decimal.parse(".").isNone()
30
+
31
+ test "decimal.format: shortest digits, as JavaScript writes them"
32
+ assert decimal.format(0.1) == "0.1"
33
+ assert decimal.format(123.0) == "123"
34
+ assert decimal.format(0.1234567) == "0.1234567"
35
+ assert decimal.format(1e21) == "1e+21"
36
+ assert decimal.format(1e-7) == "1e-7"
37
+ assert decimal.format(Float.Max) == "1.7976931348623157e+308"
38
+ assert decimal.format(5e-324) == "5e-324"
39
+ assert decimal.format(0.1 + 0.2) == "0.30000000000000004"
40
+ assert decimal.format(-1.5) == "-1.5"
41
+ assert decimal.format(1e20) == "100000000000000000000"
42
+ assert decimal.format(123456.789) == "123456.789"
43
+
44
+ test "6000 random bit patterns (and their negatives) round-trip through format and parse"
45
+ bad := 1.to(3000).fold(Pair(first: 88172645463325252, second: 0), |acc, i|
46
+ x0 := acc.first
47
+ x1 := x0 ^ {x0 << 13}
48
+ x2 := x1 ^ {x1 >> 7}
49
+ x3 := x2 ^ {x2 << 17}
50
+ Pair(first: x3, second: if roundTrips(x3) && roundTrips(x3 >> 12) then acc.second else acc.second + 1)
51
+ )
52
+ assert bad.second == 0
tests/std/json.plum ADDED
@@ -0,0 +1,95 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Str
4
+ import std/Option
5
+ import std/Result
6
+ import std/Slice
7
+ import std/Map
8
+ import std/Json
9
+
10
+ fun num(s: Str) -> Float = Json.fromStr(s)!.asFloat()!
11
+
12
+ fun bad(s: Str) -> Bool = Json.fromStr(s).isErr()
13
+
14
+ fun again(s: Str) -> Str = Json.encode(Json.fromStr(s)!)
15
+
16
+ test "integral numbers are written without a fraction"
17
+ assert Json.encode(123) == "123"
18
+ assert Json.encode(-7) == "-7"
19
+ assert Json.encode(0) == "0"
20
+ assert Json.encode(9007199254740991) == "9007199254740991"
21
+ assert Json.encode(4611686018427387904) == "4611686018427388000"
22
+ assert Json.encode(2.0) == "2"
23
+ assert Json.encode([1, 2].toSlice()) == "[1,2]"
24
+
25
+ test "floats are written with the shortest digits that read back the same"
26
+ assert Json.encode(0.1234567) == "0.1234567"
27
+ assert Json.encode(0.1) == "0.1"
28
+ assert Json.encode(0.1 + 0.2) == "0.30000000000000004"
29
+ assert Json.encode(0.0000001) == "1e-7"
30
+ assert Json.encode(1000000000000000000000.0) == "1e+21"
31
+ assert Json.encode(1.5e300) == "1.5e+300"
32
+ assert Json.encode(-2.5) == "-2.5"
33
+ assert Json.encode(5e-324) == "5e-324"
34
+ assert Json.encode(Float.Max) == "1.7976931348623157e+308"
35
+
36
+ test "NaN and the infinities are written null"
37
+ assert Json.encode(0.0 / 0.0) == "null"
38
+ assert Json.encode(1.0 / 0.0) == "null"
39
+ assert Json.encode(-1.0 / 0.0) == "null"
40
+
41
+ test "parse then encode keeps every digit"
42
+ assert again("3.14159265358979") == "3.14159265358979"
43
+ assert again("0.1e1") == "1"
44
+ assert again("1E-2") == "0.01"
45
+ assert again("123456789012345678") == "123456789012345680"
46
+ assert again("2.2250738585072014e-308") == "2.2250738585072014e-308"
47
+ assert again("[0.5,-0,1e2]") == "[0.5,-0,100]"
48
+
49
+ test "numbers parse to the nearest Float"
50
+ assert num("0.3") == 0.3
51
+ assert num("123.456") == 123.456
52
+ assert num("0.1234567890123") == 0.1234567890123
53
+ assert num("9007199254740993") == 9007199254740992.0
54
+ assert num("1.7976931348623157e308") == Float.Max
55
+ assert num("4.9406564584124654e-324") == 5e-324
56
+ assert num("1e-400") == 0.0
57
+ assert num("0.{"0".repeat(400)}1e400") == 0.1
58
+ assert num("{"1".repeat(30)}e-29") == 1.1111111111111112
59
+
60
+ test "invalid numbers are errors: leading zeros, a bare sign or point, out of range"
61
+ assert bad("01") && bad("-01") && bad("00")
62
+ assert !bad("0") && !bad("-0") && !bad("0.5") && !bad("0e5")
63
+ assert bad("-") && bad("1.") && bad(".5") && bad("1e") && bad("1e+") && bad("+1")
64
+ assert bad("1e400") && bad("-1e400")
65
+ match Json.parse("1e400")
66
+ Parsed(v) =>
67
+ assert false
68
+ Failed(pos, text) =>
69
+ assert text == "number out of range"
70
+
71
+ test "nesting past MaxJsonDepth is an error, not a stack overflow"
72
+ ok := "[".repeat(1000) + "]".repeat(1000)
73
+ assert Json.fromStr(ok).isOk()
74
+ assert bad("[".repeat(1001) + "]".repeat(1001))
75
+ assert bad("[".repeat(200000) + "]".repeat(200000))
76
+ assert bad("{{\"a\":".repeat(1001) + "1" + "}}".repeat(1001))
77
+ wide := "[" + "[],".repeat(5000) + "[]]"
78
+ assert Json.fromStr(wide)!.asList()!.length() == 5001
79
+ match Json.parse("[".repeat(2000))
80
+ Parsed(v) =>
81
+ assert false
82
+ Failed(pos, text) =>
83
+ assert pos == 1000 && text.startsWith("nested too deeply")
84
+
85
+ test "Float.parse: nearest Float, exponents, signs"
86
+ assert Float.parse("0.3")! == 0.3
87
+ assert Float.parse("123.456")! == 123.456
88
+ assert Float.parse("0.1234567890123")! == 0.1234567890123
89
+ assert Float.parse("1e5")! == 100000.0
90
+ assert Float.parse("-2.5E-3")! == -0.0025
91
+ assert Float.parse("+.5")! == 0.5
92
+ assert Float.parse("5.")! == 5.0
93
+ assert Float.parse("1e400")! > Float.Max
94
+ assert Float.parse("").isErr() && Float.parse("-").isErr() && Float.parse(".").isErr()
95
+ assert Float.parse("1x").isErr() && Float.parse("1e").isErr() && Float.parse("e5").isErr()
tests/std/parse_tanh.plum ADDED
@@ -0,0 +1,38 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Str
4
+ import std/Option
5
+ import std/Result
6
+
7
+ fun overflowed(s: Str) -> Bool = match Int.parse(s)
8
+ Err(NumOverflow) => true
9
+ _ => false
10
+
11
+ test "Int.parse: the whole range, and an overflow Err past it"
12
+ assert Int.parse("9223372036854775807")! == Int.Max
13
+ assert Int.parse("-9223372036854775808")! == Int.Min
14
+ assert Int.parse("+42")! == 42
15
+ assert Int.parse("-0")! == 0
16
+ assert overflowed("9223372036854775808")
17
+ assert overflowed("-9223372036854775809")
18
+ assert overflowed("99999999999999999999")
19
+ assert overflowed("-99999999999999999999")
20
+ assert !overflowed("12x")
21
+ assert Int.parse("12x").isErr()
22
+ assert Int.parse("").isErr() && Int.parse("-").isErr()
23
+
24
+ test "tanh: no NaN for large |x|, odd, exact near 0"
25
+ assert 800.0.tanh() == 1.0
26
+ assert {-800.0}.tanh() == -1.0
27
+ assert 20.0.tanh() == 1.0
28
+ assert {1.0 / 0.0}.tanh() == 1.0
29
+ assert {-1.0 / 0.0}.tanh() == -1.0
30
+ n := 0.0 / 0.0
31
+ assert n.tanh().isNaN()
32
+ assert 0.0.tanh() == 0.0
33
+ assert 1.0 / {-0.0}.tanh() < 0.0
34
+ assert 1e-300.tanh() == 1e-300
35
+ assert {0.5.tanh() - 0.46211715726000974}.abs() < 1e-15
36
+ assert {1.0.tanh() - 0.7615941559557649}.abs() < 1e-15
37
+ assert {{-3.0}.tanh() + 0.9950547536867305}.abs() < 1e-15
38
+ assert {0.25.tanh() - 0.24491866240370913}.abs() < 1e-15