plum

#treesitter#compiler#wasm

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

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


07ddf01 — Peter John 2026-11-10T15:26:07+05:30
std: searches return Option, Json.parse returns Result
Files changed (7) hide show
  1. docs/std.md +4 -2
  2. examples/json.plum +1 -1
  3. std/Slice.plum +18 -19
  4. std/Str.plum +27 -24
  5. std/encoding/Json.plum +72 -67
  6. std/http.plum +7 -9
  7. tests/std/json.plum +11 -11
docs/std.md CHANGED
@@ -63,7 +63,7 @@ fun main() =
63
63
  yes := name.startsWith("pl")
64
64
  ```
65
65
 
66
- - **Search:** `contains`, `startsWith`, `endsWith`, `indexOf`
66
+ - **Search:** `contains`, `startsWith`, `endsWith`, `indexOf` (the byte index of the first occurrence as an `Option[Int]`, `None` when there is none; `search` is the same)
67
67
  - **Order:** `compare(o)` and `<`, `<=`, `>`, `>=` compare byte by byte, which for UTF-8 is code point order, a prefix first (`"ab" < "b"`, `"a" < "ab"`)
68
68
  - **Cut:** `sub`, `slice`, `split(separator, limit)`, `trim`, `trimStart`, `trimEnd`, `truncate`. `trim` strips ASCII whitespace and Unicode's other White_Space characters (U+00A0, U+3000, U+2028, ...). `truncate(n)` cuts at a character boundary, never inside a multi-byte character.
69
69
  - **Change:** `replace`, `replaceAll`, `repeat`, `reverse`, `padStart`, `padEnd`
@@ -91,7 +91,7 @@ fun main() =
91
91
  second := xs.at(1) # the value, or crash when out of range
92
92
  ```
93
93
 
94
- - **Read:** `get`, `at`, `first`, `last`, `length`, `isEmpty`, `contains`, `findValue`. `at` crashes with the index and the length out of range (also on a view, and past a `pop`).
94
+ - **Read:** `get`, `at`, `first`, `last`, `length`, `isEmpty`, `contains`, `findValue`, `indexOf(v)`, `indexFrom(v, i)` and `indexWhere(pred, i)` (each an `Option[Int]`, `None` when nothing matches). `at` crashes with the index and the length out of range (also on a view, and past a `pop`).
95
95
  - **Loop:** `fold`, `each`, `map`, `filter`, `find(pred)`, `any`, `all`, as on `List`
96
96
  - **Change:** `push`, `pop`, `set`, `add`, `remove`, `removeAt`, `clear`, `reverse`, `shuffle`
97
97
  - **Other:** `sort(before)` (a new slice; a stable merge sort, O(n log n)), `slice` (a view that shares storage), `sublist` (a copy), `chunk`, `join`, `drop`, and with `std/collections/Map` imported `groupBy(key)` (a `Map` from each key to its elements, in order; the groups come in key order)
@@ -186,6 +186,8 @@ fun main() =
186
186
  p: Result[Point, JsonError] := Json.decode(text)
187
187
  ```
188
188
 
189
+ `Json.parse(text)` reads a document into a `Json` value: a `Result[Json, JsonError]`, the one way to parse (`Json.fromStr` and the `JsonParse` enum are gone). A text that isn't JSON is `Err(InvalidJson(pos, text))`, the byte position and the reason, and `e.message()` puts them in a sentence; `WrongJsonType` and `MissingField` are the decode errors.
190
+
189
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.
190
192
 
191
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`.
examples/json.plum CHANGED
@@ -53,7 +53,7 @@ test "wrong type"
53
53
  assert errorOf(house("name" => 1.toJson(), "rooms" => 1.toJson())) == "WrongJsonType"
54
54
 
55
55
  test "fractional Int is rejected"
56
- assert errorOf(house("name" => "a".toJson(), "rooms" => Json.fromStr("1.5")!)) == "WrongJsonType"
56
+ assert errorOf(house("name" => "a".toJson(), "rooms" => Json.parse("1.5")!)) == "WrongJsonType"
57
57
 
58
58
  test "invalid json"
59
59
  assert errorOf("[1,") == "InvalidJson"
std/Slice.plum CHANGED
@@ -72,21 +72,20 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
72
72
 
73
73
  # The first element for which `keep` holds, or None. Stops at the first hit.
74
74
  fun find(self, keep: fn(T) -> Bool) -> Option[T] =
