plum

#treesitter#compiler#wasm

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

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


de7eacd — Peter John 2026-11-10T22:01:09+05:30
Json: whole numbers are exact Ints, and strings are checked as JSON requires
Files changed (3) hide show
  1. docs/std.md +1 -1
  2. std/encoding/Json.plum +89 -34
  3. tests/std/json.plum +47 -2
docs/std.md CHANGED
@@ -190,7 +190,7 @@ fun main() =
190
190
 
191
191
  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.
192
192
 
193
- 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`.
193
+ A number written as a whole number that fits an `Int` (no fraction, no exponent) is a `JsonInt`, kept exactly, and an `Int` is written with every digit: `Json.encode(Int.Max)` is `9223372036854775807`, and it decodes back to `Int.Max`. Every other number is a `JsonNum`, a `Float`; `j.asFloat()` reads either kind and `j.asInt()` (what `Int.fromJson` uses) takes a `JsonInt`, or a whole `JsonNum` below 2^53 (`1e3`, `2.0`). Writing a Float gives the shortest digits that read back as the same Float, the way JavaScript writes them: `Json.encode(2.0)` is `2`, `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, and so are a raw control character in a string, bytes that aren't well-formed UTF-8, and a `\u` surrogate without its partner (it has no UTF-8 form). 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`.
194
194
 
195
195
  ## Decimal
196
196
 
std/encoding/Json.plum CHANGED
@@ -40,14 +40,15 @@ enum JsonError =
40
40
  MissingField => "MissingField"
41
41
 
42
42
 
43
- # A parsed JSON value. Numbers are always stored as `Float` (JSON doesn't
43
+ # A parsed JSON value. A number is a `JsonInt` when it is written as a whole number (no
44
- # distinguish integers from floats the way Plum does), and `JsonArr`/
45
- # `JsonObj` nest `Json` itself — the same self-referential shape `Slice<T>`
44
+ # fraction, no exponent) that fits an `Int`, so every Int reads and writes back exactly, past
46
- # already uses internally for `Node<T>.next: Link<Node<T>>`.
45
+ # 2^53 too; any other number is a `JsonNum`, the Float nearest it. `asFloat` reads either.
46
+ # `JsonArr` and `JsonObj` nest `Json` itself.
47
47
  enum Json =
48
48
  | JsonNull
49
49
  | JsonBool(value: Bool)
50
50
  | JsonNum(value: Float)
51
+ | JsonInt(value: Int)
51
52
  | JsonStr(value: Str)
52
53
  | JsonArr(items: Slice<Json>)
53
54
  | JsonObj(fields: Map<Str, Json>)
@@ -68,6 +69,7 @@ enum Json =
68
69
  JsonNull => "null"
69
70
  JsonBool(value) => if value then "true" else "false"
70
71
  JsonNum(value) => numberText(value)
72
+ JsonInt(value) => value.toStr()
71
73
  JsonStr(value) => "\"{escapeJsonStr(value)}\""
72
74
  JsonArr(items) => "[{items.join(",")}]"
73
75
  JsonObj(fields) => "{{{jsonMapToStr(fields)}}}"
@@ -124,9 +126,25 @@ enum Json =
124
126
  JsonBool(value) => Ok(value)
125
127
  _ => Err(WrongJsonType)
126
128
 
129
+ # A number as a Float (a `JsonInt` past 2^53 is rounded to the nearest one).
127
130
  fun asFloat(self) -> Result<Float, JsonError> =
128
131
  match self
129
132
  JsonNum(value) => Ok(value)