75
- i := self.indexWhere(keep, 0)
76
- if i < 0 then None else Some(self.data.get(self.start + i))
75
+ self.indexWhere(keep, 0).map(|i| self.data.get(self.start + i))
77
76
 
78
- # The index of the first element at or after `i` for which `keep` holds, or -1.
77
+ # The index of the first element at or after `i` for which `keep` holds, or None.
79
- fun indexWhere(self, keep: fn(T) -> Bool, i: Int) -> Int =
78
+ fun indexWhere(self, keep: fn(T) -> Bool, i: Int) -> Option[Int] =
80
79
  if i >= self.size
81
- -1
80
+ None
82
81
  else if keep(self.data.get(self.start + i))
83
- i
82
+ Some(i)
84
83
  else
85
84
  self.indexWhere(keep, i + 1)
86
85
 
87
86
  # Whether `keep` holds for some element. Stops at the first hit.
88
87
  fun any(self, keep: fn(T) -> Bool) -> Bool =
89
- self.indexWhere(keep, 0) >= 0
88
+ self.indexWhere(keep, 0).isSome()
90
89
 
91
90
  # Whether `keep` holds for every element (true when empty). Stops at the first miss.
92
91
  fun all(self, keep: fn(T) -> Bool) -> Bool =
@@ -176,16 +175,18 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
176
175
 
177
176
  # removes the first element equal to v from list
178
177
  fun remove(self, v: T) =
179
- i := self.indexFrom(v, 0)
178
+ if Some(i) := self.indexFrom(v, 0)
180
- if i >= 0
181
179
  self.removeAt(i)
182
180
 
181
+ # The index of the first element equal to `v`, or None.
182
+ fun indexOf(self, v: T) -> Option[Int] = self.indexFrom(v, 0)
183
+
183
- # The index of the first element equal to `v` at or after index `i`, or -1.
184
+ # The index of the first element equal to `v` at or after index `i`, or None.
184
- fun indexFrom(self, v: T, i: Int) -> Int =
185
+ fun indexFrom(self, v: T, i: Int) -> Option[Int] =
185
186
  if i >= self.size
186
- -1
187
+ None
187
188
  else if self.data.get(self.start + i) == v
188
- i
189
+ Some(i)
189
190
  else
190
191
  self.indexFrom(v, i + 1)
191
192
 
@@ -224,14 +225,10 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
224
225
 
225
226
  # Returns the first element equal to `search`, or None.
226
227
  fun findValue(self, search: T) -> Option[T] =
227
- i := self.indexFrom(search, 0)
228
- if i < 0
229
- None
230
- else
231
- Some(self.data.get(self.start + i))
228
+ self.indexFrom(search, 0).map(|i| self.data.get(self.start + i))
232
229
 
233
230
  fun contains(self, v: T) -> Bool =
234
- self.indexFrom(v, 0) >= 0
231
+ self.indexFrom(v, 0).isSome()
235
232
 
236
233
  # returns the first element in the list
237
234
  fun first(self) -> Option[T] =
@@ -625,6 +622,8 @@ test "every method indexes from the view's start"
625
622
  assert v.last()! == 7
626
623
  assert v.contains(5) && !v.contains(9) && !v.contains(8)
627
624
  assert v.findValue(3)! == 3
625
+ assert v.indexOf(3)! == 2 && v.indexOf(9).isNone() && v.indexFrom(3, 3).isNone()
626
+ assert v.indexWhere(|x| x > 3, 0)! == 1 && v.indexWhere(|x| x > 100, 0).isNone()
628
627
  assert v.sort(|a, b| a < b).toStr() == "[1,3,5,7]"
629
628
  w := Slice[Int]()
630
629
  w.push(1)
std/Str.plum CHANGED
@@ -132,20 +132,22 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
132
132
  i
133
133
 
134
134
  fun contains(self, search: Str) -> Bool =
135
- self.indexOf(search) >= 0
135
+ self.indexOf(search).isSome()
136
136
 
137
+ # Byte index of the first occurrence of `sub`, or None. An empty `sub` is found at 0.
137
- fun indexOf(self, sub: Str) -> Int =
138
+ fun indexOf(self, sub: Str) -> Option[Int] =
138
139
  m := sub.length()
139
140
  if m == 0
140
- 0
141
+ Some(0)
141
142
  else
142
143
  indexFrom(self, sub, 0, self.length() - m, m)
143
144
 
145
+ # Byte index of the first occurrence of `sub` (of length `m`) from `i` up to `last`, or None.
144
- fun indexFrom(s: Str, sub: Str, i: Int, last: Int, m: Int) -> Int =
146
+ fun indexFrom(s: Str, sub: Str, i: Int, last: Int, m: Int) -> Option[Int] =
145
147
  if i > last
146
- -1
148
+ None
147
149
  else if matchesAt(s, sub, i, m)
148
- i
150
+ Some(i)
149
151
  else
150
152
  indexFrom(s, sub, i + 1, last, m)
151
153
 
@@ -245,15 +247,14 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
245
247
  # Replaces the FIRST occurrence of `old` with `new` (byte-exact). Returns
246
248
  # `self` if `old` doesn't occur.
247
249
  fun replace(self, old: Str, new: Str) -> Str =
248
- idx := self.indexOf(old)
250
+ match self.indexOf(old)
251
+ None => self
249
- if idx < 0
252
+ Some(idx) =>
250
- self
251
- else
252
- buf := Buffer()
253
+ buf := Buffer()
253
- buf.write(self.sub(0, idx))
254
+ buf.write(self.sub(0, idx))
254
- buf.write(new)
255
+ buf.write(new)
255
- buf.write(self.sub(idx + old.length(), self.length()))
256
+ buf.write(self.sub(idx + old.length(), self.length()))
256
- buf.toStr()
257
+ buf.toStr()
257
258
 
258
259
  # Replaces every non-overlapping occurrence of `old`, scanning left to
259
260
  # right. An empty `old` returns `self` unchanged.
@@ -273,8 +274,8 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
273
274
  buf.writeByte(Byte(s.byteAtUnchecked(i)))
274
275
  replaceFrom(s, old, new, i + 1, buf)
275
276
 
276
- # Byte index of the first occurrence of `sub`, or -1 (same as `indexOf`).
277
+ # Byte index of the first occurrence of `sub`, or None (same as `indexOf`).
277
- fun search(self, sub: Str) -> Int =
278
+ fun search(self, sub: Str) -> Option[Int] =
278
279
  self.indexOf(sub)
279
280
 
280
281
  # JS-`String.prototype.slice`-style: a negative `start`/`e` counts from the
@@ -767,8 +768,10 @@ test "startsWith/endsWith/contains/indexOf agree on a shared example"
767
768
  assert s.startsWith("the") == true
768
769
  assert s.endsWith("fox") == true
769
770
  assert s.contains("quick") == true
770
- assert s.indexOf("brown") == 10
771
+ assert s.indexOf("brown")! == 10
771
- assert s.indexOf("missing") == -1
772
+ assert s.indexOf("missing").isNone()
773
+ assert s.indexOf("")! == 0 && "".indexOf("")! == 0 && "".indexOf("a").isNone()
774
+ assert s.indexOf("the")! == 0 && s.indexOf("fox")! == 16 && s.indexOf("foxy").isNone()
772
775
 
773
776
  test "trim/trimStart/trimEnd strip only leading/trailing whitespace"
774
777
  assert " hi ".trim() == "hi"
@@ -864,10 +867,10 @@ test "replaceAll swaps every non-overlapping occurrence"
864
867
  assert "héhé".replaceAll("é", "e") == "hehe"
865
868
  assert "aXbXc".replaceAll("X", "--") == "a--b--c"
866
869
 
867
- test "search returns the byte index or -1, like indexOf"
870
+ test "search returns the byte index or None, like indexOf"
868
- assert "the quick fox".search("quick") == 4
871
+ assert "the quick fox".search("quick")! == 4
869
- assert "the quick fox".search("slow") == -1
872
+ assert "the quick fox".search("slow").isNone()
870
- assert "abc".search("") == 0
873
+ assert "abc".search("")! == 0
871
874
 
872
875
  test "deburr strips Latin-1 and Latin Extended-A diacritics"
873
876
  assert "café".deburr() == "cafe"
@@ -918,7 +921,7 @@ test "substrings are views: nested, compared, hashed and concatenated by content
918
921
  assert n.concat("!") == "new!"
919
922
  assert "<{w.sub(0, 5)}>" == "<brave>"
920
923
  assert w.sub(5, 2) == ""
921
- assert w.indexOf("new") == 6
924
+ assert w.indexOf("new")! == 6
922
925
  assert w.reverse() == "wen evarb"
923
926
 
924
927
  test "trim and split parts are views with correct content"
std/encoding/Json.plum CHANGED
@@ -19,15 +19,23 @@ import std/Decimal
19
19
  # name is a collision error. `Json.encode` / `Json.decode` stay duck-typed and