133
+ JsonInt(value) => Ok(Float(value))
134
+ _ => Err(WrongJsonType)
135
+
136
+ # A whole number as an Int: a `JsonInt` exactly, or a `JsonNum` (`1e3`, `2.0`) that is
137
+ # whole and below 2^53 in size (past it a Float stands for several Ints). Anything else is
138
+ # `WrongJsonType`.
139
+ fun asInt(self) -> Result<Int, JsonError> =
140
+ match self
141
+ JsonInt(value) => Ok(value)
142
+ JsonNum(f) =>
143
+ if f >= 9007199254740992.0f || f <= -9007199254740992.0f
144
+ Err(WrongJsonType)
145
+ else
146
+ n := Int(f)
147
+ if Float(n) != f then Err(WrongJsonType) else Ok(n)
130
148
  _ => Err(WrongJsonType)
131
149
 
132
150
  fun asStr(self) -> Result<Str, JsonError> =
@@ -144,13 +162,7 @@ enum Json =
144
162
  JsonObj(fields) => Ok(fields)
145
163
  _ => Err(WrongJsonType)
146
164
 
147
- # `Map` has no built-in `toStr`/`join` (unlike `Slice`, which uses `join` for
148
- # `Json.toStr`'s `JsonList` case above) — a static taking the
149
- # `Buffer` as a captured-by-reference parameter instead of a closure sidesteps
150
- # `libs/std/list.plum`'s `join` note on closures: reassigning a CAPTURED
165
+ # An object's fields as `"key":value` pairs, in key order (`Map.toStr` writes `k => v`).
151
- # variable inside a closure body doesn't persist across that closure's own
152
- # repeated calls, but mutating a heap object's fields THROUGH a captured
153
- # reference (as `appendJsonPair` does to `buf`) does.
154
166
  fun jsonMapToStr(pairs: Map<Str, Json>) -> Str =
155
167
  buf := Buffer()
156
168
  for e := range pairs.entries()
@@ -357,7 +369,15 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
357
369
  else
358
370
  self.numberOf(self.src.sub(start, self.pos))
359
371
 
372
+ # A whole number that fits an Int is a `JsonInt`, exactly (`-0` stays a Float, to keep its
373
+ # sign); any other number is the nearest Float.
360
374
  fun numberOf(self, text: Str) -> Result<Json, JsonError> =
375
+ whole := !text.contains(".") && !text.contains("e") && !text.contains("E") && text != "-0"
376
+ match if whole then Int.parse(text).ok() else None
377
+ Some(n) => Ok(JsonInt(value: n))
378
+ None => self.floatOf(text)
379
+
380
+ fun floatOf(self, text: Str) -> Result<Json, JsonError> =
361
381
  match Decimal.parseFloat(text)
362
382
  Some(f) =>
363
383
  if f > Float.Max || f < 0.0 - Float.Max
@@ -384,11 +404,40 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
384
404
  else if c == 92
385
405
  self.parseEscape(buf)?
386
406
  self.parseStringBody(buf)
407
+ else if c < 0x20
408
+ self.note("unescaped control character in string")
409
+ Err(self.invalid())
387
410
  else
388
- n := self.src.codePointByteLength(self.pos)
411
+ n := if c < 0x80 then 1 else self.utf8Length()
412
+ if n == 0
413
+ self.note("invalid UTF-8 in string")
414
+ Err(self.invalid())
415
+ else
389
- buf.write(self.src.sub(self.pos, self.pos + n))
416
+ buf.write(self.src.sub(self.pos, self.pos + n))
390
- self.pos = self.pos + n
417
+ self.pos = self.pos + n
391
- self.parseStringBody(buf)
418
+ self.parseStringBody(buf)
419
+
420
+ # The length of the well-formed UTF-8 character at the cursor (whose first byte is 0x80 or
421
+ # more), or 0: no stray continuation byte, overlong form, surrogate, value past U+10FFFF or
422
+ # character cut off by the end of the text.
423
+ fun utf8Length(self) -> Int =
424
+ b0 := self.peek()
425
+ b1 := self.peekAt(1)
426
+ cont1 := b1 >= 0x80 && b1 <= 0xBF
427
+ cont2 := self.peekAt(2) >= 0x80 && self.peekAt(2) <= 0xBF
428
+ cont3 := self.peekAt(3) >= 0x80 && self.peekAt(3) <= 0xBF
429
+ if b0 >= 0xC2 && b0 <= 0xDF
430
+ if cont1 then 2 else 0
431
+ else if b0 >= 0xE0 && b0 <= 0xEF
432
+ lo := if b0 == 0xE0 then 0xA0 else 0x80
433
+ hi := if b0 == 0xED then 0x9F else 0xBF
434
+ if b1 >= lo && b1 <= hi && cont2 then 3 else 0
435
+ else if b0 >= 0xF0 && b0 <= 0xF4
436
+ lo := if b0 == 0xF0 then 0x90 else 0x80
437
+ hi := if b0 == 0xF4 then 0x8F else 0xBF
438
+ if b1 >= lo && b1 <= hi && cont2 && cont3 then 4 else 0
439
+ else
440
+ 0
392
441
 