20
20
  # call `x.toJson()` / `T.fromJson(j)` per instantiation.
21
21
 
22
+ # Why a text could not be parsed (`InvalidJson`, with the byte position and the reason), or
22
- # Why a JSON value could not be decoded into a type.
23
+ # why a JSON value could not be decoded into a type.
23
24
  enum JsonError =
24
- | InvalidJson
25
+ | InvalidJson(pos: Int, text: Str)
25
26
  | WrongJsonType
26
27
  | MissingField
27
28
 
28
29
  fun name(self) -> Str =
29
30
  match self
30
- InvalidJson => "InvalidJson"
31
+ InvalidJson(_, _) => "InvalidJson"
32
+ WrongJsonType => "WrongJsonType"
33
+ MissingField => "MissingField"
34
+
35
+ # A sentence for a person: where and why for `InvalidJson`, the name otherwise.
36
+ fun message(self) -> Str =
37
+ match self
38
+ InvalidJson(pos, text) => "json parse error at position {pos}: {text}"
31
39
  WrongJsonType => "WrongJsonType"
32
40
  MissingField => "MissingField"
33
41
 
@@ -45,21 +53,13 @@ enum Json =
45
53
  | JsonObj(fields: Map[Str, Json])
46
54
 
47
55
  # Parses `s` as a single JSON document, requiring the whole string (aside
48
- # from surrounding whitespace) to be consumed. Called as `Json.fromStr(s)`,
56
+ # from surrounding whitespace) to be consumed. Called as `Json.parse(s)`,
49
- # matching `Int.fromStr`/`Float.fromStr`'s naming. Errors carry no data: to
57
+ # like `Int.parse`/`Float.parse`. A failure is `InvalidJson(pos, text)`: the
50
- # learn where and why a parse failed use `Json.parse(s)` instead.
58
+ # byte position and the reason.
51
- fun fromStr(s: Str) -> Result[Json, JsonError] =
59
+ fun parse(s: Str) -> Result[Json, JsonError] =
52
60
  parser := JsonParser(src: s, pos: 0, text: "", depth: 0)
53
61
  parser.parseDocument()
54
62
 
55
- # Like `fromStr`, but the outcome is an ordinary value: `Parsed` with the
56
- # document, or `Failed` with the position and message of the failure.
57
- fun parse(s: Str) -> JsonParse =
58
- parser := JsonParser(src: s, pos: 0, text: "", depth: 0)
59
- match parser.parseDocument()
60
- Ok(v) => Parsed(value: v)
61
- Err(e) => Failed(pos: parser.pos, text: parser.text)
62
-
63
63
  # Renders `self` back to its JSON text form. A literal `{`/`}` is written
64
64
  # doubled (`{{`/`}}`) — a single, un-doubled brace in a Plum string starts
65
65
  # or ends a `{expr}` interpolation instead of standing for itself.
@@ -77,7 +77,7 @@ enum Json =
77
77
 
78
78
  # `T` comes from the result annotation: `h: JsonError!House := Json.decode(s)`.
79
79
  fun decode[T](s: Str) -> Result[T, JsonError] =
80
- j := Json.fromStr(s)?
80
+ j := Json.parse(s)?
81
81
  T.fromJson(j)
82
82
 
83
83
  # Decodes an already-parsed value; `T` comes from the result type.
@@ -85,7 +85,7 @@ enum Json =
85
85
 
86
86
  # Explicit-decoder form: `Json.decodeWith(s, |j| House.fromJson(j))`.
87
87
  fun decodeWith[T](s: Str, f: fn(Json) -> Result[T, JsonError]) -> Result[T, JsonError] =
88
- j := Json.fromStr(s)?
88
+ j := Json.parse(s)?
89
89
  f(j)
90
90
 
91
91
  fun field(self, name: Str) -> Result[Json, JsonError] =
@@ -231,26 +231,24 @@ enum Json =
231
231
  # overflow (the parser recurses once per level).
232
232
  MaxJsonDepth = 1000
233
233
 
234
- # The outcome of `Json.parse`: the document, or where and why parsing failed.
235
- enum JsonParse = Parsed(value: Json) | Failed(pos: Int, text: Str)
236
-
237
234
  # A recursive-descent parser over a `Str` source, tracking its read position
238
235
  # in `pos`. It reads directly from a `Str`, the same way every other stdlib
239
236
  # parser (e.g. `Int.parse`) does.
240
237
  struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
241
238
 
242
239
  # Records why parsing is about to fail at the current position; the caller
243
- # then fails with `InvalidJson`.
240
+ # then fails with `self.invalid()`.
244
241
  fun note(self, text: Str) -> Unit =
245
242
  self.text = text
246
243
 
244
+ # The error to fail with: the current position and the reason last noted.
245
+ fun invalid(self) -> JsonError =
246
+ InvalidJson(pos: self.pos, text: self.text)
247
+
247
248
  # Notes "invalid number" and gives the error to fail with.
248
249
  fun badNumber(self) -> JsonError =
249
250
  self.note("invalid number")
250
- InvalidJson
251
+ self.invalid()
251
-
252
- fun message(self) -> Str =
253
- "json parse error at position {self.pos}: {self.text}"
254
252
 
255
253
  # The whole document: one value, then only whitespace.
256
254
  fun parseDocument(self) -> Result[Json, JsonError] =
@@ -259,7 +257,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
259
257
  self.skipSpace()
260
258
  if self.pos < self.src.length()
261
259
  self.note("unexpected trailing characters")
262
- Err(InvalidJson)
260
+ Err(self.invalid())
263
261
  else
264
262
  Ok(v)
265
263
 
@@ -301,13 +299,13 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
301
299
  self.parseNumber()
302
300
  else
303
301
  self.note("unexpected character")
304
- Err(InvalidJson)
302
+ Err(self.invalid())
305
303
 
306
304
  fun parseLiteral(self, lit: Str, value: Json) -> Result[Json, JsonError] =
307
305
  n := lit.length()
308
306
  if !Str.matchesAt(self.src, lit, self.pos, n)
309
307
  self.note("invalid literal, expected '{lit}'")
310
- Err(InvalidJson)
308
+ Err(self.invalid())
311
309
  else
312
310
  self.pos = self.pos + n
313
311
  Ok(value)
@@ -323,7 +321,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
323
321
  Err(self.badNumber())
324
322
  else if self.peek() == 48 && isDigit(self.peekAt(1))
325
323
  self.note("invalid number: leading zero")
326
- Err(InvalidJson)
324
+ Err(self.invalid())
327
325
  else
328
326
  self.skipDigits()
329
327
  self.parseFraction(start)
@@ -364,7 +362,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
364
362
  Some(f) =>
365
363
  if f > Float.Max || f < 0.0 - Float.Max
366
364
  self.note("number out of range")
367
- Err(InvalidJson)
365
+ Err(self.invalid())
368
366
  else
369
367
  Ok(JsonNum(value: f))
370
368
  None => Err(self.badNumber())
@@ -379,7 +377,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
379
377
  c := self.peek()
380
378
  if c == 0
381
379
  self.note("unterminated string")
382
- Err(InvalidJson)
380
+ Err(self.invalid())
383
381
  else if c == 34
384
382
  self.advance()
385
383
  Ok(buf.toStr())
@@ -404,7 +402,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
404
402
  text := escapeText(esc)
405
403
  if text.length() == 0
406
404
  self.note("invalid escape character")
407
- Err(InvalidJson)
405
+ Err(self.invalid())
408
406
  else
409
407
  buf.write(text)
410
408
  self.advance()
@@ -442,7 +440,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
442
440
  d := hexDigitValue(self.peek())
443
441
  if d < 0
444
442
  self.note("invalid unicode escape")
445
- Err(InvalidJson)
443
+ Err(self.invalid())
446
444
  else
447
445
  self.advance()
448
446
  self.parseHexDigits(count + 1, value * 16 + d)
@@ -459,7 +457,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
459
457
  low := self.parseHex4()?
460
458
  if low < 0xDC00 || low > 0xDFFF
461
459
  self.note("invalid low surrogate")
462
- Err(InvalidJson)
460
+ Err(self.invalid())
463
461
  else
464
462
  combined := 0x10000 + {{cp - 0xD800} << 10} + {low - 0xDC00}
465
463
  buf.writeRune(combined)
@@ -479,7 +477,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
479
477
 
480
478
  fun parseArray(self) -> Result[Json, JsonError] =
481
479
  if !self.deeper()
482
- Err(InvalidJson)
480
+ Err(self.invalid())
483
481
  else
484
482
  self.advance()
485
483
  self.skipSpace()
@@ -504,14 +502,14 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
504
502
  Ok(JsonArr(items: items))
505
503
  else if c != 44
506
504
  self.note("expected ',' or ']'")