393
442
  # Handles one escape sequence (the cursor is on the backslash), writing the
394
443
  # decoded text into `buf`.
@@ -447,11 +496,15 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
447
496
 
448
497
  # Decodes the four hex digits after `\u` (and, for a high surrogate
449
498
  # (`0xD800`..`0xDBFF`), the `\u` low surrogate (`0xDC00`..`0xDFFF`) that must
450
- # follow immediately; the pair encodes one codepoint above `0xFFFF`). Any
499
+ # follow immediately; the pair encodes one codepoint above `0xFFFF`). A surrogate
451
- # other codepoint is used as-is.
500
+ # without its partner has no UTF-8 form, so it is an error; any other codepoint is used
501
+ # as-is.
452
502
  fun parseUnicodeEscape(self, buf: Buffer) -> Result<Unit, JsonError> =
453
503
  cp := self.parseHex4()?
454
- if cp >= 0xD800 && cp <= 0xDBFF && self.peek() == 92 && self.peekAt(1) == 117
504
+ if cp >= 0xDC00 && cp <= 0xDFFF || cp >= 0xD800 && cp <= 0xDBFF && !{self.peek() == 92 && self.peekAt(1) == 117}
505
+ self.note("lone surrogate in unicode escape")
506
+ Err(self.invalid())
507
+ else if cp >= 0xD800 && cp <= 0xDBFF
455
508
  self.advance()
456
509
  self.advance()
457
510
  low := self.parseHex4()?
@@ -571,20 +624,12 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
571
624
  # ---- extensions of built-in and std types (see the rule at the top) ----------
572
625
 
573
626
  primitive Int =
574
- # A JSON number (numbers are stored as `Float`).
627
+ # A JSON number with every digit (`JsonInt`): `Int.Max` writes all 19.
575
- fun toJson(self) -> Json = JsonNum(value: Float(self))
628
+ fun toJson(self) -> Json = JsonInt(value: self)
576
-
629
+
577
- # Rejects a fraction and any magnitude of 2^53 or more (2^53+1 parses to 2^53, so the boundary is ambiguous).
630
+ # `j.asInt()`: a whole number written as one exactly; a fraction, and a Float of 2^53 or
631
+ # more in size (`1e17`, where a Float stands for several Ints), are `WrongJsonType`.
578
- fun fromJson(j: Json) -> Result<Int, JsonError> =
632
+ fun fromJson(j: Json) -> Result<Int, JsonError> = j.asInt()
579
- f := j.asFloat()?
580
- if f >= 9007199254740992.0f || f <= -9007199254740992.0f
581
- Err(WrongJsonType)
582
- else
583
- n := Int(f)
584
- if Float(n) != f
585
- Err(WrongJsonType)
586
- else
587
- Ok(n)
588
633
 
589
634
  primitive Float =
590
635
  fun toJson(self) -> Json = JsonNum(value: self)
@@ -803,11 +848,21 @@ test "api: field missing, wrong container, optField"
803
848
  test "int_fraction_rejected and int_over_2_53_rejected"