507
- Err(InvalidJson)
505
+ Err(self.invalid())
508
506
  else
509
507
  self.advance()
510
508
  self.parseArrayItems(items)
511
509
 
512
510
  fun parseObject(self) -> Result[Json, JsonError] =
513
511
  if !self.deeper()
514
- Err(InvalidJson)
512
+ Err(self.invalid())
515
513
  else
516
514
  self.advance()
517
515
  self.skipSpace()
@@ -529,13 +527,13 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
529
527
  self.skipSpace()
530
528
  if self.peek() != 34
531
529
  self.note("expected string key")
532
- Err(InvalidJson)
530
+ Err(self.invalid())
533
531
  else
534
532
  key := self.parseString()?
535
533
  self.skipSpace()
536
534
  if self.peek() != 58
537
535
  self.note("expected ':'")
538
- Err(InvalidJson)
536
+ Err(self.invalid())
539
537
  else
540
538
  self.advance()
541
539
  self.skipSpace()
@@ -549,7 +547,7 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str, mut depth: Int) =
549
547
  Ok(JsonObj(fields: more))
550
548
  else if c != 44
551
549
  self.note("expected ',' or '}}'")
552
- Err(InvalidJson)
550
+ Err(self.invalid())
553
551
  else
554
552
  self.advance()
555
553
  self.parsePairs(more)
@@ -675,24 +673,24 @@ fun jsonTestHouseError(s: Str) -> Str =
675
673
  fun jsonTestDecodeHouse(s: Str) -> Result[JsonTestHouse, JsonError] = Json.decode(s)
676
674
 
677
675
  test "parses null, true, and false"
678
- assert Json.fromStr("null")!.isNull()
676
+ assert Json.parse("null")!.isNull()
679
- assert Json.fromStr("true")!.asBool()!
677
+ assert Json.parse("true")!.asBool()!
680
- assert !Json.fromStr("false")!.asBool()!
678
+ assert !Json.parse("false")!.asBool()!
681
679
 
682
680
  test "parses integers, decimals, negatives, and exponents"
683
- assert Json.fromStr("42")!.asFloat()! == 42.0f
681
+ assert Json.parse("42")!.asFloat()! == 42.0f
684
- assert Json.fromStr("-7")!.asFloat()! == -7.0f
682
+ assert Json.parse("-7")!.asFloat()! == -7.0f
685
- assert Json.fromStr("3.5")!.asFloat()! == 3.5f
683
+ assert Json.parse("3.5")!.asFloat()! == 3.5f
686
- assert Json.fromStr("1e2")!.asFloat()! == 100.0f
684
+ assert Json.parse("1e2")!.asFloat()! == 100.0f
687
- assert Json.fromStr("1.5e-2")!.asFloat()! == 0.015f
685
+ assert Json.parse("1.5e-2")!.asFloat()! == 0.015f
688
686
 
689
687
  test "parses a plain string, with escapes"
690
- assert Json.fromStr("\"hello\"")!.asStr()! == "hello"
688
+ assert Json.parse("\"hello\"")!.asStr()! == "hello"
691
- assert Json.fromStr("\"a\\nb\"")!.asStr()! == "a\nb"
689
+ assert Json.parse("\"a\\nb\"")!.asStr()! == "a\nb"
692
- assert Json.fromStr("\"\\u0041\"")!.asStr()! == "A"
690
+ assert Json.parse("\"\\u0041\"")!.asStr()! == "A"
693
691
 
694
692
  test "parses an array of mixed values"
695
- v := Json.fromStr("[1, \"two\", true, null]")!
693
+ v := Json.parse("[1, \"two\", true, null]")!
696
694
  items := v.asList()!
697
695
  assert items.length() == 4
698
696
  assert items.get(0)!.asFloat()! == 1.0f
@@ -701,7 +699,7 @@ test "parses an array of mixed values"
701
699
  assert items.get(3)!.isNull()
702
700
 
703
701
  test "parses a nested object"
704
- v := Json.fromStr("{{\"a\": 1, \"b\": {{\"c\": [1, 2, 3]}}}}")!
702
+ v := Json.parse("{{\"a\": 1, \"b\": {{\"c\": [1, 2, 3]}}}}")!
705
703
  pairs := v.asMap()!
706
704
  assert pairs.get("a")!.asFloat()! == 1.0f
707
705
  nested := pairs.get("b")!.asMap()!
@@ -710,27 +708,34 @@ test "parses a nested object"
710
708
  assert inner.get(2)!.asFloat()! == 3.0f