804
849
  assert jsonTestDecodeInt("3.5").unwrapOr(-1) == -1
805
850
  assert jsonTestDecodeInt("1e17").unwrapOr(-1) == -1
806
- assert jsonTestDecodeInt("9007199254740993").unwrapOr(-1) == -1
807
851
  assert jsonTestDecodeInt("[1]").unwrapOr(-1) == -1
808
852
  assert jsonTestDecodeInt("-7")! == -7
809
- assert jsonTestDecodeInt("9007199254740992").unwrapOr(-1) == -1
810
853
  assert jsonTestDecodeInt("9007199254740991")! == 9007199254740991
854
+ assert jsonTestDecodeInt("2.0")! == 2 && jsonTestDecodeInt("1e3")! == 1000
855
+ assert jsonTestDecodeInt("9007199254740992.0").unwrapOr(-1) == -1
856
+
857
+ test "an Int past 2^53 writes and reads back with every digit"
858
+ assert jsonTestDecodeInt("9007199254740993")! == 9007199254740993
859
+ assert jsonTestDecodeInt("9223372036854775807")! == Int.Max
860
+ assert jsonTestDecodeInt("-9223372036854775808")! == Int.Min
861
+ assert jsonTestDecodeInt("9223372036854775808").unwrapOr(-1) == -1
862
+ assert Json.encode(Int.Max) == "9223372036854775807" && Json.encode(Int.Min) == "-9223372036854775808"
863
+ assert Json.encode(4611686018427387905) == "4611686018427387905"
864
+ assert jsonTestDecodeInt(Json.encode(4611686018427387905))! == 4611686018427387905
865
+ assert Json.parse("9007199254740993")!.asFloat()! == 9007199254740992.0f
811
866
 
812
867
  test "nested_list_of_lists round-trips"
813
868
  v := jsonTestDecodeNested("[[1,2],[3],[]]")!
tests/std/json.plum CHANGED
@@ -13,12 +13,19 @@ fun bad(s: Str) -> Bool = Json.parse(s).isErr()
13
13
 
14
14
  fun again(s: Str) -> Str = Json.encode(Json.parse(s)!)
15
15
 
16
+ fun str(s: Str) -> Str = Json.parse(s)!.asStr()!
17
+
18
+ fun reason(s: Str) -> Str = match Json.parse(s)
19
+ Err(InvalidJson(pos, text)) => text
20
+ _ => "ok"
21
+
16
22
  test "integral numbers are written without a fraction"
17
23
  assert Json.encode(123) == "123"
18
24
  assert Json.encode(-7) == "-7"
19
25
  assert Json.encode(0) == "0"
20
26
  assert Json.encode(9007199254740991) == "9007199254740991"
21
- assert Json.encode(4611686018427387904) == "4611686018427388000"
27
+ assert Json.encode(4611686018427387904) == "4611686018427387904"
28
+ assert Json.encode(9007199254740993) == "9007199254740993"
22
29
  assert Json.encode(2.0) == "2"
23
30
  assert Json.encode([1, 2].toSlice()) == "[1,2]"
24
31
 
@@ -42,7 +49,9 @@ test "parse then encode keeps every digit"
42
49
  assert again("3.14159265358979") == "3.14159265358979"
43
50
  assert again("0.1e1") == "1"
44
51
  assert again("1E-2") == "0.01"
45
- assert again("123456789012345678") == "123456789012345680"
52
+ assert again("123456789012345678") == "123456789012345678"
53
+ assert again("12345678901234567890123") == "1.2345678901234568e+22"
54
+ assert again("1.0") == "1" && again("1e0") == "1"
46
55
  assert again("2.2250738585072014e-308") == "2.2250738585072014e-308"
47
56
  assert again("[0.5,-0,1e2]") == "[0.5,-0,100]"
48
57
 
@@ -93,3 +102,39 @@ test "Float.parse: nearest Float, exponents, signs"
93
102
  assert Float.parse("1e400")! > Float.Max
94
103
  assert Float.parse("").isErr() && Float.parse("-").isErr() && Float.parse(".").isErr()
95
104
  assert Float.parse("1x").isErr() && Float.parse("1e").isErr() && Float.parse("e5").isErr()
105
+
106
+ test "strings: every escape, surrogate pairs, and what JSON forbids"
107
+ assert str("\"\\\" \\\\ \\/ \\b \\f \\n \\r \\t\"") == "\" \\ / \b \f \n \r \t"
108
+ assert str("\"\\u00e9\\u4e16\"") == "\u00e9\u4e16"
109
+ assert str("\"\\ud83d\\ude00\"") == Str.codePointToStr(0x1F600)
110
+ assert str("\"\\uD83D\\uDE00\"").length() == 4
111
+ assert reason("\"\\ud83d\"") == "lone surrogate in unicode escape"
112
+ assert reason("\"\\ude00\"") == "lone surrogate in unicode escape"
113
+ assert reason("\"\\ud83dx\"") == "lone surrogate in unicode escape"
114
+ assert reason("\"\\ud83d\\u0041\"") == "invalid low surrogate"
115
+ assert reason("\"\\u12\"") == "invalid unicode escape" && reason("\"\\x\"") == "invalid escape character"
116
+ assert reason("\"a\nb\"") == "unescaped control character in string"
117
+ assert reason("\"a\tb\"") == "unescaped control character in string"
118
+ assert reason("\"abc") == "unterminated string"
119
+ back := "\u0001 \u001f \" \\ {Str.codePointToStr(0x1F600)} \u00e9"
120
+ assert str(Json.encode(back)) == back && Json.encode("\u0001") == "\"\\u0001\""
121
+
122
+ test "strings: well-formed UTF-8 is kept, anything else is an error"
123
+ assert str("\"h\u00e9llo \u4e16\u754c\"") == "h\u00e9llo \u4e16\u754c"
124
+ bad := |bytes: Str| reason("\"{bytes}\"") == "invalid UTF-8 in string"
125
+ assert bad(Str.byteToStr(0x80))
126
+ assert bad(Str.byteToStr(0xC3))
127
+ assert bad("{Str.byteToStr(0xC0)}{Str.byteToStr(0xAF)}")
128
+ assert bad("{Str.byteToStr(0xE0)}{Str.byteToStr(0x80)}{Str.byteToStr(0xAF)}")
129
+ assert bad("{Str.byteToStr(0xED)}{Str.byteToStr(0xA0)}{Str.byteToStr(0x80)}")
130
+ assert bad("{Str.byteToStr(0xF4)}{Str.byteToStr(0x90)}{Str.byteToStr(0x80)}{Str.byteToStr(0x80)}")
131
+ assert bad(Str.byteToStr(0xFF))
132
+ assert reason("\"{Str.byteToStr(0xE4)}{Str.byteToStr(0xB8)}") == "invalid UTF-8 in string"
133
+
134
+ test "objects: fields in key order whatever the text's order, a later duplicate wins"
135
+ assert again("{{\"b\":1,\"a\":2,\"\":3,\"aa\":4}}") == "{{\"\":3,\"a\":2,\"aa\":4,\"b\":1}}"
136
+ assert again("{{\"k\":1,\"k\":2}}") == "{{\"k\":2}}"
137
+ assert reason("{{\"a\" 1}}") == "expected ':'" && reason("{{1:2}}") == "expected string key"
138
+ assert reason("[1 2]") == "expected ',' or ']'" && reason("[1,]") == "unexpected character"
139
+ assert reason("tru") == "invalid literal, expected 'true'" && reason(" 1 x") == "unexpected trailing characters"
140
+ assert again(" \n\t[ 1 , {{ }} , [ ] ] ") == "[1,{{}},[]]"