711
709
 
712
710
  test "reports an error on malformed input"
713
- bad := Json.fromStr("{{\"a\": }}").unwrapOr(JsonNull)
711
+ bad := Json.parse("{{\"a\": }}").unwrapOr(JsonNull)
714
712
  assert bad.isNull()
715
- assert Json.fromStr("[1,").unwrapOr(JsonNull).isNull()
713
+ assert Json.parse("[1,").unwrapOr(JsonNull).isNull()
716
714
 
717
715
  test "parse reports where and why a document is invalid"
718
716
  match Json.parse("[1, x]")
719
- Parsed(v) =>
717
+ Ok(v) =>
720
718
  assert false
719
+ Err(e) =>
720
+ assert e.message() == "json parse error at position 4: unexpected character"
721
+ assert e.name() == "InvalidJson"
722
+ match e
721
- Failed(pos, text) =>
723
+ InvalidJson(pos, text) =>
722
- assert pos == 4
724
+ assert pos == 4
723
- assert text == "unexpected character"
725
+ assert text == "unexpected character"
726
+ _ =>
727
+ assert false
724
728
  match Json.parse("[1]")
725
- Parsed(v) =>
729
+ Ok(v) =>
726
730
  assert v.asList()!.length() == 1
727
- Failed(pos, text) =>
731
+ Err(e) =>
728
732
  assert false
733
+ assert Json.parse("[1]")!.asList()!.length() == 1
729
734
 
730
735
  test "round-trips a value through toStr and back"
731
736
  original := "[1,\"two\",true,null,{{\"k\":3.5}}]"
732
- v := Json.fromStr(original)!
737
+ v := Json.parse(original)!
733
- again := Json.fromStr(v.toStr())!
738
+ again := Json.parse(v.toStr())!
734
739
  assert again.toStr() == v.toStr()
735
740
 
736
741
  test "toStr escapes special characters in strings"
@@ -742,7 +747,7 @@ test "round-trips a 100000 character string"
742
747
  for i := range 100000
743
748
  buf.write("a")
744
749
  doc := "\"{buf.toStr()}\""
745
- v := Json.fromStr(doc)!
750
+ v := Json.parse(doc)!
746
751
  assert v.asStr()!.length() == 100000
747
752
  assert v.toStr().length() == 100002
748
753
 
@@ -752,7 +757,7 @@ test "parses a 10000 element array"
752
757
  for i := range 1.until(10000)
753
758
  buf.write(",{i}")
754
759
  buf.write("]")
755
- items := Json.fromStr(buf.toStr())!.asList()!
760
+ items := Json.parse(buf.toStr())!.asList()!
756
761
  assert items.length() == 10000
757
762
  assert items.get(9999)!.asFloat()! == 9999.0f
758
763
 
@@ -762,7 +767,7 @@ test "parses an object with 2000 keys"
762
767
  for i := range 1.until(2000)
763
768
  buf.write(",\"k{i}\":{i}")
764
769
  buf.write("}}")
765
- pairs := Json.fromStr(buf.toStr())!.asMap()!
770
+ pairs := Json.parse(buf.toStr())!.asMap()!
766
771
  assert pairs.get("k1999")!.asFloat()! == 1999.0f
767
772
  assert pairs.get("k0")!.asFloat()! == 0.0f
768
773
 
@@ -785,7 +790,7 @@ test "extension: nested Slice.toJson recurses through T.toJson"
785
790
  assert [[1].toSlice(), [2, 3].toSlice()].toSlice().toJson().toStr() == "[[1],[2,3]]"
786
791
 
787
792
  test "api: field missing, wrong container, optField"
788
- o := Json.fromStr("{{\"a\":1}}")!
793
+ o := Json.parse("{{\"a\":1}}")!
789
794
  l0 := Json.array([])
790
795
  assert o.field("a")!.asFloat()! == 1.0f
791
796
  assert o.field("x").unwrapOr(JsonNull).isNull()
std/http.plum CHANGED
@@ -33,10 +33,10 @@ struct Response(status: Int, headers: Map[Str, Str], body: Str) =
33
33
  fun ok(self) -> Bool =
34
34
  self.status >= 200 && self.status < 300
35
35
 
36
- # Parses `body` as JSON. Fails the same way `Json.fromStr` does for a
36
+ # Parses `body` as JSON. Fails the same way `Json.parse` does for a
37
37
  # response body that isn't valid JSON.
38
38
  fun json(self) -> Result[Json, JsonError] =
39
- Json.fromStr(self.body)
39
+ Json.parse(self.body)
40
40
 
41
41
  # A single blocking network round trip — this VM has no async/event-loop
42
42
  # mechanism, so `rawHttpRequest` runs to completion before returning (same
@@ -72,11 +72,9 @@ fun decodeHeaders(raw: Str) -> Map[Str, Str] =
72
72
  emptyHeaders()
73
73
  else
74
74
  raw.split("\n", 0).fold(emptyHeaders(), |result, line|
75
- idx := line.indexOf(": ")
75
+ match line.indexOf(": ")
76
- if idx >= 0
77
- result.with(line.sub(0, idx), line.sub(idx + 2, line.length()))
76
+ Some(idx) => result.with(line.sub(0, idx), line.sub(idx + 2, line.length()))
78
- else
79
- result
77
+ None => result
80
78
  )
81
79
 
82
80
  # Performs a single HTTP request and waits for the full response. Fails
@@ -88,8 +86,8 @@ fun decodeHeaders(raw: Str) -> Map[Str, Str] =
88
86
  fun request(io: Io, method: Str, url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, HttpError] =
89
87
  raw := io.rawHttpRequest(method, url, encodeHeaders(headers), body)
90
88
  sep := raw.indexOf("\x00")
91
- meta := if sep >= 0 then raw.sub(0, sep) else raw
89
+ meta := sep.map(|i| raw.sub(0, i)).unwrapOr(raw)
92
- resp_body := if sep >= 0 then raw.sub(sep + 1, raw.length()) else ""
90
+ resp_body := sep.map(|i| raw.sub(i + 1, raw.length())).unwrapOr("")
93
91
  parts := meta.split("\x01", 3)
94
92
  flag := parts.get(0).unwrapOr("")
95
93
  if flag != "1"
tests/std/json.plum CHANGED
@@ -7,11 +7,11 @@ import std/Slice
7
7
  import std/collections/Map
8
8
  import std/encoding/Json
9
9
 
10
- fun num(s: Str) -> Float = Json.fromStr(s)!.asFloat()!
10
+ fun num(s: Str) -> Float = Json.parse(s)!.asFloat()!
11
11
 
12
- fun bad(s: Str) -> Bool = Json.fromStr(s).isErr()
12
+ fun bad(s: Str) -> Bool = Json.parse(s).isErr()
13
13
 
14
- fun again(s: Str) -> Str = Json.encode(Json.fromStr(s)!)
14
+ fun again(s: Str) -> Str = Json.encode(Json.parse(s)!)
15
15
 
16
16
  test "integral numbers are written without a fraction"
17
17
  assert Json.encode(123) == "123"
@@ -63,24 +63,24 @@ test "invalid numbers are errors: leading zeros, a bare sign or point, out of ra
63
63
  assert bad("-") && bad("1.") && bad(".5") && bad("1e") && bad("1e+") && bad("+1")
64
64
  assert bad("1e400") && bad("-1e400")
65
65
  match Json.parse("1e400")
66
- Parsed(v) =>
67
- assert false
68
- Failed(pos, text) =>
66
+ Err(InvalidJson(pos, text)) =>
69
67
  assert text == "number out of range"
68
+ _ =>
69
+ assert false
70
70
 
71
71
  test "nesting past MaxJsonDepth is an error, not a stack overflow"
72
72
  ok := "{"[".repeat(1000)}{"]".repeat(1000)}"
73
- assert Json.fromStr(ok).isOk()
73
+ assert Json.parse(ok).isOk()
74
74
  assert bad("{"[".repeat(1001)}{"]".repeat(1001)}")
75
75
  assert bad("{"[".repeat(200000)}{"]".repeat(200000)}")
76
76
  assert bad("{"{{\"a\":".repeat(1001)}1{"}}".repeat(1001)}")
77
77
  wide := "[{"[],".repeat(5000)}[]]"
78
- assert Json.fromStr(wide)!.asList()!.length() == 5001
78
+ assert Json.parse(wide)!.asList()!.length() == 5001
79
79
  match Json.parse("[".repeat(2000))
80
- Parsed(v) =>
81
- assert false
82
- Failed(pos, text) =>
80
+ Err(InvalidJson(pos, text)) =>
83
81
  assert pos == 1000 && text.startsWith("nested too deeply")
82
+ _ =>
83
+ assert false
84
84
 
85
85
  test "Float.parse: nearest Float, exponents, signs"
86
86
  assert Float.parse("0.3")! == 0.3