plum

#treesitter#compiler#wasm

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

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


b2baefb — Peter John 2026-11-06T21:47:41+05:30
Simpler language: std off return, while and local reassignment
AGENTS.md CHANGED
@@ -6,7 +6,7 @@ Do not use git worktrees or feature branches. Work directly on `master` in the m
6
6
 
7
7
  ## Before every commit
8
8
 
9
- Run every test executable, not just the Plum sweep, even when only `.plum` files changed. List them with `cargo test --no-run --workspace 2>&1 | grep Executable` (`cargo test` itself is blocked in superlite runs), then run `target/debug/plum test std examples tests`. A change to `std` can break Rust tests that the sweep never runs.
9
+ Run `compiler/scripts/test-all.sh`. It builds, runs every test executable (not just the Plum sweep, even when only `.plum` files changed), then runs `target/debug/plum test std examples tests` with the default, `--no-fbip` and `--no-fusion`, and ends with `ALL PASSED` or `FAILED: <n>`. A change to `std` can break Rust tests that the sweep never runs.
10
10
 
11
11
  ## Subagents
12
12
 
compiler/core/src/closure_spec.rs CHANGED
@@ -1,6 +1,8 @@
1
1
  //! Closure specialisation. A call that passes a closure literal (or a free fn name)
2
2
  //! directly to a fn-typed parameter that does not escape (see `closure_escape`) gets a
3
- //! copy of the callee, named `name$c0`, `name$c1`, ..., in which every call of that
3
+ //! copy of the callee, named `name$c0`, `name$c1`, ... (numbered per bare name, so copies of
4
+ //! same-named methods of two types never share a name: `purity` and `drive` resolve a method
5
+ //! of unknown receiver type by name), in which every call of that
4
6
  //! parameter is replaced by the closure body (params bound to the call's arguments,
5
7
  //! binders renamed fresh). Variables the closure captures become extra trailing params of
6
8
  //! the copy (generic, named `__cap<spec>_<i>`) that the call site passes after the
@@ -63,6 +65,7 @@ pub fn specialiseWith(src: &mut Source, hints: &Hints) -> Vec<String> {
63
65
  specs: Vec::new(),
64
66
  copies: HashMap::new(),
65
67
  perCallee: HashMap::new(),
68
+ perName: HashMap::new(),
66
69
  out: Vec::new(),
67
70
  outKeys: Vec::new(),
68
71
  fresh: 0,
@@ -161,6 +164,8 @@ struct Ctx<'h> {
161
164
  /// (callee key, param index, spec) -> copy fn name; `None` when it cannot be made.
162
165
  copies: HashMap<(String, usize, usize), Option<String>>,
163
166
  perCallee: HashMap<String, usize>,
167
+ /// copies made per bare fn name, across all types: numbers the copy names
168
+ perName: HashMap<String, usize>,
164
169
  out: Vec<Option<Fn>>,
165
170
  outKeys: Vec<String>,
166
171
  fresh: usize,
@@ -404,12 +409,14 @@ impl<'h> Ctx<'h> {
404
409
  self.copies.insert(ck, None);
405
410
  return None;
406
411
  }
412
+ let number = *self.perName.get(&orig.name).unwrap_or(&0);
407
- let name = format!("{}$c{}", orig.name, n);
413
+ let name = format!("{}$c{}", orig.name, number);
408
414
  let newKey = match &orig.type_param {
409
415
  Some(t) => format!("{}.{}", t, name),
410
416
  None => name.clone(),
411
417
  };
412
418
  self.perCallee.insert(key.to_string(), n + 1);
419
+ self.perName.insert(orig.name.clone(), number + 1);
413
420
  self.copies.insert(ck.clone(), Some(name.clone()));
414
421
  let idx = self.out.len();
415
422
  self.out.push(None);
@@ -417,6 +424,7 @@ impl<'h> Ctx<'h> {
417
424
  // Everything made from here on belongs to this copy until it succeeds.
418
425
  let copiesBefore: HashSet<(String, usize, usize)> = self.copies.keys().cloned().collect();
419
426
  let perBefore = self.perCallee.clone();
427
+ let namesBefore = self.perName.clone();
420
428
  match self.buildCopy(orig, name.clone(), j, sid) {
421
429
  Some(f) => {
422
430
  if f.type_param.is_some() && f.has_self {
@@ -450,6 +458,7 @@ impl<'h> Ctx<'h> {
450
458
  }
451
459
  self.perCallee = perBefore;
452
460
  self.perCallee.insert(key.to_string(), n);
461
+ self.perName = namesBefore;
453
462
  self.copies.insert(ck, None);
454
463
  None
455
464
  }
compiler/core/tests/core/closure_spec_test.rs CHANGED
@@ -59,6 +59,23 @@ fn copies(name: &str, src: &str) -> Vec<String> {
59
59
  .collect()
60
60
  }
61
61
 
62
+ /// The copies the program itself causes: `copies` minus the ones std makes for its own
63
+ /// closure arguments (e.g. `Slice.shuffle`'s `downTo(1).fold(..)`), found by lowering the
64
+ /// same imports with an empty `main`.
65
+ fn userCopies(name: &str, src: &str) -> Vec<String> {
66
+ let mut std = copies("stdbase", &withHead("fun main() -> Int = 0\n"));
67
+ let mut mine = Vec::new();
68
+ for n in copies(name, src) {
69
+ match std.iter().position(|s| *s == n) {
70
+ Some(i) => {
71
+ std.remove(i);
72
+ }
73
+ None => mine.push(n),
74
+ }
75
+ }
76
+ mine
77
+ }
78
+
62
79
  /// Number of closure calls (`call_ref` / `call_indirect`) in the module.
63
80
  fn callRefs(bytes: &[u8]) -> usize {
64
81
  let mut n = 0;
@@ -206,12 +223,26 @@ fn fn_name_argument() {
206
223
  assert_eq!(runIntBytes(&bytes), 12);
207
224
  }
208
225
 
226
+ /// Purity and fusion resolve a method of unknown receiver type by bare name, so a copy of
227
+ /// `A.twice` must not share its name with one of `B.twice`: an impure copy would taint the other.
228
+ #[test]
229
+ fn copies_of_same_named_methods_have_different_names() {
230
+ let src = withHead(
231
+ "struct A(n: Int) =\n fun twice(self, f: fn(Int) -> Int) -> Int = f(f(self.n))\n\nstruct B(n: Int) =\n fun twice(self, f: fn(Int) -> Int) -> Int = f(f(self.n))\n\nfun main() -> Int = A(n: 1).twice(|x| x + 1) + B(n: 2).twice(|x| x + 2)\n",
232
+ );
233
+ let names = userCopies("same_method", &src);
234
+ assert_eq!(names.len(), 2, "{names:?}");
235
+ let bare = |k: &str| k.split('.').last().unwrap().to_string();
236
+ assert_ne!(bare(&names[0]), bare(&names[1]), "{names:?}");
237
+ assert_eq!(runInt("same_method", &src), 9);
238
+ }
239
+
209
240
  #[test]
210
241
  fn escaping_closure_untouched() {
211
242
  let src = withHead(
212
243
  "struct Box(cb: fn(Int) -> Int)\n\nfun keep(f: fn(Int) -> Int) -> Box = Box(cb: f)\n\nfun main() -> Int =\n b := keep(|x| x + 1)\n g := b.cb\n return g(41)\n",
213
244
  );
214
- assert!(copies("escaping", &src).is_empty());
245
+ assert!(userCopies("escaping", &src).is_empty());
215
246
  assert_eq!(runInt("escaping", &src), 42);
216
247
  }
217
248
 
@@ -348,7 +379,7 @@ fn deep_recursive_closure_callee() {
348
379
  let plain = withHead(
349
380
  "fun loop(n: Int, acc: Int, f: fn(Int) -> Int) -> Int =\n if n == 0 then acc else loop(n - 1, f(acc), f)\n\nfun mid(n: Int, f: fn(Int) -> Int) -> Int = loop(n, f(0), f)\n\nfun outer(n: Int, g: fn(Int) -> Int) -> Int = mid(n, g)\n\nfun main() -> Int =\n k := 2\n a := |x| x + 1\n b := |x| x + k\n return outer(100000, a) + outer(50000, b)\n",
350
381
  );
351
- assert!(copies("deep_plain", &plain).is_empty());
382
+ assert!(userCopies("deep_plain", &plain).is_empty());
352
383
  let r = runIntBytes(&bytes);
353
384
  assert_eq!(r, runInt("deep_plain", &plain));
354
385
  assert_eq!(r, 100001 + 100002);
@@ -383,8 +414,8 @@ fn capture_read_after_mutation() {
383
414
  let plain = withHead(
384
415
  "fun main() -> Int =\n xs := [1, 2, 3]\n k := 1\n k = 10\n m := |x| x + k\n s := |a, x| a + x\n a := xs.map(m).fold(0, s)\n k = 100\n m2 := |x| x + k\n b := xs.map(m2).fold(0, s)\n return a * 1000 + b\n",
385
416
  );
386
- assert!(!copies("capmut", &spec).is_empty());
417
+ assert!(!userCopies("capmut", &spec).is_empty());
387
- assert!(copies("capmut_plain", &plain).is_empty());
418
+ assert!(userCopies("capmut_plain", &plain).is_empty());
388
419
  let r = runInt("capmut", &spec);
389
420
  assert_eq!(r, runInt("capmut_plain", &plain));
390
421
  assert_eq!(r, 36 * 1000 + 306);
compiler/scripts/test-all.sh ADDED
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env bash
2
+ # Runs every test: all Rust test executables, then the Plum sweep in three modes.
3
+ cd "$(dirname "$0")/../.." || exit 1
4
+ fail=0
5
+ failed_names=""
6
+
7
+ if ! cargo build --workspace --tests; then
8
+ echo "FAIL build"
9
+ echo "FAILED: 1"
10
+ exit 1
11
+ fi
12
+
13
+ exes=$(cargo test --no-run --workspace 2>&1 | grep Executable | sed -E 's/.*\(([^)]*)\).*/\1/')
14
+ if [ -z "$exes" ]; then
15
+ echo "FAIL no test executables found"
16
+ echo "FAILED: 1"
17
+ exit 1
18
+ fi
19
+
20
+ for exe in $exes; do
21
+ out=$("$exe" 2>&1)
22
+ if [ $? -eq 0 ]; then
23
+ echo "ok $exe"
24
+ else
25
+ echo "FAIL $exe"
26
+ fail=$((fail + 1))
27
+ failed_names="$failed_names
28
+ $(echo "$out" | grep -E '^test .* FAILED$')"
29
+ fi
30
+ done
31
+
32
+ for flag in "" --no-fbip --no-fusion; do
33
+ # shellcheck disable=SC2086
34
+ out=$(target/debug/plum test $flag std examples tests 2>&1)
35
+ if [ $? -eq 0 ]; then
36
+ echo "ok sweep ${flag:-default}"
37
+ else
38
+ echo "FAIL sweep ${flag:-default}"
39
+ fail=$((fail + 1))
40
+ failed_names="$failed_names
41
+ $(echo "$out" | grep -iE 'fail' | head -20)"
42
+ fi
43
+ done
44
+
45
+ [ -n "$(echo "$failed_names" | tr -d '[:space:]')" ] && echo "Failing tests:$failed_names"
46
+ if [ "$fail" -eq 0 ]; then echo "ALL PASSED"; else echo "FAILED: $fail"; exit 1; fi
docs/backlog.md CHANGED
@@ -27,7 +27,8 @@ Open work, in the order the user queued it, plus smaller items found during buil
27
27
 
28
28
  ## Planned, not yet placed in the queue
29
29
 
30
- - **Testing improvements** (user 2026-11-06, "All 3 please"):
30
+ - **Testing improvements** (user 2026-11-06, "All 3 please", and "Yes please add group"):
31
+ - **`group "name"` blocks:** a naming and scope block with one level of nesting. It can hold helper functions and constants visible only inside it, stripped from normal builds. No `setUp` or `tearDown`, and no test classes. After T10 of the simpler language run.
31
32
  - **One test command:** runs every Rust test executable plus the sweep. Comes right after the current fix in the simpler language run.
32
33
  - **Compare-mode tests:** one test flag that runs a test with and without fusion and FBIP. After T10 of the simpler language run.
33
34
  - **Property tests in `std`:** `check(|a, b| a + b == b + a)` with generated inputs. After T10 of the simpler language run.
docs/decisions/2026-11-simpler-language-notes.md CHANGED
@@ -48,6 +48,22 @@ This is what makes the compiler simpler. An optimiser can walk each branch on it
48
48
 
49
49
  **It isn't perfectly a tree.** Blocks still run in order, as in `gfx.clear(io, ..)` then `self.ship.draw(io)`, though a straight line is just as easy to walk. `mut` fields can still be assigned, so `Slice` and similar types need more care.
50
50
 
51
+ ## `for` and `while` are side-effect sugar
52
+
53
+ Both stay, but only for doing something, not for computing a value:
54
+
55
+ ```plum
56
+ for o := range orbs
57
+ gfx.circle(io, o.x, o.y, 10.0, Color.Yellow)
58
+
59
+ while !queue.isEmpty()
60
+ handle(io, queue.pop())
61
+ ```
62
+
63
+ The compiler rewrites each into a function call before any other pass, so the tree shape holds. Neither can exit early or reassign a local, so a `while` body has to change something through a `mut` field or `io`. A value comes from `fold`, `find`, `repeatUntil` or a recursive function.
64
+
65
+ A form that carries state, `r := while s := Start(..), s.i < n`, was considered and left out for now.
66
+
51
67
  ## `?` with no `return`
52
68
 
53
69
  The compiler rewrites the rest of the block into a `match` arm:
docs/plans/2026-11-06-simpler-language.md CHANGED
@@ -156,7 +156,7 @@ e.g. `grep -rE '\breturn\b|^\s*while ' std` finds nothing in code
156
156
  **Consumes:** std uses no `return`, `while`, `break`, `continue` or local `=`; std provides `fold`, `each`, `find`, `repeatUntil` over `range` and collections (T8)
157
157
  **Produces:** no Plum source in examples, tests or Rust test strings uses the old forms, apart from tests of those forms themselves
158
158
  e.g. `examples/control_flow.plum` teaches `if`, `match`, `for`, `fold` and recursion
159
- **Notes:** Rust tests of `return`/`while` semantics that exist only for those forms are deleted in T10, not here. `tests/fbip` keeps checking the same aliasing cases in the new forms: never drop one. Kids' games use `for` and state structs and stay readable.
159
+ **Notes:** Rust tests of `return`/`while` semantics that exist only for those forms are deleted in T10, not here. `tests/fbip` keeps checking the same aliasing cases in the new forms: never drop one. A `while cond` over `mut` state or `io`, with no local `=`, `break` or `continue` in it, may stay. Kids' games use `for` and state structs and stay readable.
160
160
  **Test code:** ported tests.
161
161
 
162
162
  ### T10 remove the old forms · Complexity 8 · Est. context 120k
@@ -165,10 +165,10 @@ e.g. `examples/control_flow.plum` teaches `if`, `match`, `for`, `fold` and recur
165
165
  **LOC owned:** 2000
166
166
  **Tests:** fast
167
167
  **Consumes:** no Plum source in examples, tests or Rust test strings uses the old forms, apart from tests of those forms themselves (T9)
168
- **Produces:** `return`, `while`, `break`, `continue` and `x = v` on a local are parse or type errors; `for` lowers to `each`; `Array.with`, `withUnique` and the pilot `Vec` are gone
168
+ **Produces:** `return`, `break`, `continue` and `x = v` on a local are parse or type errors; `for` and `while cond` are side-effect sugar lowered to function calls; `Array.with`, `withUnique` and the pilot `Vec` are gone
169
169
  e.g. `x = 1` on a local reports "locals can't be reassigned; use a new name with :="
170
- **Notes:** Delete the AST nodes, checker and codegen arms, and the pass branches, and simplify the passes they complicated: this is the payoff. A `for` body that assigns an outer local is an error. A pass may keep a private loop node only if TRMC truly needs it, not parseable; say so if it does. Keep `fip fun`, `--no-fbip`, the fuzzer. Update the fuzzer's generator to the new forms. Report lines removed.
171
- **Test code:** an error test for each removed form; `for` over a range, a list and a `Slice`.
170
+ **Notes:** Delete the AST nodes, checker and codegen arms, and the pass branches, and simplify the passes they complicated: this is the payoff. A `for` or `while` body that assigns an outer local is an error. `while cond` (user 2026-11-06) stays as sugar for a side-effect loop: the body changes things through a `mut` field or `io`, the condition is re-evaluated each pass, and it lowers before all passes to a tail-recursive function or a std helper, so no `While` AST node survives. It has no state form, no value and no early exit. A pass may keep a private loop node only if TRMC truly needs it, not parseable; say so if it does. Keep `fip fun`, `--no-fbip`, the fuzzer. Update the fuzzer's generator to the new forms. Report lines removed.
171
+ **Test code:** an error test for each removed form; `for` over a range, a list and a `Slice`; `while` draining a `mut` queue for 1,000,000 passes without overflowing, and a `while` whose condition is false at the start.
172
172
 
173
173
  ## Package D: the proof, for structs and enums
174
174
 
docs/plans/2026-11-06-simpler-language.review.md CHANGED
@@ -53,7 +53,8 @@ A game is any type with `update` and `draw`, found by duck typing, as with Ebite
53
53
  | Imports | Types and enum variants unqualified; functions and constants use the module name |
54
54
  | `return` | Removed. Block `if` is an expression |
55
55
  | `?` | Stays. The compiler rewrites the rest of the block into a `match` arm |
56
- | `while`, `break`, `continue` | Removed. Use `fold`, `find`, `repeatUntil` or a recursive function |
56
+ | `break`, `continue` | Removed. Use `fold`, `find`, `repeatUntil` or a recursive function |
57
+ | `while` | Stays as side-effect sugar only (user 2026-11-06): `while !queue.isEmpty()`. The body changes things through a `mut` field or `io`. No state form, no reassigning locals, and no early exit |
57
58
  | `for` | Stays as side-effect sugar for `each`: no early exit, no updating outer variables |
58
59
  | `=` on locals | Removed. `:=` is the only form. `=` stays only for `mut` fields |
59
60
  | `mut` | Stays for now, for `Array`, `Slice` and other in-place shells |
std/Deque.plum CHANGED
@@ -15,26 +15,23 @@ struct Deque[T](mut buf: Array[T], mut head: Int, mut size: Int) =
15
15
 
16
16
  fun init() -> Deque[T] =
17
17
  b := Array[T]().resize(8)
18
- return Deque(buf: b, head: 0, size: 0)
18
+ Deque(buf: b, head: 0, size: 0)
19
19
 
20
20
  fun length(self) -> Int =
21
- return self.size
21
+ self.size
22
22
 
23
23
  fun isEmpty(self) -> Bool =
24
- return self.size == 0
24
+ self.size == 0
25
25
 
26
26
  # Doubles capacity when full, relinearizing the ring so `head` becomes 0.
27
27
  fun grow(self) -> Unit =
28
- if self.size < self.buf.length()
28
+ if self.size >= self.buf.length()
29
- return
30
- cap := self.buf.length()
29
+ cap := self.buf.length()
31
- nb := Array[T]().resize(cap * 2)
30
+ nb := Array[T]().resize(cap * 2)
32
- i := 0
33
- while i < self.size
31
+ for i := range self.size
34
- nb.set(i, self.buf.get({self.head + i} % cap))
32
+ nb.set(i, self.buf.get({self.head + i} % cap))
35
- i = i + 1
36
- self.buf = nb
33
+ self.buf = nb
37
- self.head = 0
34
+ self.head = 0
38
35
 
39
36
  fun pushBack(self, v: T) -> Unit =
40
37
  self.grow()
@@ -51,24 +48,27 @@ struct Deque[T](mut buf: Array[T], mut head: Int, mut size: Int) =
51
48
  # Removes and returns the front element, or None if empty.
52
49
  fun popFront(self) -> Option[T] =
53
50
  if self.size == 0
54
- return None
51
+ None
52
+ else
55
- v := self.buf.get(self.head)
53
+ v := self.buf.get(self.head)
56
- self.head = {self.head + 1} % self.buf.length()
54
+ self.head = {self.head + 1} % self.buf.length()
57
- self.size = self.size - 1
55
+ self.size = self.size - 1
58
- Some(v)
56
+ Some(v)
59
57
 
60
58
  # Removes and returns the back element, or None if empty.
61
59
  fun popBack(self) -> Option[T] =
62
60
  if self.size == 0
63
- return None
61
+ None
62
+ else
64
- self.size = self.size - 1
63
+ self.size = self.size - 1
65
- Some(self.buf.get({self.head + self.size} % self.buf.length()))
64
+ Some(self.buf.get({self.head + self.size} % self.buf.length()))
66
65
 
67
66
  # The `i`'th element from the front, or None if out of bounds.
68
67
  fun get(self, i: Int) -> Option[T] =
69
68
  if i < 0 || i >= self.size
70
- return None
69
+ None
70
+ else
71
- Some(self.buf.get({self.head + i} % self.buf.length()))
71
+ Some(self.buf.get({self.head + i} % self.buf.length()))
72
72
 
73
73
  # the `i`'th element from the front, unchecked (the `for x := range deque` protocol)
74
74
  fun at(self, i: Int) -> T =
@@ -81,23 +81,19 @@ struct Deque[T](mut buf: Array[T], mut head: Int, mut size: Int) =
81
81
  test "deque_wraparound: head wraps past the end of the ring and growth unwraps it"
82
82
  d := Deque[Int]()
83
83
  # keep size small so head keeps advancing around the 8-slot ring
84
- i := 0
85
- while i < 50
84
+ for i := range 50
86
85
  d.pushBack(i)
87
86
  d.pushBack(i + 1000)
88
87
  assert d.popFront()! == i
89
88
  assert d.popFront()! == i + 1000
90
- i = i + 1
91
89
  assert d.isEmpty()
92
90
  assert d.head != 0 || d.buf.length() > 8
93
91
  # fill beyond capacity while head is mid-ring
94
92
  d.pushBack(1)
95
93
  d.pushBack(2)
96
94
  _ := d.popFront()
97
- i = 0
98
- while i < 20
95
+ for i := range 20
99
96
  d.pushBack(10 + i)
100
- i = i + 1
101
97
  assert d.length() == 21
102
98
  assert d.get(0)! == 2
103
99
  assert d.get(20)! == 29
@@ -105,10 +101,8 @@ test "deque_wraparound: head wraps past the end of the ring and growth unwraps i
105
101
 
106
102
  test "pushFront builds the front in reverse order"
107
103
  d := Deque[Int]()
108
- i := 0
109
- while i < 12
104
+ for i := range 12
110
105
  d.pushFront(i)
111
- i = i + 1
112
106
  assert d.get(0)! == 11
113
107
  assert d.get(11)! == 0
114
108
  assert d.popFront()! == 11
std/Heap.plum CHANGED
@@ -16,10 +16,10 @@ import std/Float
16
16
  struct Heap[T](items: Slice[T], key: fn(T) -> Float) =
17
17
 
18
18
  fun length(self) -> Int =
19
- return self.items.length()
19
+ self.items.length()
20
20
 
21
21
  fun isEmpty(self) -> Bool =
22
- return self.items.length() == 0
22
+ self.items.length() == 0
23
23
 
24
24
  fun clear(self) -> Unit =
25
25
  self.items.clear()
@@ -30,32 +30,23 @@ struct Heap[T](items: Slice[T], key: fn(T) -> Float) =
30
30
  self.items.data.set(j, a)
31
31
 
32
32
  fun less(self, i: Int, j: Int) -> Bool =
33
- return self.key(self.items.data.get(i)) < self.key(self.items.data.get(j))
33
+ self.key(self.items.data.get(i)) < self.key(self.items.data.get(j))
34
34
 
35
- fun siftUp(self, start: Int) -> Unit =
35
+ fun siftUp(self, i: Int) -> Unit =
36
- i := start
37
- while i > 0
38
- p := {i - 1} / 2
36
+ p := {i - 1} / 2
39
- if !self.less(i, p)
37
+ if i > 0 && self.less(i, p)
40
- return
41
38
  self.swap(i, p)
42
- i = p
39
+ self.siftUp(p)
43
40
 
44
- fun siftDown(self, start: Int) -> Unit =
41
+ fun siftDown(self, i: Int) -> Unit =
45
- i := start
46
42
  n := self.items.length()
47
- while true
48
- l := 2 * i + 1
43
+ l := 2 * i + 1
49
- r := l + 1
44
+ r := l + 1
50
- m := i
51
- if l < n && self.less(l, m)
45
+ lowest := if l < n && self.less(l, i) then l else i
52
- m = l
53
- if r < n && self.less(r, m)
46
+ m := if r < n && self.less(r, lowest) then r else lowest
54
- m = r
55
- if m == i
47
+ if m != i
56
- return
57
48
  self.swap(i, m)
58
- i = m
49
+ self.siftDown(m)
59
50
 
60
51
  fun push(self, v: T) -> Unit =
61
52
  self.items.push(v)
@@ -64,36 +55,35 @@ struct Heap[T](items: Slice[T], key: fn(T) -> Float) =
64
55
  # The smallest element without removing it, or None if empty.
65
56
  fun peek(self) -> Option[T] =
66
57
  if self.items.length() == 0
67
- return None
58
+ None
59
+ else
68
- Some(self.items.data.get(0))
60
+ Some(self.items.data.get(0))
69
61
 
70
62
  # Removes and returns the smallest element, or None if empty.
71
63
  fun pop(self) -> Option[T] =
72
64
  n := self.items.length()
73
65
  if n == 0
74
- return None
66
+ None
67
+ else
75
- top := self.items.data.get(0)
68
+ top := self.items.data.get(0)
76
- self.items.data.set(0, self.items.data.get(n - 1))
69
+ self.items.data.set(0, self.items.data.get(n - 1))
77
- self.items.size = n - 1
70
+ self.items.size = n - 1
78
- self.siftDown(0)
71
+ self.siftDown(0)
79
- Some(top)
72
+ Some(top)
80
73
 
81
74
  test "heap_pop_order: 1000 pseudo-random keys pop in ascending order"
82
75
  h := Heap[Int](items: Slice[Int](), key: |x| Float(x))
83
- x := 12345
76
+ _ := 1.to(1000).fold(12345, |x, _|
84
- i := 0
85
- while i < 1000
86
- x = {x * 1103515245 + 12345} % 2147483648
77
+ next := {x * 1103515245 + 12345} % 2147483648
87
- h.push(x % 100000)
78
+ h.push(next % 100000)
88
- i = i + 1
79
+ next
80
+ )
89
81
  assert h.length() == 1000
90
- prev := -1
91
- i = 0
92
- while i < 1000
82
+ _ := 1.to(1000).fold(-1, |prev, _|
93
83
  v := h.pop()!
94
84
  assert v >= prev
95
- prev = v
85
+ v
96
- i = i + 1
86
+ )
97
87
  assert h.isEmpty()
98
88
  assert h.pop().unwrapOr(-1) == -1
99
89
 
std/Json.plum CHANGED
@@ -49,7 +49,7 @@ enum Json =
49
49
  # learn where and why a parse failed use `Json.parse(s)` instead.
50
50
  fun fromStr(s: Str) -> Result[Json, JsonError] =
51
51
  parser := JsonParser(src: s, pos: 0, text: "")
52
- return parser.parseDocument()
52
+ parser.parseDocument()
53
53
 
54
54
  # Like `fromStr`, but the outcome is an ordinary value: `Parsed` with the
55
55
  # document, or `Failed` with the position and message of the failure.
@@ -77,7 +77,7 @@ enum Json =
77
77
  # `T` comes from the result annotation: `h: JsonError!House := Json.decode(s)`.
78
78
  fun decode[T](s: Str) -> Result[T, JsonError] =
79
79
  j := Json.fromStr(s)?
80
- return T.fromJson(j)
80
+ T.fromJson(j)
81
81
 
82
82
  # Decodes an already-parsed value; `T` comes from the result type.
83
83
  fun into[T](self) -> Result[T, JsonError] = T.fromJson(self)
@@ -85,7 +85,7 @@ enum Json =
85
85
  # Explicit-decoder form: `Json.decodeWith(s, |j| House.fromJson(j))`.
86
86
  fun decodeWith[T](s: Str, f: fn(Json) -> Result[T, JsonError]) -> Result[T, JsonError] =
87
87
  j := Json.fromStr(s)?
88
- return f(j)
88
+ f(j)
89
89
 
90
90
  fun field(self, name: Str) -> Result[Json, JsonError] =
91
91
  m := self.asMap()?
@@ -100,14 +100,14 @@ enum Json =
100
100
 
101
101
  # `Json.object(["a" => x, "b" => y])`: a map literal is already a Json object.
102
102
  fun object(fields: Map[Str, Json]) -> Json =
103
- return JsonObj(fields: fields)
103
+ JsonObj(fields: fields)
104
104
 
105
105
  # `Json.array([x, y])`.
106
106
  fun array(items: List[Json]) -> Json =
107
107
  out := Slice[Json]()
108
108
  for x := range items
109
109
  out.push(x)
110
- return JsonArr(items: out)
110
+ JsonArr(items: out)
111
111
 
112
112
  fun toJson(self) -> Json = self
113
113
 
@@ -154,7 +154,7 @@ enum Json =
154
154
  buf := Buffer()
155
155
  for e := range pairs.entries()
156
156
  appendJsonPair(buf, e.first, e.second)
157
- return buf.toStr()
157
+ buf.toStr()
158
158
 
159
159
  fun appendJsonPair(buf: Buffer, k: Str, v: Json) -> Unit =
160
160
  if !buf.isEmpty()
@@ -166,10 +166,16 @@ enum Json =
166
166
 
167
167
  fun escapeJsonStr(s: Str) -> Str =
168
168
  buf := Buffer()
169
+ escapeFrom(s, buf, 0)
170
+ buf.toStr()
171
+
172
+ # `escapeJsonStr`'s loop: escapes the codepoints of `s` from byte `i` on into `buf`.
173
+ fun escapeFrom(s: Str, buf: Buffer, i: Int) -> Unit =
169
- len := s.length()
174
+ if i < s.length()
170
- i := 0
171
- while i < len
172
175
  b := s.byteAt(i)
176
+ # Copies a whole UTF-8 codepoint at once: copying a lone continuation
177
+ # byte as its own "character" would corrupt any non-ASCII text.
178
+ step := if b < 0x20 || b == 34 || b == 92 then 1 else s.codePointByteLength(i)
173
179
  if b == 34
174
180
  buf.write("\\\"")
175
181
  else if b == 92
@@ -188,13 +194,8 @@ enum Json =
188
194
  buf.write("\\u00")
189
195
  buf.write(hexByteStr(b))
190
196
  else
191
- # Copies a whole UTF-8 codepoint at once: copying a lone continuation
192
- # byte as its own "character" would corrupt any non-ASCII text.
193
- n := s.codePointByteLength(i)
194
- buf.write(s.sub(i, i + n))
197
+ buf.write(s.sub(i, i + step))
195
- i = i + n - 1
196
- i = i + 1
197
- return buf.toStr()
198
+ escapeFrom(s, buf, i + step)
198
199
 
199
200
  fun hexByteStr(b: Int) -> Str =
200
201
  hexDigitChar(b / 16) + hexDigitChar(b % 16)
@@ -247,8 +248,9 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
247
248
  self.skipSpace()
248
249
  if self.pos < self.src.length()
249
250
  self.note("unexpected trailing characters")
250
- return Err(InvalidJson)
251
+ Err(InvalidJson)
252
+ else
251
- return Ok(v)
253
+ Ok(v)
252
254
 
253
255
  # The raw byte at the current position, or 0 (never a valid JSON byte) past
254
256
  # the end of `src` — lets every caller test for "end of input" the same way
@@ -264,37 +266,40 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
264
266
  self.pos = self.pos + 1
265
267
 
266
268
  fun skipSpace(self) -> Unit =
267
- while isSpace(self.peek())
269
+ if isSpace(self.peek())
268
270
  self.advance()
271
+ self.skipSpace()
269
272
 
270
273
  fun parseValue(self) -> Result[Json, JsonError] =
271
274
  self.skipSpace()
272
275
  c := self.peek()
273
276
  if c == 34
274
277
  str := self.parseString()?
275
- return Ok(JsonStr(value: str))
278
+ Ok(JsonStr(value: str))
276
- if c == 91
279
+ else if c == 91
277
- return self.parseArray()
280
+ self.parseArray()
278
- if c == 123
281
+ else if c == 123
279
- return self.parseObject()
282
+ self.parseObject()
280
- if c == 116
283
+ else if c == 116
281
- return self.parseLiteral("true", JsonBool(value: true))
284
+ self.parseLiteral("true", JsonBool(value: true))
282
- if c == 102
285
+ else if c == 102
283
- return self.parseLiteral("false", JsonBool(value: false))
286
+ self.parseLiteral("false", JsonBool(value: false))
284
- if c == 110
287
+ else if c == 110
285
- return self.parseLiteral("null", JsonNull)
288
+ self.parseLiteral("null", JsonNull)
286
- if c == 45 || isDigit(c)
289
+ else if c == 45 || isDigit(c)
287
- return self.parseNumber()
290
+ self.parseNumber()
291
+ else
288
- self.note("unexpected character")
292
+ self.note("unexpected character")
289
- return Err(InvalidJson)
293
+ Err(InvalidJson)
290
294
 
291
295
  fun parseLiteral(self, lit: Str, value: Json) -> Result[Json, JsonError] =
292
296
  n := lit.length()
293
297
  if !Str.matchesAt(self.src, lit, self.pos, n)
294
298
  self.note("invalid literal, expected '{lit}'")
295
- return Err(InvalidJson)
299
+ Err(InvalidJson)
300
+ else
296
- self.pos = self.pos + n
301
+ self.pos = self.pos + n
297
- return Ok(value)
302
+ Ok(value)
298
303
 
299
304
  fun parseNumber(self) -> Result[Json, JsonError] =
300
305
  start := self.pos
@@ -302,26 +307,43 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
302
307
  self.advance()
303
308
  if !isDigit(self.peek())
304
309
  self.note("invalid number")
305
- return Err(InvalidJson)
310
+ Err(InvalidJson)
311
+ else
312
+ self.skipDigits()
313
+ self.parseFraction(start)
314
+
315
+ fun skipDigits(self) -> Unit =
306
- while isDigit(self.peek())
316
+ if isDigit(self.peek())
307
317
  self.advance()
318
+ self.skipDigits()
319
+
320
+ # The optional `.digits` part of a number that began at `start`.
321
+ fun parseFraction(self, start: Int) -> Result[Json, JsonError] =
308
322
  if self.peek() == 46
309
323
  self.advance()
310
324
  if !isDigit(self.peek())
311
325
  self.note("invalid number")
312
- return Err(InvalidJson)
326
+ Err(InvalidJson)
313
- while isDigit(self.peek())
327
+ else
314
- self.advance()
328
+ self.skipDigits()
329
+ self.parseExponent(start)
330
+ else
331
+ self.parseExponent(start)
332
+
333
+ # The optional `e[+-]digits` part of a number that began at `start`.
334
+ fun parseExponent(self, start: Int) -> Result[Json, JsonError] =
315
335
  if self.peek() == 101 || self.peek() == 69
316
336
  self.advance()
317
337
  if self.peek() == 43 || self.peek() == 45
318
338
  self.advance()
319
339
  if !isDigit(self.peek())
320
340
  self.note("invalid number")
321
- return Err(InvalidJson)
341
+ Err(InvalidJson)
322
- while isDigit(self.peek())
342
+ else
323
- self.advance()
343
+ self.skipDigits()
324
- return self.parseNumberText(self.src.sub(start, self.pos))
344
+ self.parseNumberText(self.src.sub(start, self.pos))
345
+ else
346
+ self.parseNumberText(self.src.sub(start, self.pos))
325
347
 
326
348
  # `Float.fromStr` (`libs/std/float.plum`) doesn't understand exponent
327
349
  # notation, so a number that has one is split into its mantissa and
@@ -330,29 +352,34 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
330
352
  e_index := exponentIndex(text)
331
353
  if e_index < 0
332
354
  f := Float.parse(text).mapErr(|e| self.badNumber())?
333
- return Ok(JsonNum(value: f))
355
+ Ok(JsonNum(value: f))
356
+ else
334
- mv := Float.parse(text.sub(0, e_index)).mapErr(|e| self.badNumber())?
357
+ mv := Float.parse(text.sub(0, e_index)).mapErr(|e| self.badNumber())?
335
- ev := Int.parse(text.sub(e_index + 1, text.length())).mapErr(|e| self.badNumber())?
358
+ ev := Int.parse(text.sub(e_index + 1, text.length())).mapErr(|e| self.badNumber())?
336
- return Ok(JsonNum(value: mv * 10.pow(Float(ev))))
359
+ Ok(JsonNum(value: mv * 10.pow(Float(ev))))
337
360
 
338
361
  fun parseString(self) -> Result[Str, JsonError] =
339
362
  self.advance()
340
363
  buf := Buffer()
341
- while true
364
+ self.parseStringBody(buf)
365
+
366
+ # `parseString`'s loop: the characters up to the closing quote, into `buf`.
367
+ fun parseStringBody(self, buf: Buffer) -> Result[Str, JsonError] =
342
- c := self.peek()
368
+ c := self.peek()
343
- if c == 0
369
+ if c == 0
344
- self.note("unterminated string")
370
+ self.note("unterminated string")
345
- return Err(InvalidJson)
371
+ Err(InvalidJson)
346
- if c == 34
372
+ else if c == 34
347
- self.advance()
373
+ self.advance()
348
- return Ok(buf.toStr())
374
+ Ok(buf.toStr())
349
- if c == 92
375
+ else if c == 92
350
- self.parseEscape(buf)?
376
+ self.parseEscape(buf)?
377
+ self.parseStringBody(buf)
351
- else
378
+ else
352
- n := self.src.codePointByteLength(self.pos)
379
+ n := self.src.codePointByteLength(self.pos)
353
- buf.write(self.src.sub(self.pos, self.pos + n))
380
+ buf.write(self.src.sub(self.pos, self.pos + n))
354
- self.pos = self.pos + n
381
+ self.pos = self.pos + n
355
- return Ok(buf.toStr())
382
+ self.parseStringBody(buf)
356
383
 
357
384
  # Handles one escape sequence (the cursor is on the backslash), writing the
358
385
  # decoded text into `buf`.
@@ -361,41 +388,53 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
361
388
  esc := self.peek()
362
389
  if esc == 117
363
390
  self.advance()
364
- return self.parseUnicodeEscape(buf)
391
+ self.parseUnicodeEscape(buf)
392
+ else
393
+ text := escapeText(esc)
394
+ if text.length() == 0
395
+ self.note("invalid escape character")
396
+ Err(InvalidJson)
397
+ else
398
+ buf.write(text)
399
+ self.advance()
400
+ Ok(Unit)
401
+
402
+ # What the simple escape `\<esc>` stands for, or "" if `esc` isn't one.
403
+ fun escapeText(esc: Int) -> Str =
365
404
  if esc == 34
366
- buf.write("\"")
405
+ "\""
367
406
  else if esc == 92
368
- buf.write("\\")
407
+ "\\"
369
408
  else if esc == 47
370
- buf.write("/")
409
+ "/"
371
410
  else if esc == 98
372
- buf.write("\b")
411
+ "\b"
373
412
  else if esc == 102
374
- buf.write("\f")
413
+ "\f"
375
414
  else if esc == 110
376
- buf.write("\n")
415
+ "\n"
377
416
  else if esc == 114
378
- buf.write("\r")
417
+ "\r"
379
418
  else if esc == 116
380
- buf.write("\t")
419
+ "\t"
381
420
  else
382
- self.note("invalid escape character")
383
- return Err(InvalidJson)
384
- self.advance()
421
+ ""
385
- Ok(Unit)
386
422
 
387
423
  fun parseHex4(self) -> Result[Int, JsonError] =
388
- value := 0
424
+ self.parseHexDigits(0, 0)
425
+
389
- count := 0
426
+ # `parseHex4`'s loop: `count` digits read so far, worth `value`.
427
+ fun parseHexDigits(self, count: Int, value: Int) -> Result[Int, JsonError] =
390
- while count < 4
428
+ if count >= 4
429
+ Ok(value)
430
+ else
391
431
  d := hexDigitValue(self.peek())
392
432
  if d < 0
393
433
  self.note("invalid unicode escape")
394
- return Err(InvalidJson)
434
+ Err(InvalidJson)
435
+ else
395
- self.advance()
436
+ self.advance()
396
- value = value * 16 + d
437
+ self.parseHexDigits(count + 1, value * 16 + d)
397
- count = count + 1
398
- return Ok(value)
399
438
 
400
439
  # Decodes the four hex digits after `\u` (and, for a high surrogate
401
440
  # (`0xD800`..`0xDBFF`), the `\u` low surrogate (`0xDC00`..`0xDFFF`) that must
@@ -409,12 +448,14 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
409
448
  low := self.parseHex4()?
410
449
  if low < 0xDC00 || low > 0xDFFF
411
450
  self.note("invalid low surrogate")
412
- return Err(InvalidJson)
451
+ Err(InvalidJson)
452
+ else
413
- combined := 0x10000 + {{cp - 0xD800} << 10} + {low - 0xDC00}
453
+ combined := 0x10000 + {{cp - 0xD800} << 10} + {low - 0xDC00}
414
- buf.writeRune(combined)
454
+ buf.writeRune(combined)
415
- return Ok(Unit)
455
+ Ok(Unit)
456
+ else
416
- buf.writeRune(cp)
457
+ buf.writeRune(cp)
417
- Ok(Unit)
458
+ Ok(Unit)
418
459
 
419
460
  fun parseArray(self) -> Result[Json, JsonError] =
420
461
  self.advance()
@@ -422,21 +463,26 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
422
463
  items := Slice[Json]()
423
464
  if self.peek() == 93
424
465
  self.advance()
425
- return Ok(JsonArr(items: items))
466
+ Ok(JsonArr(items: items))
426
- while true
467
+ else
468
+ self.parseArrayItems(items)
469
+
470
+ # `parseArray`'s loop: the values up to the closing bracket, pushed onto `items`.
471
+ fun parseArrayItems(self, items: Slice[Json]) -> Result[Json, JsonError] =
427
- self.skipSpace()
472
+ self.skipSpace()
428
- v := self.parseValue()?
473
+ v := self.parseValue()?
429
- items.push(v)
474
+ items.push(v)
430
- self.skipSpace()
475
+ self.skipSpace()
431
- c := self.peek()
476
+ c := self.peek()
432
- if c == 93
477
+ if c == 93
433
- self.advance()
478
+ self.advance()
434
- return Ok(JsonArr(items: items))
479
+ Ok(JsonArr(items: items))
435
- if c != 44
480
+ else if c != 44
436
- self.note("expected ',' or ']'")
481
+ self.note("expected ',' or ']'")
437
- return Err(InvalidJson)
482
+ Err(InvalidJson)
483
+ else
438
484
  self.advance()
439
- return Ok(JsonArr(items: items))
485
+ self.parseArrayItems(items)
440
486
 
441
487
  fun parseObject(self) -> Result[Json, JsonError] =
442
488
  self.advance()
@@ -444,31 +490,38 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
444
490
  pairs: Map[Str, Json] := Map.empty()
445
491
  if self.peek() == 125
446
492
  self.advance()
447
- return Ok(JsonObj(fields: pairs))
493
+ Ok(JsonObj(fields: pairs))
448
- while true
494
+ else
495
+ self.parsePairs(pairs)
496
+
497
+ # `parseObject`'s loop: the `key: value` pairs up to the closing brace, set into `pairs`.
498
+ fun parsePairs(self, pairs: Map[Str, Json]) -> Result[Json, JsonError] =
449
- self.skipSpace()
499
+ self.skipSpace()
450
- if self.peek() != 34
500
+ if self.peek() != 34
451
- self.note("expected string key")
501
+ self.note("expected string key")
452
- return Err(InvalidJson)
502
+ Err(InvalidJson)
503
+ else
453
504
  key := self.parseString()?
454
505
  self.skipSpace()
455
506
  if self.peek() != 58
456
507
  self.note("expected ':'")
457
- return Err(InvalidJson)
508
+ Err(InvalidJson)
458
- self.advance()
459
- self.skipSpace()
509
+ else
460
- v := self.parseValue()?
461
- pairs.set(key, v)
462
- self.skipSpace()
463
- c := self.peek()
464
- if c == 125
465
510
  self.advance()
511
+ self.skipSpace()
512
+ v := self.parseValue()?
513
+ pairs.set(key, v)
514
+ self.skipSpace()
515
+ c := self.peek()
516
+ if c == 125
517
+ self.advance()
466
- return Ok(JsonObj(fields: pairs))
518
+ Ok(JsonObj(fields: pairs))
467
- if c != 44
519
+ else if c != 44
468
- self.note("expected ',' or '}}'")
520
+ self.note("expected ',' or '}}'")
469
- return Err(InvalidJson)
521
+ Err(InvalidJson)
522
+ else
470
- self.advance()
523
+ self.advance()
471
- return Ok(JsonObj(fields: pairs))
524
+ self.parsePairs(pairs)
472
525
 
473
526
  fun exponentIndex(text: Str) -> Int =
474
527
  e := text.indexOf("e")
@@ -476,12 +529,13 @@ struct JsonParser(src: Str, mut pos: Int, mut text: Str) =
476
529
 
477
530
  fun hexDigitValue(b: Int) -> Int =
478
531
  if b >= 48 && b <= 57
479
- return b - 48
532
+ b - 48
480
- if b >= 97 && b <= 102
533
+ else if b >= 97 && b <= 102
481
- return b - 97 + 10
534
+ b - 97 + 10
482
- if b >= 65 && b <= 70
535
+ else if b >= 65 && b <= 70
483
- return b - 65 + 10
536
+ b - 65 + 10
484
- return -1
537
+ else
538
+ -1
485
539
 
486
540
  fun isSpace(c: Int) -> Bool =
487
541
  c == 32 || c >= 9 && c <= 13
@@ -499,11 +553,13 @@ primitive Int =
499
553
  fun fromJson(j: Json) -> Result[Int, JsonError] =
500
554
  f := j.asFloat()?
501
555
  if f >= 9007199254740992.0f || f <= -9007199254740992.0f
502
- return Err(WrongJsonType)
556
+ Err(WrongJsonType)
557
+ else
503
- n := Int(f)
558
+ n := Int(f)
504
- if Float(n) != f
559
+ if Float(n) != f
505
- return Err(WrongJsonType)
560
+ Err(WrongJsonType)
561
+ else
506
- return Ok(n)
562
+ Ok(n)
507
563
 
508
564
  primitive Float =
509
565
  fun toJson(self) -> Json = JsonNum(value: self)
@@ -526,15 +582,21 @@ primitive Slice[T] =
526
582
  out := Slice[Json]()
527
583
  for x := range self
528
584
  out.push(x.toJson())
529
- return JsonArr(items: out)
585
+ JsonArr(items: out)
530
586
 
531
587
  # Decodes each element with `T.fromJson`.
532
588
  fun fromJson(j: Json) -> Result[Slice[T], JsonError] =
533
589
  items := j.asList()?
534
- out := Slice[T]()
590
+ fromJsonFrom(items, 0, Slice[T]())
591
+
592
+ # `fromJson`'s loop: decodes the elements of `items` from `i` on, pushing onto `out`.
593
+ fun fromJsonFrom(items: Slice[Json], i: Int, out: Slice[T]) -> Result[Slice[T], JsonError] =
535
- for x := range items
594
+ if i >= items.length()
536
- out.push(T.fromJson(x)?)
537
- return Ok(out)
595
+ Ok(out)
596
+ else
597
+ x := T.fromJson(items.at(i))?
598
+ out.push(x)
599
+ fromJsonFrom(items, i + 1, out)
538
600
 
539
601
  primitive Map[K, V] =
540
602
  # A JSON object; keys must be `Str`.
@@ -542,14 +604,22 @@ primitive Map[K, V] =
542
604
  out: Map[Str, Json] := Map.empty()
543
605
  for e := range self.entries()
544
606
  out.set(e.first, e.second.toJson())
545
- return JsonObj(fields: out)
607
+ JsonObj(fields: out)
546
608
 
547
609
  fun fromJson(j: Json) -> Result[Map[Str, V], JsonError] =
548
610
  pairs := j.asMap()?
549
611
  out: Map[Str, V] := Map.empty()
550
- for e := range pairs.entries()
612
+ fromJsonPairs(pairs.entries(), 0, out)
613
+
614
+ # `fromJson`'s loop: decodes the values of `entries` from `i` on, setting them into `out`.
615
+ fun fromJsonPairs(entries: Slice[Pair[Str, Json]], i: Int, out: Map[Str, V]) -> Result[Map[Str, V], JsonError] =
616
+ if i >= entries.length()
617
+ Ok(out)
618
+ else
619
+ e := entries.at(i)
551
- out.set(e.first, V.fromJson(e.second)?)
620
+ v := V.fromJson(e.second)?
552
- return Ok(out)
621
+ out.set(e.first, v)
622
+ fromJsonPairs(entries, i + 1, out)
553
623
 
554
624
  fun jsonTestDecodeInt(s: Str) -> Result[Int, JsonError] = Json.decode(s)
555
625
 
@@ -569,7 +639,7 @@ struct JsonTestHouse(name: Str, rooms: Int, kids: Slice[JsonTestHouse]) =
569
639
  name := Str.fromJson(j.field("name")?)?
570
640
  rooms := Int.fromJson(j.field("rooms")?)?
571
641
  kids := jsonTestKidsOf(j.field("kids")?)?
572
- return Ok(JsonTestHouse(name: name, rooms: rooms, kids: kids))
642
+ Ok(JsonTestHouse(name: name, rooms: rooms, kids: kids))
573
643
 
574
644
  fun jsonTestKidsOf(j: Json) -> Result[Slice[JsonTestHouse], JsonError] = j.into()
575
645
 
@@ -645,10 +715,8 @@ test "toStr escapes special characters in strings"
645
715
 
646
716
  test "round-trips a 100000 character string"
647
717
  buf := Buffer()
648
- i := 0
649
- while i < 100000
718
+ for i := range 100000
650
719
  buf.write("a")
651
- i = i + 1
652
720
  doc := "\"" + buf.toStr() + "\""
653
721
  v := Json.fromStr(doc)!
654
722
  assert v.asStr()!.length() == 100000
@@ -657,10 +725,8 @@ test "round-trips a 100000 character string"
657
725
  test "parses a 10000 element array"
658
726
  buf := Buffer()
659
727
  buf.write("[0")
660
- i := 1
661
- while i < 10000
728
+ for i := range 1.until(10000)
662
729
  buf.write(",{i}")
663
- i = i + 1
664
730
  buf.write("]")
665
731
  items := Json.fromStr(buf.toStr())!.asList()!
666
732
  assert items.length() == 10000
@@ -669,10 +735,8 @@ test "parses a 10000 element array"
669
735
  test "parses an object with 2000 keys"
670
736
  buf := Buffer()
671
737
  buf.write("{{\"k0\":0")
672
- i := 1
673
- while i < 2000
738
+ for i := range 1.until(2000)
674
739
  buf.write(",\"k{i}\":{i}")
675
- i = i + 1
676
740
  buf.write("}}")
677
741
  pairs := Json.fromStr(buf.toStr())!.asMap()!
678
742
  assert pairs.get("k1999")!.asFloat()! == 1999.0f
@@ -680,10 +744,8 @@ test "parses an object with 2000 keys"
680
744
 
681
745
  test "escapes a 50000 character string of quotes and newlines"
682
746
  buf := Buffer()
683
- i := 0
684
- while i < 25000
747
+ for i := range 25000
685
748
  buf.write("\"\n")
686
- i = i + 1
687
749
  j: Json := JsonStr(value: buf.toStr())
688
750
  out := j.toStr()
689
751
  assert out.length() == 100002
std/List.plum CHANGED
@@ -76,53 +76,42 @@ enum List[T] =
76
76
 
77
77
  # The elements of `xs` as a cons list, in order.
78
78
  fun fromSlice(xs: Slice[T]) -> List[T] =
79
- out: List[T] := Nil
79
+ nil: List[T] := Nil
80
- i := xs.length() - 1
80
+ consFrom(xs, xs.length() - 1, nil)
81
- while i >= 0
82
- out = Cons(head: xs.at(i), tail: out)
83
- i = i - 1
84
- return out
85
81
 
86
82
  fun toSlice(self) -> Slice[T] =
87
83
  out := Slice()
88
84
  for x := range self
89
85
  out.push(x)
90
- return out
86
+ out
91
87
 
92
88
  fun toArray(self) -> Array[T] =
93
- out := Array[T]()
94
- for x := range self
95
- out = out.push(x)
89
+ self.fold(Array[T](), |out, x| out.push(x))
96
- return out
97
90
 
98
91
  fun toStr(self) -> Str =
99
92
  res := Buffer()
100
93
  res.write("[")
101
- first := true
94
+ if Cons(h, t) := self
95
+ res.write(h.toStr())
102
- for x := range self
96
+ for x := range t
103
- if !first
104
97
  res.write(",")
105
- first = false
106
- res.write(x.toStr())
98
+ res.write(x.toStr())
107
99
  res.write("]")
108
- return res.toStr()
100
+ res.toStr()
109
101
 
110
102
  # Elementwise comparison via `==`.
111
- fun equals(self, other: List[T]) -> Bool =
103
+ fun equals(self, other: List[T]) -> Bool = match self
112
- a := self
113
- b := other
104
+ Nil => other.isEmpty()
114
- while true
115
- if Cons(h, t) := a
105
+ Cons(h, t) => match other
116
- if Cons(h2, t2) := b
106
+ Nil => false
107
+ Cons(h2, t2) => if h != h2 then false else t.equals(t2)
108
+
109
+ # `fromSlice`'s loop: conses `xs[i]`, `xs[i-1]`, ... down to index 0 onto `out`.
110
+ fun consFrom[A](xs: Slice[A], i: Int, out: List[A]) -> List[A] =
117
- if h != h2
111
+ if i < 0
118
- return false
119
- a = t
112
+ out
120
- b = t2
121
- else
113
+ else
122
- return false
123
- else
124
- return b.isEmpty()
114
+ consFrom(xs, i - 1, Cons(head: xs.at(i), tail: out))
125
- return true
126
115
 
127
116
  # `map`'s loop: a constructor wrapped self call, rewritten to a loop (TRMC).
128
117
  fun mapCells[A, B](xs: List[A], f: fn(A) -> B) -> List[B] = match xs
@@ -130,11 +119,8 @@ fun mapCells[A, B](xs: List[A], f: fn(A) -> B) -> List[B] = match xs
130
119
  Cons(h, t) => Cons(head: f(h), tail: mapCells(t, f))
131
120
 
132
121
  test "filter_million_constant_stack"
133
- xs: List[Int] := Nil
122
+ nil: List[Int] := Nil
134
- i := 1000000
135
- while i > 0
136
- xs = Cons(head: i, tail: xs)
123
+ xs := 1.to(1000000).fold(nil, |acc, i| Cons(head: i, tail: acc))
137
- i = i - 1
138
124
  evens := xs.filter(|x| x % 2 == 0)
139
125
  assert evens.length() == 500000
140
126
 
std/Map.plum CHANGED
@@ -40,7 +40,7 @@ struct Map[K, V](mut index: Array[Int], mut hashes: Array[Int], mut keys: Array[
40
40
  fun empty() -> Map[K, V] =
41
41
  m := Map(index: Array[Int](), hashes: Array[Int](), keys: Array[K](), vals: Array[V](), alive: Array[Bool](), used: 0, size: 0)
42
42
  m.allocate(16)
43
- return m
43
+ m
44
44
 
45
45
  # Installs empty storage for `cap` index slots (a power of two).
46
46
  fun allocate(self, cap: Int) -> Unit =
@@ -57,33 +57,34 @@ struct Map[K, V](mut index: Array[Int], mut hashes: Array[Int], mut keys: Array[
57
57
  # spread across the low bits that pick the slot.
58
58
  fun hashOf(self, k: K) -> Int =
59
59
  h := k.hash()
60
- h = {h ^ {h >> 32}} * 0x5851f42d4c957f2d
60
+ mixed := {h ^ {h >> 32}} * 0x5851f42d4c957f2d
61
- return h ^ {h >> 29}
61
+ mixed ^ {mixed >> 29}
62
62
 
63
63
  # The `index` slot holding `k` (whose hash is `h`), or -1.
64
64
  fun findSlot(self, k: K, h: Int) -> Int =
65
65
  mask := self.index.length() - 1
66
- slot := h & mask
66
+ self.probeFor(h & mask, mask, k, h)
67
+
67
- while true
68
+ # Linear probe from `slot` for `k`: the slot holding it, or -1 at an empty slot.
69
+ fun probeFor(self, slot: Int, mask: Int, k: K, h: Int) -> Int =
68
- x := self.index.get(slot)
70
+ x := self.index.get(slot)
69
- if x == 0
71
+ if x == 0
70
- return -1
72
+ -1
71
- if x >= 2
72
- e := x - 2
73
- if self.hashes.get(e) == h && self.keys.get(e) == k
73
+ else if x >= 2 && self.hashes.get(x - 2) == h && self.keys.get(x - 2) == k
74
- return slot
74
+ slot
75
+ else
75
- slot = {slot + 1} & mask
76
+ self.probeFor({slot + 1} & mask, mask, k, h)
76
- return -1
77
77
 
78
78
  # Gets the value for `k`, or None if absent.
79
79
  fun get(self, k: K) -> Option[V] =
80
80
  slot := self.findSlot(k, self.hashOf(k))
81
81
  if slot < 0
82
- return None
82
+ None
83
+ else
83
- Some(self.vals.get(self.index.get(slot) - 2))
84
+ Some(self.vals.get(self.index.get(slot) - 2))
84
85
 
85
86
  fun has(self, k: K) -> Bool =
86
- return self.findSlot(k, self.hashOf(k)) >= 0
87
+ self.findSlot(k, self.hashOf(k)) >= 0
87
88
 
88
89
  # Rebuilds the table when the entry arrays are full: doubles the capacity if
89
90
  # at least half the entries are live, else compacts at the same capacity.
@@ -95,18 +96,13 @@ struct Map[K, V](mut index: Array[Int], mut hashes: Array[Int], mut keys: Array[
95
96
  oldAlive := self.alive
96
97
  oldUsed := self.used
97
98
  n := cap - cap / 4
98
- newCap := cap
99
- if self.size * 2 >= n
99
+ newCap := if self.size * 2 >= n then cap * 2 else cap
100
- newCap = cap * 2
101
100
  self.allocate(newCap)
102
101
  mask := newCap - 1
103
- e := 0
104
- while e < oldUsed
102
+ for e := range oldUsed
105
103
  if oldAlive.get(e)
106
104
  h := oldHashes.get(e)
107
- slot := h & mask
108
- while self.index.get(slot) != 0
109
- slot = {slot + 1} & mask
105
+ slot := self.emptySlot(h & mask, mask)
110
106
  j := self.used
111
107
  self.index.set(slot, j + 2)
112
108
  self.hashes.set(j, h)
@@ -114,27 +110,39 @@ struct Map[K, V](mut index: Array[Int], mut hashes: Array[Int], mut keys: Array[
114
110
  self.vals.set(j, oldVals.get(e))
115
111
  self.alive.set(j, true)
116
112
  self.used = j + 1
117
- e = e + 1
118
113
  self.size = self.used
119
114
 
115
+ # The first empty (0) slot at or after `slot`, probing linearly.
116
+ fun emptySlot(self, slot: Int, mask: Int) -> Int =
117
+ if self.index.get(slot) != 0
118
+ self.emptySlot({slot + 1} & mask, mask)
119
+ else
120
+ slot
121
+
122
+ # The slot a new key is inserted at: the first tombstone on its probe path,
123
+ # else the empty slot that ends it. `tomb` is the first tombstone seen, or -1.
124
+ fun insertSlot(self, slot: Int, mask: Int, tomb: Int) -> Int =
125
+ x := self.index.get(slot)
126
+ if x == 0
127
+ if tomb >= 0 then tomb else slot
128
+ else
129
+ self.insertSlot({slot + 1} & mask, mask, if tomb < 0 && x == 1 then slot else tomb)
130
+
120
131
  # Sets `k`'s value to `v`, replacing an existing entry for `k` in place.
121
132
  fun set(self, k: K, v: V) -> Unit =
122
133
  h := self.hashOf(k)
123
134
  slot := self.findSlot(k, h)
124
135
  if slot >= 0
125
136
  self.vals.set(self.index.get(slot) - 2, v)
126
- return
137
+ else
138
+ self.insertNew(k, v, h)
139
+
140
+ # Appends a key known to be absent (hash `h`), rebuilding first if full.
141
+ fun insertNew(self, k: K, v: V, h: Int) -> Unit =
127
142
  if self.used >= self.hashes.length()
128
143
  self.rebuild()
129
144
  mask := self.index.length() - 1
130
- slot = h & mask
131
- tomb := -1
132
- while self.index.get(slot) != 0
133
- if tomb < 0 && self.index.get(slot) == 1
134
- tomb = slot
135
- slot = {slot + 1} & mask
145
+ slot := self.insertSlot(h & mask, mask, -1)
136
- if tomb >= 0
137
- slot = tomb
138
146
  e := self.used
139
147
  self.index.set(slot, e + 2)
140
148
  self.hashes.set(e, h)
@@ -149,7 +157,7 @@ struct Map[K, V](mut index: Array[Int], mut hashes: Array[Int], mut keys: Array[
149
157
  # statement-position callers need no `_ :=`.)
150
158
  fun with(self, k: K, v: V) -> Map[K, V] =
151
159
  self.set(k, v)
152
- return self
160
+ self
153
161
 
154
162
  # Sets `k`'s value to `v` only if `k` isn't already present.
155
163
  fun putIfAbsent(self, k: K, v: V) -> Unit =
@@ -165,10 +173,10 @@ struct Map[K, V](mut index: Array[Int], mut hashes: Array[Int], mut keys: Array[
165
173
  self.size = self.size - 1
166
174
 
167
175
  fun length(self) -> Int =
168
- return self.size
176
+ self.size
169
177
 
170
178
  fun isEmpty(self) -> Bool =
171
- return self.size == 0
179
+ self.size == 0
172
180
 
173
181
  fun clear(self) -> Unit =
174
182
  self.allocate(16)
@@ -177,32 +185,26 @@ struct Map[K, V](mut index: Array[Int], mut hashes: Array[Int], mut keys: Array[
177
185
  # (`e.first`, `e.second`).
178
186
  fun entries(self) -> Slice[Pair[K, V]] =
179
187
  out := Slice[Pair[K, V]]()
180
- i := 0
181
- while i < self.used
188
+ for i := range self.used
182
189
  if self.alive.get(i)
183
190
  out.push(Pair(first: self.keys.get(i), second: self.vals.get(i)))
184
- i = i + 1
185
- return out
191
+ out
186
192
 
187
193
  # Every key, in insertion order: `for k := range m.keys()`.
188
194
  fun keys(self) -> Slice[K] =
189
195
  out := Slice[K]()
190
- i := 0
191
- while i < self.used
196
+ for i := range self.used
192
197
  if self.alive.get(i)
193
198
  out.push(self.keys.get(i))
194
- i = i + 1
195
- return out
199
+ out
196
200
 
197
201
  # Every value, in insertion order: `for v := range m.values()`.
198
202
  fun values(self) -> Slice[V] =
199
203
  out := Slice[V]()
200
- i := 0
201
- while i < self.used
204
+ for i := range self.used
202
205
  if self.alive.get(i)
203
206
  out.push(self.vals.get(i))
204
- i = i + 1
205
- return out
207
+ out
206
208
 
207
209
  test "get/set/has round-trip and set replaces an existing key in place"
208
210
  m: Map[Str, Int] := Map.empty()
@@ -243,15 +245,11 @@ test "removing then re-adding keys keeps lookups correct"
243
245
 
244
246
  test "many keys landing in the same bucket still resolve correctly (collision chaining)"
245
247
  m: Map[Int, Int] := Map.empty()
246
- i := 0
247
- while i < 40
248
+ for i := range 40
248
249
  m.set(i, i * i)
249
- i = i + 1
250
250
  assert m.length() == 40
251
- j := 0
252
- while j < 40
251
+ for j := range 40
253
252
  assert m.get(j)! == j * j
254
- j = j + 1
255
253
  m.remove(5)
256
254
  assert m.has(5) == false
257
255
  assert m.get(4)! == 16
@@ -260,15 +258,11 @@ test "many keys landing in the same bucket still resolve correctly (collision ch
260
258
 
261
259
  test "map_collisions_erased: Map[Str, Int] with 500 keys round-trips"
262
260
  m: Map[Str, Int] := Map.empty()
263
- i := 0
264
- while i < 500
261
+ for i := range 500
265
262
  m.set("key{i}", i * 3)
266
- i = i + 1
267
263
  assert m.length() == 500
268
- j := 0
269
- while j < 500
264
+ for j := range 500
270
265
  assert m.get("key{j}")! == j * 3
271
- j = j + 1
272
266
  assert m.has("key500") == false
273
267
  m.remove("key250")
274
268
  assert m.length() == 499
@@ -280,66 +274,53 @@ test "map_for_entries: for e := range m.entries() visits every entry once"
280
274
  m.set("a", 1)
281
275
  m.set("b", 2)
282
276
  m.set("c", 3)
283
- total := 0
284
- seen := 0
285
- for e := range m.entries()
277
+ es := m.entries()
286
- total = total + e.second
278
+ total := 0.until(es.length()).fold(0, |acc, i| acc + es.at(i).second)
287
- seen = seen + e.first.length()
279
+ seen := 0.until(es.length()).fold(0, |acc, i| acc + es.at(i).first.length())
288
280
  assert total == 6
289
281
  assert seen == 3
290
282
 
291
283
  test "map_keys_values_methods: keys() and values() are for sources"
292
284
  m: Map[Int, Int] := Map.empty()
293
- i := 0
294
- while i < 20
285
+ for i := range 20
295
286
  m.set(i, i * 10)
296
- i = i + 1
297
- ks := 0
298
- for k := range m.keys()
287
+ ks := m.keys()
299
- ks = ks + k
300
- vs := 0
301
- for v := range m.values()
288
+ vs := m.values()
302
- vs = vs + v
303
- assert ks == 190
289
+ assert 0.until(ks.length()).fold(0, |acc, i| acc + ks.at(i)) == 190
304
- assert vs == 1900
290
+ assert 0.until(vs.length()).fold(0, |acc, i| acc + vs.at(i)) == 1900
305
291
 
306
292
  test "values and keys alone"
307
293
  m: Map[Int, Int] := Map.empty()
308
294
  m.set(1, 5)
309
295
  m.set(2, 7)
310
- a := 0
311
- for v := range m.values()
296
+ vs := m.values()
312
- a = a + v
313
- b := 0
314
- for k := range m.keys()
297
+ ks := m.keys()
315
- b = b + k
316
- assert a == 12
298
+ assert 0.until(vs.length()).fold(0, |acc, i| acc + vs.at(i)) == 12
317
- assert b == 3
299
+ assert 0.until(ks.length()).fold(0, |acc, i| acc + ks.at(i)) == 3
318
-
300
+
319
- test "map entries: break stops the whole walk, an if filters"
301
+ test "map entries: an if filters, find stops at the first hit"
320
302
  m: Map[Int, Int] := Map.empty()
321
- i := 0
322
- while i < 30
303
+ for i := range 30
323
304
  m.set(i, i)
324
- i = i + 1
325
- n := 0
326
- for e := range m.entries()
305
+ es := m.entries()
306
+ n := 0.until(es.length()).fold(0, |acc, i|
327
- if e.second % 2 == 0
307
+ if es.at(i).second % 2 == 0
328
- n = n + 1
308
+ acc + 1
309
+ else
310
+ acc
311
+ )
329
312
  assert n == 15
330
- stopped := 0
331
- for e := range m.entries()
313
+ visited := Array.filled(1, 0)
314
+ hit := 0.until(es.length()).find(|i|
332
- stopped = stopped + 1
315
+ visited.set(0, visited.get(0) + 1)
333
- if stopped == 4
316
+ visited.get(0) == 4
317
+ )
334
- break
318
+ assert hit.unwrapOr(-1) == 3
335
- assert stopped == 4
319
+ assert visited.get(0) == 4
336
320
 
337
321
  test "empty map iterates zero times"
338
322
  m: Map[Str, Int] := Map.empty()
339
- n := 0
340
- for e := range m.entries()
341
- n = n + 1
342
- assert n == 0
323
+ assert m.entries().length() == 0
343
324
 
344
325
  test "init_infers_kv_from_pairs: K and V come from the pairs"
345
326
  m := ["a" => 1]
@@ -399,63 +380,54 @@ test "init_negative_int_keys_and_duplicates"
399
380
 
400
381
  test "100k inserts, every key found, 100k missing keys absent"
401
382
  m: Map[Int, Int] := Map.empty()
402
- i := 0
403
- while i < 100000
383
+ for i := range 100000
404
384
  m.set(i, i * 2)
405
- i = i + 1
406
385
  assert m.length() == 100000
407
- i = 0
408
- bad := 0
409
- while i < 100000
386
+ bad := 0.until(100000).fold(0, |acc, i|
410
387
  if m.get(i)! != i * 2
411
- bad = bad + 1
412
- i = i + 1
388
+ acc + 1
389
+ else
390
+ acc
391
+ )
413
392
  assert bad == 0
414
- i = 100000
415
- found := 0
416
- while i < 200000
393
+ found := 100000.until(200000).fold(0, |acc, i|
417
394
  if m.has(i)
418
- found = found + 1
419
- i = i + 1
395
+ acc + 1
396
+ else
397
+ acc
398
+ )
420
399
  assert found == 0
421
400
 
422
401
  test "delete half, reinsert, tombstones are reused and lookups stay right"
423
402
  m: Map[Int, Int] := Map.empty()
424
- i := 0
425
- while i < 20000
403
+ for i := range 20000
426
404
  m.set(i, i)
427
- i = i + 1
428
- i = 0
429
- while i < 20000
405
+ for i := range 10000
430
- m.remove(i)
406
+ m.remove(i * 2)
431
- i = i + 2
432
407
  assert m.length() == 10000
433
- i = 0
434
- bad := 0
435
- while i < 20000
408
+ bad := 0.until(20000).fold(0, |acc, i|
436
409
  if m.has(i) != {i % 2 == 1}
437
- bad = bad + 1
438
- i = i + 1
410
+ acc + 1
411
+ else
412
+ acc
413
+ )
439
414
  assert bad == 0
440
- i = 0
441
- while i < 20000
415
+ for i := range 10000
442
- m.set(i, i + 1)
416
+ m.set(i * 2, i * 2 + 1)
443
- i = i + 2
444
417
  assert m.length() == 20000
445
- i = 0
446
- while i < 20000
418
+ bad2 := 0.until(20000).fold(0, |acc, i|
447
419
  if m.get(i)! != {if i % 2 == 0 then i + 1 else i}
448
- bad = bad + 1
449
- i = i + 1
420
+ acc + 1
421
+ else
422
+ acc
423
+ )
450
- assert bad == 0
424
+ assert bad2 == 0
451
425
 
452
426
  test "repeated set/remove of a few keys never grows the table without bound"
453
427
  m: Map[Int, Int] := Map.empty()
454
- i := 0
455
- while i < 100000
428
+ for i := range 100000
456
429
  m.set(i % 7, i)
457
430
  m.remove(i % 7)
458
- i = i + 1
459
431
  assert m.length() == 0
460
432
  m.set(3, 9)
461
433
  assert m.get(3)! == 9
@@ -464,22 +436,18 @@ test "repeated set/remove of a few keys never grows the table without bound"
464
436
  test "growth past several doublings"
465
437
  m: Map[Int, Int] := Map.empty()
466
438
  assert m.index.length() == 16
467
- i := 0
468
- while i < 1000
439
+ for i := range 1000
469
440
  m.set(i, i)
470
- i = i + 1
471
441
  assert m.index.length() == 2048
472
442
  assert m.length() == 1000
473
443
 
474
444
  test "Map[Str, Int] with Buffer-built keys"
475
445
  m: Map[Str, Int] := Map.empty()
476
- i := 0
477
- while i < 2000
446
+ for i := range 2000
478
447
  b := Buffer()
479
448
  b.write("k")
480
449
  b.write(i.toStr())
481
450
  m.set(b.toStr(), i)
482
- i = i + 1
483
451
  assert m.length() == 2000
484
452
  assert m.get("k1999")! == 1999
485
453
  assert m.has("k2000") == false
@@ -492,17 +460,14 @@ test "iteration is insertion order, skipping removed entries"
492
460
  m.set(10, 4)
493
461
  m.remove(30)
494
462
  m.set(30, 5)
495
- order := ""
496
- for e := range m.entries()
463
+ es := m.entries()
497
- order = "{order}{e.first}={e.second} "
464
+ order := 0.until(es.length()).fold("", |acc, i| "{acc}{es.at(i).first}={es.at(i).second} ")
498
465
  assert order == "10=4 20=3 30=5 "
499
466
 
500
467
  test "clear then reuse"
501
468
  m: Map[Int, Int] := Map.empty()
502
- i := 0
503
- while i < 100
469
+ for i := range 100
504
470
  m.set(i, i)
505
- i = i + 1
506
471
  m.clear()
507
472
  assert m.length() == 0
508
473
  assert m.has(5) == false
std/Random.plum CHANGED
@@ -26,38 +26,35 @@ struct Random(seed: Int) =
26
26
 
27
27
  # 64 well-mixed bits (may be negative) and the advanced generator.
28
28
  fun nextInt(self) -> Rolled[Int] =
29
- x := self.seed
30
- if x == 0
31
- x = 88172645463325252
29
+ start := if self.seed == 0 then 88172645463325252 else self.seed
32
- x = x ^ { {x >> 12} & 0xFFFFFFFFFFFFF }
30
+ a := start ^ { {start >> 12} & 0xFFFFFFFFFFFFF }
33
- x = x ^ { x << 25 }
31
+ b := a ^ { a << 25 }
34
- x = x ^ { {x >> 27} & 0x1FFFFFFFFF }
32
+ x := b ^ { {b >> 27} & 0x1FFFFFFFFF }
35
- return Rolled(value: x * 2685821657736338717, rng: Random(seed: x))
33
+ Rolled(value: x * 2685821657736338717, rng: Random(seed: x))
36
34
 
37
35
  # A uniformly distributed Int in [0, n). Returns 0 for n <= 0 (generator unchanged).
38
36
  fun nextIntBelow(self, n: Int) -> Rolled[Int] =
39
37
  if n <= 0
40
- return Rolled(value: 0, rng: self)
38
+ Rolled(value: 0, rng: self)
39
+ else
41
- d := self.nextInt()
40
+ d := self.nextInt()
42
- return Rolled(value: { d.value & 0x7FFFFFFFFFFFFFFF } % n, rng: d.rng)
41
+ Rolled(value: { d.value & 0x7FFFFFFFFFFFFFFF } % n, rng: d.rng)
43
42
 
44
43
  # A uniformly distributed Float in [0.0, 1.0) with 53 bits of precision.
45
44
  fun nextFloat(self) -> Rolled[Float] =
46
45
  d := self.nextInt()
47
46
  bits := {d.value >> 11} & 0x1FFFFFFFFFFFFF
48
- return Rolled(value: Float(bits) / 9007199254740992.0, rng: d.rng)
47
+ Rolled(value: Float(bits) / 9007199254740992.0, rng: d.rng)
49
48
 
50
49
  test "same_seed_same_sequence"
51
50
  a := Random.seeded(12345)
52
51
  b := Random.seeded(12345)
53
- i := 0
52
+ _ := 1.to(100).fold(Rolled[Random](value: a, rng: b), |pair, _|
54
- while i < 100
53
+ da := pair.value.nextInt()
55
- da := a.nextInt()
54
+ db := pair.rng.nextInt()
56
- db := b.nextInt()
57
55
  assert da.value == db.value
58
- a = da.rng
56
+ Rolled[Random](value: da.rng, rng: db.rng)
59
- b = db.rng
60
- i = i + 1
57
+ )
61
58
 
62
59
  test "different seeds diverge and the stream is not constant"
63
60
  a := Random.seeded(1).nextInt()
@@ -71,32 +68,24 @@ test "drawing does not change the receiver"
71
68
  assert r.nextInt().value == r.nextInt().value
72
69
 
73
70
  test "nextIntBelow stays in range and covers the range"
74
- r := Random.seeded(99)
71
+ end := 1.to(1000).fold(Rolled[Int](value: 0, rng: Random.seeded(99)), |state, _|
75
- seen := 0
76
- i := 0
77
- while i < 1000
78
- d := r.nextIntBelow(10)
72
+ d := state.rng.nextIntBelow(10)
79
- r = d.rng
80
73
  assert d.value >= 0
81
74
  assert d.value < 10
82
- seen = seen | {1 << d.value}
75
+ Rolled[Int](value: state.value | {1 << d.value}, rng: d.rng)
83
- i = i + 1
76
+ )
84
- assert seen == 1023
77
+ assert end.value == 1023
85
- assert r.nextIntBelow(0).value == 0
78
+ assert end.rng.nextIntBelow(0).value == 0
86
79
 
87
80
  test "nextFloat is in [0, 1) with a sane mean"
88
- r := Random.seeded(5)
81
+ end := 1.to(1000).fold(Rolled[Float](value: 0.0, rng: Random.seeded(5)), |state, _|
89
- total := 0.0
90
- i := 0
91
- while i < 1000
92
- d := r.nextFloat()
82
+ d := state.rng.nextFloat()
93
- r = d.rng
94
83
  assert d.value >= 0.0
95
84
  assert d.value < 1.0
96
- total = total + d.value
85
+ Rolled[Float](value: state.value + d.value, rng: d.rng)
97
- i = i + 1
86
+ )
98
- assert total > 400.0
87
+ assert end.value > 400.0
99
- assert total < 600.0
88
+ assert end.value < 600.0
100
89
 
101
90
  test "seed 0 still produces a varying stream"
102
91
  d := Random.seeded(0).nextInt()
std/Slice.plum CHANGED
@@ -28,16 +28,18 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
28
28
  # gets the element at i'th index of the list
29
29
  fun get(self, i: Int) -> Option[T] =
30
30
  if i < 0 || i >= self.size
31
- return None
31
+ None
32
+ else
32
- Some(self.data.get(self.start + i))
33
+ Some(self.data.get(self.start + i))
33
34
 
34
35
  # sets the element at i'th index of the list, returning the old value (or None if i is out of bounds)
35
36
  fun set(self, i: Int, v: T) -> Option[T] =
36
37
  if i < 0 || i >= self.size
37
- return None
38
+ None
39
+ else
38
- old := self.data.get(self.start + i)
40
+ old := self.data.get(self.start + i)
39
- self.data.set(self.start + i, v)
41
+ self.data.set(self.start + i, v)
40
- Some(old)
42
+ Some(old)
41
43
 
42
44
  # the element at index i, unchecked (the `for x := range list` protocol; i must be in range)
43
45
  fun at(self, i: Int) -> T =
@@ -45,10 +47,8 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
45
47
 
46
48
  # Rewrites every slot with `f(old)` and returns the same list (no new list).
47
49
  fun mapInPlace(self, f: fn(T) -> T) -> Slice[T] =
48
- i := 0
49
- while i < self.size
50
+ for i := range self.size
50
51
  self.data.set(self.start + i, f(self.data.get(self.start + i)))
51
- i = i + 1
52
52
  self
53
53
 
54
54
  # Moves the element at index i out (i must be in range); pair it with `putAt`
@@ -68,14 +68,16 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
68
68
  # `libs/std/testing.plum` for what that means when `T` is a class/enum
69
69
  # without its own `equals` (reference identity, not structural equality).
70
70
  fun equals(self, other: Slice[T]) -> Bool =
71
- if self.length() != other.length()
71
+ self.length() == other.length() && self.sameFrom(other, 0)
72
+
73
+ # Whether `self` and `other` (same length) agree from index `i` on.
72
- return false
74
+ fun sameFrom(self, other: Slice[T], i: Int) -> Bool =
73
- i := 0
74
- while i < self.length()
75
+ if i >= self.size
76
+ true
75
- if self.data.get(self.start + i) != other.data.get(other.start + i)
77
+ else if self.data.get(self.start + i) != other.data.get(other.start + i)
76
- return false
78
+ false
79
+ else
77
- i = i + 1
80
+ self.sameFrom(other, i + 1)
78
- return true
79
81
 
80
82
  # appends `v` to the end of the list, doubling the capacity when full
81
83
  fun push(self, v: T) -> Unit =
@@ -91,10 +93,8 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
91
93
  self.data = self.data.resize(n)
92
94
  else
93
95
  fresh := Array[T]().resize(n)
94
- i := 0
95
- while i < self.size
96
+ for i := range self.size
96
97
  fresh.set(i, self.data.get(self.start + i))
97
- i = i + 1
98
98
  self.data = fresh
99
99
  self.start = 0
100
100
  self.cap = n
@@ -105,7 +105,7 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
105
105
  fun slice(self, i: Int, j: Int) -> Slice[T] =
106
106
  s := if i < 0 then 0 else if i > self.size then self.size else i
107
107
  e := if j > self.size then self.size else if j < s then s else j
108
- return Slice(data: self.data, start: self.start + s, size: e - s, cap: e - s)
108
+ Slice(data: self.data, start: self.start + s, size: e - s, cap: e - s)
109
109
 
110
110
  # adds every element of `values` to the end of the list
111
111
  fun add(self, values: Slice[T]) =
@@ -115,28 +115,32 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
115
115
  # removes and returns the last element, or None if empty
116
116
  fun pop(self) -> Option[T] =
117
117
  if self.size == 0
118
- return None
118
+ None
119
+ else
119
- self.size = self.size - 1
120
+ self.size = self.size - 1
120
- Some(self.data.get(self.start + self.size))
121
+ Some(self.data.get(self.start + self.size))
121
122
 
122
123
  # removes the element at i'th index of the list (out of range is a no-op)
123
124
  fun removeAt(self, i: Int) =
124
- if i < 0 || i >= self.size
125
+ if i >= 0 && i < self.size
125
- return
126
- j := i
127
- while j < self.size - 1
126
+ for j := range i.until(self.size - 1)
128
- self.data.set(self.start + j, self.data.get(self.start + j + 1))
127
+ self.data.set(self.start + j, self.data.get(self.start + j + 1))
129
- j = j + 1
130
- self.size = self.size - 1
128
+ self.size = self.size - 1
131
129
 
132
130
  # removes the first element equal to v from list
133
131
  fun remove(self, v: T) =
132
+ i := self.indexFrom(v, 0)
134
- i := 0
133
+ if i >= 0
135
- while i < self.size
136
- if self.data.get(self.start + i) == v
137
- self.removeAt(i)
134
+ self.removeAt(i)
135
+
136
+ # The index of the first element equal to `v` at or after index `i`, or -1.
137
+ fun indexFrom(self, v: T, i: Int) -> Int =
138
+ if i >= self.size
139
+ -1
140
+ else if self.data.get(self.start + i) == v
141
+ i
138
- return
142
+ else
139
- i = i + 1
143
+ self.indexFrom(v, i + 1)
140
144
 
141
145
  # removes all objects from this list
142
146
  fun clear(self) =
@@ -144,68 +148,65 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
144
148
 
145
149
  # reverses the list in place, returning it.
146
150
  fun reverse(self) -> Slice[T] =
147
- i := 0
148
- j := self.size - 1
151
+ self.swapInwards(0, self.size - 1)
152
+ self
153
+
154
+ # Swaps `i` and `j`, then the pair inside them, until the indexes meet.
155
+ fun swapInwards(self, i: Int, j: Int) -> Unit =
149
- while i < j
156
+ if i < j
150
157
  tmp := self.data.get(self.start + i)
151
158
  self.data.set(self.start + i, self.data.get(self.start + j))
152
159
  self.data.set(self.start + j, tmp)
153
- i = i + 1
154
- j = j - 1
160
+ self.swapInwards(i + 1, j - 1)
155
- self
156
161
 
157
162
  # Returns a NEW list with `self`'s elements sorted, using `before(a, b)` as
158
163
  # the "does a belong before b" comparator. Insertion sort (O(n^2)).
159
164
  fun sort(self, before: fn(T, T) -> Bool) -> Slice[T] =
160
165
  result := self.sublist(0, self.size)
161
- i := 1
162
- while i < result.size
166
+ for i := range 1.until(result.size)
163
- x := result.data.get(result.start + i)
167
+ result.insertBefore(result.data.get(result.start + i), i - 1, before)
164
- j := i - 1
165
- while j >= 0
168
+ result
169
+
170
+ # Insertion step of `sort`: shifts elements at or below index `j` that `x`
171
+ # belongs before one slot up, then puts `x` in the gap.
172
+ fun insertBefore(self, x: T, j: Int, before: fn(T, T) -> Bool) -> Unit =
166
- if !before(x, result.data.get(result.start + j))
173
+ if j >= 0 && before(x, self.data.get(self.start + j))
167
- break
168
- result.data.set(result.start + j + 1, result.data.get(result.start + j))
174
+ self.data.set(self.start + j + 1, self.data.get(self.start + j))
169
- j = j - 1
175
+ self.insertBefore(x, j - 1, before)
176
+ else
170
- result.data.set(result.start + j + 1, x)
177
+ self.data.set(self.start + j + 1, x)
171
- i = i + 1
172
- return result
173
178
 
174
179
  # Returns the first element equal to `search`, or None.
175
180
  fun findValue(self, search: T) -> Option[T] =
176
- i := 0
181
+ i := self.indexFrom(search, 0)
177
- while i < self.size
182
+ if i < 0
183
+ None
184
+ else
178
- value := self.data.get(self.start + i)
185
+ Some(self.data.get(self.start + i))
179
- if value == search
180
- return Some(value)
181
- i = i + 1
182
- return None
183
186
 
184
187
  fun contains(self, v: T) -> Bool =
185
- i := 0
186
- while i < self.size
187
- if self.data.get(self.start + i) == v
188
+ self.indexFrom(v, 0) >= 0
188
- return true
189
- i = i + 1
190
- return false
191
189
 
192
190
  # returns the first element in the list
193
191
  fun first(self) -> Option[T] =
194
192
  if self.size == 0
195
- return None
193
+ None
194
+ else
196
- Some(self.data.get(self.start + 0))
195
+ Some(self.data.get(self.start + 0))
197
196
 
198
197
  # the first element, or None when the list is empty (the typed tail of `find`)
199
198
  fun head(self) -> Option[T] =
200
199
  if self.size == 0
201
- return None
200
+ None
201
+ else
202
- return Some(self.data.get(self.start + 0))
202
+ Some(self.data.get(self.start + 0))
203
203
 
204
204
  # returns the last element in the list
205
205
  fun last(self) -> Option[T] =
206
206
  if self.size == 0
207
- return None
207
+ None
208
+ else
208
- Some(self.data.get(self.start + self.size - 1))
209
+ Some(self.data.get(self.start + self.size - 1))
209
210
 
210
211
  # Returns a new list of the elements at index `[start, end)`, clamped into
211
212
  # range (a `start`/`end` outside `[0, length]` is clamped, not an error).
@@ -213,51 +214,44 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
213
214
  result := Slice[T]()
214
215
  s := if start < 0 then 0 else start
215
216
  e := if end > self.size then self.size else end
216
- i := s
217
- while i < e
217
+ for i := range s.until(e)
218
218
  result.push(self.data.get(self.start + i))
219
- i = i + 1
220
- return result
219
+ result
221
220
 
222
221
  # Every element AFTER the first `n` (a copy; `xs.skip(n)` in a `for` is the lazy form).
223
222
  fun drop(self, n: Int) -> Slice[T] =
224
- return self.sublist(n, self.size)
223
+ self.sublist(n, self.size)
225
224
 
226
225
  # Returns one uniformly random element and the advanced generator, or None
227
226
  # if `self` is empty.
228
227
  fun sample(self, rng: Random) -> Option[Rolled[T]] =
229
228
  if self.size == 0
230
- return None
229
+ None
230
+ else
231
- d := rng.nextIntBelow(self.size)
231
+ d := rng.nextIntBelow(self.size)
232
- return Some(Rolled(value: self.data.get(self.start + d.value), rng: d.rng))
232
+ Some(Rolled(value: self.data.get(self.start + d.value), rng: d.rng))
233
233
 
234
234
  # Returns a new list with `self`'s elements in random order (Fisher-Yates) and the
235
235
  # advanced generator.
236
236
  fun shuffle(self, rng: Random) -> Rolled[Slice[T]] =
237
237
  result := self.sublist(0, self.size)
238
- r := rng
239
- i := result.size - 1
238
+ final := {result.size - 1}.downTo(1).fold(rng, |gen, i|
240
- while i > 0
241
- d := r.nextIntBelow(i + 1)
239
+ d := gen.nextIntBelow(i + 1)
242
- r = d.rng
243
240
  j := d.value
244
241
  vi := result.data.get(result.start + i)
245
242
  result.data.set(result.start + i, result.data.get(result.start + j))
246
243
  result.data.set(result.start + j, vi)
247
- i = i - 1
244
+ d.rng
245
+ )
248
- return Rolled(value: result, rng: r)
246
+ Rolled(value: result, rng: final)
249
247
 
250
248
  # Splits into consecutive sublists of at most `size` elements each.
251
249
  fun chunk(self, size: Int) -> Slice[Slice[T]] =
252
250
  result := Slice[Slice[T]]()
253
- if size <= 0
251
+ if size > 0
254
- return result
255
- i := 0
256
- n := self.length()
252
+ for i := range Range(start: 0, stop: self.length(), step: size)
257
- while i < n
258
- result.push(self.sublist(i, i + size))
253
+ result.push(self.sublist(i, i + size))
259
- i = i + size
260
- return result
254
+ result
261
255
 
262
256
  # Grouping by an arbitrary key type would need `Map[K, Slice[T]]`, but
263
257
  # `Map.plum` depends on this file. Not implemented.
@@ -266,16 +260,14 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
266
260
 
267
261
  fun join(self, sep: Str = ",") -> Str =
268
262
  res := Buffer()
269
- i := 0
270
- while i < self.size
263
+ for i := range self.size
271
264
  if i > 0
272
265
  res.write(sep)
273
266
  res.write(self.data.get(self.start + i).toStr())
274
- i = i + 1
275
267
  res.toStr()
276
268
 
277
269
  fun toStr(self) -> Str =
278
- return "[" + self.join(",") + "]"
270
+ "[" + self.join(",") + "]"
279
271
 
280
272
  # ---- regression tests ----
281
273
 
@@ -313,10 +305,8 @@ test "removing every node in a loop leaves an empty correctly functioning list"
313
305
  l.push(8)
314
306
  l.push(9)
315
307
  l.push(10)
316
- i := 0
317
- while i < 10
308
+ for _ := range 10
318
309
  l.removeAt(0)
319
- i = i + 1
320
310
  assert l.length() == 0
321
311
  assert l.get(0).unwrapOr(-1000) == -1000
322
312
  l.add(Slice[Int]())
@@ -399,10 +389,8 @@ test "chunk splits into sublists of at most size elements each"
399
389
 
400
390
  test "list_get_set_push_pop: push 1000, get(999), pop until empty, get on empty is an error"
401
391
  l := Slice[Int]()
402
- i := 0
403
- while i < 1000
392
+ for i := range 1000
404
393
  l.push(i)
405
- i = i + 1
406
394
  assert l.length() == 1000
407
395
  assert l.get(999)! == 999
408
396
  assert l.get(1000).unwrapOr(-1000) == -1000
@@ -410,7 +398,7 @@ test "list_get_set_push_pop: push 1000, get(999), pop until empty, get on empty
410
398
  assert l.get(500)! == 7
411
399
  assert l.pop()! == 999
412
400
  assert l.length() == 999
413
- while l.length() > 0
401
+ for _ := range 999
414
402
  _ := l.pop()!
415
403
  assert l.length() == 0
416
404
  assert l.pop().unwrapOr(-1) == -1
@@ -420,33 +408,27 @@ test "list_get_set_push_pop: push 1000, get(999), pop until empty, get on empty
420
408
 
421
409
  test "list_growth: length stays exact across the doubling boundaries"
422
410
  l := Slice[Int]()
423
- i := 0
424
- while i < 1025
411
+ for i := range 1025
425
412
  l.push(i)
426
413
  n := i + 1
427
414
  if n == 15 || n == 16 || n == 17 || n == 1023 || n == 1024 || n == 1025
428
415
  assert l.length() == n
429
416
  assert l.get(n - 1)! == i
430
417
  assert l.get(0)! == 0
431
- i = i + 1
432
418
  assert l.get(16)! == 16
433
419
  assert l.get(1024)! == 1024
434
420
 
435
421
  test "list of strings keeps its elements through growth"
436
422
  l := Slice[Str]()
437
- i := 0
438
- while i < 40
423
+ for i := range 40
439
424
  l.push("s{i}")
440
- i = i + 1
441
425
  assert l.get(39)! == "s39"
442
426
  assert l.get(16)! == "s16"
443
427
 
444
428
  test "Slice[Float] push/get round-trips"
445
429
  l := Slice[Float]()
446
- i := 0
447
- while i < 1000
430
+ for i := range 1000
448
431
  l.push(Float(i) + 0.5)
449
- i = i + 1
450
432
  assert l.length() == 1000
451
433
  assert l.get(999)! == 999.5
452
434
 
@@ -521,9 +503,7 @@ test "every method indexes from the view's start"
521
503
  assert v.drop(2).toStr() == "[3,7]"
522
504
  assert v.chunk(3).length() == 2
523
505
  assert v.join("-") == "1-5-3-7"
524
- total := 0
525
- for x := range v
526
- total = total + x
506
+ total := 0.until(v.length()).fold(0, |sum, i| sum + v.at(i))
527
507
  assert total == 16
528
508
  assert v.pop()! == 7
529
509
  assert v.length() == 3
std/Str.plum CHANGED
@@ -36,12 +36,14 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
36
36
  # (ordinary 64-bit multiplication), which is fine — only the bit pattern
37
37
  # matters, not the numeric value itself.
38
38
  fun hash(self) -> Int =
39
- h := -0x340d631b7bdddcdb # FNV offset basis 0xcbf29ce484222325 as a signed Int
39
+ # FNV offset basis 0xcbf29ce484222325 as a signed Int
40
- i := 0
40
+ hashFrom(self, 0, -0x340d631b7bdddcdb)
41
+
42
+ fun hashFrom(s: Str, i: Int, h: Int) -> Int =
41
- while i < self.length()
43
+ if i >= s.length()
44
+ h
45
+ else
42
- h = {h ^ self.byteAt(i)} * 0x100000001b3
46
+ hashFrom(s, i + 1, {h ^ s.byteAt(i)} * 0x100000001b3)
43
- i = i + 1
44
- return h
45
47
 
46
48
  # The single-character substring at index `i`. (Was declared to return a
47
49
  # `Char` type, but `Char` was never actually defined anywhere in `libs/std` —
@@ -70,12 +72,13 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
70
72
  fun codePointByteLength(self, i: Int) -> Int =
71
73
  b := self.byteAt(i)
72
74
  if b < 0x80
73
- return 1
75
+ 1
74
- if b & 0xE0 == 0xC0
76
+ else if b & 0xE0 == 0xC0
75
- return 2
77
+ 2
76
- if b & 0xF0 == 0xE0
78
+ else if b & 0xF0 == 0xE0
79
+ 3
77
- return 3
80
+ else
78
- return 4
81
+ 4
79
82
 
80
83
  # Decodes the single Unicode codepoint (as its raw integer value) starting
81
84
  # at byte index `i`.
@@ -83,52 +86,56 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
83
86
  n := self.codePointByteLength(i)
84
87
  b0 := self.byteAt(i)
85
88
  if n == 1
86
- return b0
89
+ b0
87
- b1 := self.byteAt(i + 1)
88
- if n == 2
90
+ else if n == 2
89
- return {b0 & 0x1F} << 6 | {b1 & 0x3F}
91
+ {b0 & 0x1F} << 6 | {self.byteAt(i + 1) & 0x3F}
90
- b2 := self.byteAt(i + 2)
91
- if n == 3
92
+ else if n == 3
92
- return {b0 & 0x0F} << 12 | {b1 & 0x3F} << 6 | {b2 & 0x3F}
93
+ {b0 & 0x0F} << 12 | {self.byteAt(i + 1) & 0x3F} << 6 | {self.byteAt(i + 2) & 0x3F}
93
- b3 := self.byteAt(i + 3)
94
+ else
94
- return {b0 & 0x07} << 18 | {b1 & 0x3F} << 12 | {b2 & 0x3F} << 6 | {b3 & 0x3F}
95
+ {b0 & 0x07} << 18 | {self.byteAt(i + 1) & 0x3F} << 12 | {self.byteAt(i + 2) & 0x3F} << 6 | {self.byteAt(i + 3) & 0x3F}
95
96
 
96
97
  # Number of Unicode CHARACTERS (codepoints) — as opposed to `length`,
97
98
  # which counts bytes and only agrees with this for pure-ASCII text.
98
99
  fun runeLength(self) -> Int =
100
+ runeCount(self, 0, 0)
101
+
102
+ fun runeCount(s: Str, i: Int, count: Int) -> Int =
99
- n := self.length()
103
+ if i >= s.length()
100
- i := 0
101
- count := 0
104
+ count
102
- while i < n
105
+ else
103
- i = i + self.codePointByteLength(i)
106
+ runeCount(s, i + s.codePointByteLength(i), count + 1)
104
- count = count + 1
105
- return count
106
107
 
107
108
  # The `charIndex`-th Unicode character, re-encoded as its own (1-4 byte)
108
109
  # `Str`. Unlike `get` (which indexes by BYTE and can split a character in
109
110
  # half), this always returns a complete character.
110
111
  fun runeAt(self, charIndex: Int) -> Str =
111
- i := 0
112
- k := charIndex
113
- while k > 0
114
- i = i + self.codePointByteLength(i)
112
+ i := runeStart(self, 0, charIndex)
115
- k = k - 1
116
- return self.sub(i, i + self.codePointByteLength(i))
113
+ self.sub(i, i + self.codePointByteLength(i))
114
+
115
+ # Byte index of the character `k` characters on from byte index `i`.
116
+ fun runeStart(s: Str, i: Int, k: Int) -> Int =
117
+ if k > 0
118
+ runeStart(s, i + s.codePointByteLength(i), k - 1)
119
+ else
120
+ i
117
121
 
118
122
  fun contains(self, search: Str) -> Bool =
119
123
  self.indexOf(search) >= 0
120
124
 
121
125
  fun indexOf(self, sub: Str) -> Int =
122
- n := self.length()
123
126
  m := sub.length()
124
127
  if m == 0
128
+ 0
125
- return 0
129
+ else
126
- i := 0
130
+ indexFrom(self, sub, 0, self.length() - m, m)
131
+
132
+ fun indexFrom(s: Str, sub: Str, i: Int, last: Int, m: Int) -> Int =
127
- while i <= n - m
133
+ if i > last
134
+ -1
128
- if matchesAt(self, sub, i, m)
135
+ else if matchesAt(s, sub, i, m)
136
+ i
129
- return i
137
+ else
130
- i = i + 1
138
+ indexFrom(s, sub, i + 1, last, m)
131
- return -1
132
139
 
133
140
  fun startsWith(self, search: Str) -> Bool =
134
141
  matchesAt(self, search, 0, search.length())
@@ -145,20 +152,22 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
145
152
  n := self.length()
146
153
  m := o.length()
147
154
  if m == 0
148
- return self
155
+ self
149
- if n == 0
156
+ else if n == 0
157
+ o
150
- return o
158
+ else
151
- out := Array[Byte]().resize(n + m)
159
+ out := Array[Byte]().resize(n + m)
152
- Array.copy(out, 0, self.data, self.start, n)
160
+ Array.copy(out, 0, self.data, self.start, n)
153
- Array.copy(out, n, o.data, o.start, m)
161
+ Array.copy(out, n, o.data, o.start, m)
154
- return Str(data: out, start: 0, len: n + m)
162
+ Str(data: out, start: 0, len: n + m)
155
163
 
156
164
  # `a == b` / `a != b`: CONTENT equality (never reference equality).
157
165
  fun eq(self, o: Str) -> Bool =
158
166
  n := self.length()
159
167
  if n != o.length()
160
- return false
168
+ false
169
+ else
161
- return Array.equal(self.data, self.start, o.data, o.start, n)
170
+ Array.equal(self.data, self.start, o.data, o.start, n)
162
171
 
163
172
  fun toStr(self) -> Str =
164
173
  self
@@ -168,67 +177,66 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
168
177
  # final length may overshoot `count` by up to `sub.length() - 1`.
169
178
  fun padStart(self, sub: Str, count: Int) -> Str =
170
179
  if self.length() >= count || sub.length() == 0
171
- return self
180
+ self
172
- buf := Buffer()
181
+ else
173
- need := count - self.length()
182
+ need := count - self.length()
174
- written := 0
175
- while written < need
176
- buf.write(sub)
177
- written = written + sub.length()
183
+ buf := writeRepeat(Buffer(), sub, {need + sub.length() - 1} / sub.length())
178
- buf.write(self)
184
+ buf.write(self)
179
- return buf.toStr()
185
+ buf.toStr()
180
186
 
181
187
  fun padEnd(self, sub: Str, count: Int) -> Str =
182
188
  if self.length() >= count || sub.length() == 0
183
- return self
189
+ self
190
+ else
184
- buf := Buffer()
191
+ buf := Buffer()
185
- buf.write(self)
192
+ buf.write(self)
186
- need := count - self.length()
193
+ need := count - self.length()
194
+ writeRepeat(buf, sub, {need + sub.length() - 1} / sub.length()).toStr()
195
+
196
+ # Writes `s` into `buf` `k` times (in place); returns `buf`.
197
+ fun writeRepeat(buf: Buffer, s: Str, k: Int) -> Buffer =
187
- written := 0
198
+ if k <= 0
199
+ buf
188
- while written < need
200
+ else
189
- buf.write(sub)
201
+ buf.write(s)
190
- written = written + sub.length()
202
+ writeRepeat(buf, s, k - 1)
191
- return buf.toStr()
192
203
 
193
204
  fun repeat(self, count: Int) -> Str =
194
205
  if count <= 0
195
- return ""
206
+ ""
196
- buf := Buffer()
197
- i := 0
207
+ else
198
- while i < count
199
- buf.write(self)
200
- i = i + 1
201
- return buf.toStr()
208
+ writeRepeat(Buffer(), self, count).toStr()
202
209
 
203
210
  # Replaces the FIRST occurrence of `old` with `new` (byte-exact). Returns
204
211
  # `self` if `old` doesn't occur.
205
212
  fun replace(self, old: Str, new: Str) -> Str =
206
213
  idx := self.indexOf(old)
207
214
  if idx < 0
208
- return self
215
+ self
216
+ else
209
- buf := Buffer()
217
+ buf := Buffer()
210
- buf.write(self.sub(0, idx))
218
+ buf.write(self.sub(0, idx))
211
- buf.write(new)
219
+ buf.write(new)
212
- buf.write(self.sub(idx + old.length(), self.length()))
220
+ buf.write(self.sub(idx + old.length(), self.length()))
213
- return buf.toStr()
221
+ buf.toStr()
214
222
 
215
223
  # Replaces every non-overlapping occurrence of `old`, scanning left to
216
224
  # right. An empty `old` returns `self` unchanged.
217
225
  fun replaceAll(self, old: Str, new: Str) -> Str =
218
- m := old.length()
226
+ if old.length() == 0
219
- if m == 0
220
- return self
227
+ self
228
+ else
229
+ replaceFrom(self, old, new, 0, Buffer())
230
+
231
+ fun replaceFrom(s: Str, old: Str, new: Str, i: Int, buf: Buffer) -> Str =
221
- n := self.length()
232
+ if i >= s.length()
222
- buf := Buffer()
233
+ buf.toStr()
223
- i := 0
224
- while i < n
225
- if matchesAt(self, old, i, m)
234
+ else if matchesAt(s, old, i, old.length())
226
- buf.write(new)
235
+ buf.write(new)
227
- i = i + m
236
+ replaceFrom(s, old, new, i + old.length(), buf)
228
- else
237
+ else
229
- buf.writeByte(Byte(self.byteAt(i)))
238
+ buf.writeByte(Byte(s.byteAt(i)))
230
- i = i + 1
231
- return buf.toStr()
239
+ replaceFrom(s, old, new, i + 1, buf)
232
240
 
233
241
  # Byte index of the first occurrence of `sub`, or -1 (same as `indexOf`).
234
242
  fun search(self, sub: Str) -> Int =
@@ -240,7 +248,7 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
240
248
  len := self.length()
241
249
  s := if start < 0 then len + start else start
242
250
  en := if e < 0 then len + e else e
243
- return self.sub(s, en)
251
+ self.sub(s, en)
244
252
 
245
253
  # Splits on every occurrence of `separator` (byte-exact, not regex).
246
254
  # `limit <= 0` means unlimited; `limit > 0` caps the RESULT COUNT at
@@ -249,29 +257,28 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
249
257
  # past the limit). An empty `separator` splits into individual bytes.
250
258
  fun split(self, separator: Str, limit: Int) -> Slice[Str] =
251
259
  result := Slice[Str]()
252
- len := self.length()
253
- sep_len := separator.length()
260
+ if separator.length() == 0
254
- if sep_len == 0
255
- j := 0
256
- while j < len
257
- result.push(self.get(j))
258
- j = j + 1
259
- return result
260
- start := 0
261
- i := 0
262
- count := 1
263
- while i <= len - sep_len
264
- if limit > 0 && count >= limit
265
- break
266
- if matchesAt(self, separator, i, sep_len)
267
- result.push(self.sub(start, i))
261
+ splitBytes(self, result, 0)
268
- start = i + sep_len
269
- i = start
270
- count = count + 1
271
- else
262
+ else
263
+ splitFrom(self, separator, limit, result, 0, 0, 1)
264
+
265
+ fun splitBytes(s: Str, result: Slice[Str], j: Int) -> Slice[Str] =
272
- i = i + 1
266
+ if j >= s.length()
267
+ result
268
+ else
269
+ result.push(s.get(j))
270
+ splitBytes(s, result, j + 1)
271
+
272
+ fun splitFrom(s: Str, sep: Str, limit: Int, result: Slice[Str], start: Int, i: Int, count: Int) -> Slice[Str] =
273
+ sep_len := sep.length()
274
+ if i > s.length() - sep_len || {limit > 0 && count >= limit}
275
+ result.push(s.sub(start, s.length()))
276
+ result
277
+ else if matchesAt(s, sep, i, sep_len)
273
- result.push(self.sub(start, len))
278
+ result.push(s.sub(start, i))
279
+ splitFrom(s, sep, limit, result, i + sep_len, i + sep_len, count + 1)
274
- return result
280
+ else
281
+ splitFrom(s, sep, limit, result, start, i + 1, count)
275
282
 
276
283
  # Plain substring, `start`/`e` clamped into `[0, length]`; `e` is exclusive.
277
284
  # Unlike `slice`, negative indices are just clamped to 0, not counted from
@@ -281,8 +288,9 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
281
288
  s := if start < 0 then 0 else start
282
289
  en := if e > len then len else e
283
290
  if s >= en
284
- return ""
291
+ ""
292
+ else
285
- return Str(data: self.data, start: self.start + s, len: en - s)
293
+ Str(data: self.data, start: self.start + s, len: en - s)
286
294
 
287
295
  fun toLower(self) -> Str =
288
296
  mapCase(self, false)
@@ -292,15 +300,16 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
292
300
  # along with the string's, corrupting any non-ASCII text.
293
301
  fun reverse(self) -> Str =
294
302
  n := self.length()
295
- out := Array[Byte]().resize(n)
303
+ reverseFrom(self, Array[Byte]().resize(n), n, 0)
304
+
296
- i := 0
305
+ fun reverseFrom(s: Str, out: Array[Byte], n: Int, i: Int) -> Str =
297
- while i < n
306
+ if i >= n
307
+ Str(data: out, start: 0, len: n)
308
+ else
298
- cl := self.codePointByteLength(i)
309
+ full := s.codePointByteLength(i)
299
- if i + cl > n
310
+ cl := if i + full > n then n - i else full
300
- cl = n - i
301
- Array.copy(out, n - i - cl, self.data, self.start + i, cl)
311
+ Array.copy(out, n - i - cl, s.data, s.start + i, cl)
302
- i = i + cl
303
- return Str(data: out, start: 0, len: n)
312
+ reverseFrom(s, out, n, i + cl)
304
313
 
305
314
  fun camelCase(self) -> Str =
306
315
  caseConvert(self, "", 2)
@@ -310,8 +319,9 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
310
319
 
311
320
  fun capitalize(self) -> Str =
312
321
  if self.length() == 0
313
- return self
322
+ self
323
+ else
314
- return self.get(0).upperCase() + self.sub(1, self.length()).toLower()
324
+ self.get(0).upperCase() + self.sub(1, self.length()).toLower()
315
325
 
316
326
  fun kebabCase(self) -> Str =
317
327
  caseConvert(self, "-", 1)
@@ -321,16 +331,18 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
321
331
 
322
332
  fun lowerFirst(self) -> Str =
323
333
  if self.length() == 0
324
- return self
334
+ self
335
+ else
325
- return self.get(0).toLower() + self.sub(1, self.length())
336
+ self.get(0).toLower() + self.sub(1, self.length())
326
337
 
327
338
  fun upperCase(self) -> Str =
328
339
  mapCase(self, true)
329
340
 
330
341
  fun upperFirst(self) -> Str =
331
342
  if self.length() == 0
332
- return self
343
+ self
344
+ else
333
- return self.get(0).upperCase() + self.sub(1, self.length())
345
+ self.get(0).upperCase() + self.sub(1, self.length())
334
346
 
335
347
  fun startCase(self) -> Str =
336
348
  caseConvert(self, " ", 4)
@@ -340,32 +352,28 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
340
352
  # characters (including `×`/`÷` and everything outside U+00C0..U+017F)
341
353
  # pass through unchanged. Compact table, not exhaustive Unicode.
342
354
  fun deburr(self) -> Str =
355
+ deburrFrom(self, deburrLatin1(), deburrLatinExtA(), Buffer(), 0)
356
+
357
+ fun deburrFrom(s: Str, t1: Str, t2: Str, buf: Buffer, i: Int) -> Str =
343
- n := self.length()
358
+ if i >= s.length()
344
- t1 := deburrLatin1()
345
- t2 := deburrLatinExtA()
346
- buf := Buffer()
359
+ buf.toStr()
347
- i := 0
360
+ else
348
- while i < n
349
- cl := self.codePointByteLength(i)
361
+ cl := s.codePointByteLength(i)
350
362
  if cl == 1
351
- buf.writeByte(Byte(self.byteAt(i)))
363
+ buf.writeByte(Byte(s.byteAt(i)))
352
364
  else
353
- cp := self.codePointAt(i)
365
+ cp := s.codePointAt(i)
354
- idx := -1
355
- tbl := t1
356
- if cp >= 0xC0 && cp < 0x100
366
+ in1 := cp >= 0xC0 && cp < 0x100
357
- idx = {cp - 0xC0} * 2
358
- else if cp >= 0x100 && cp < 0x180
367
+ in2 := cp >= 0x100 && cp < 0x180
359
- idx = {cp - 0x100} * 2
368
+ tbl := if in2 then t2 else t1
360
- tbl = t2
369
+ idx := if in1 then {cp - 0xC0} * 2 else if in2 then {cp - 0x100} * 2 else -1
361
370
  if idx < 0 || tbl.byteAt(idx) == 35
362
- buf.write(self.sub(i, i + cl))
371
+ buf.write(s.sub(i, i + cl))
363
372
  else
364
373
  buf.writeByte(Byte(tbl.byteAt(idx)))
365
374
  if tbl.byteAt(idx + 1) != 32
366
375
  buf.writeByte(Byte(tbl.byteAt(idx + 1)))
367
- i = i + cl
368
- return buf.toStr()
376
+ deburrFrom(s, t1, t2, buf, i + cl)
369
377
 
370
378
  fun escape(self) -> Str =
371
379
  escapeHtml(self)
@@ -381,11 +389,12 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
381
389
  fun pad(self, sub: Str, count: Int) -> Str =
382
390
  len := self.length()
383
391
  if len >= count || sub.length() == 0
384
- return self
392
+ self
393
+ else
385
- total := count - len
394
+ total := count - len
386
- left := total / 2
395
+ left := total / 2
387
- right := total - left
396
+ right := total - left
388
- return self.padStart(sub, len + left).padEnd(sub, len + left + right)
397
+ self.padStart(sub, len + left).padEnd(sub, len + left + right)
389
398
 
390
399
  fun trim(self) -> Str =
391
400
  self.trimStart().trimEnd()
@@ -401,12 +410,13 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
401
410
  # `self` unchanged otherwise. `length` too small to fit the full "..."
402
411
  # itself just returns as many of its leading bytes as fit.
403
412
  fun truncate(self, length: Int) -> Str =
404
- if self.length() <= length
405
- return self
406
413
  omission := "..."
414
+ if self.length() <= length
415
+ self
407
- if length <= omission.length()
416
+ else if length <= omission.length()
408
- return omission.sub(0, length)
417
+ omission.sub(0, length)
418
+ else
409
- return self.sub(0, length - omission.length()) + omission
419
+ self.sub(0, length - omission.length()) + omission
410
420
 
411
421
  fun unescape(self) -> Str =
412
422
  unescapeHtml(self)
@@ -422,13 +432,13 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
422
432
  fun fromBytes(src: Array[Byte], start: Int, n: Int) -> Str =
423
433
  data := Array[Byte]().resize(n)
424
434
  Array.copy(data, 0, src, start, n)
425
- return Str(data: data, start: 0, len: n)
435
+ Str(data: data, start: 0, len: n)
426
436
 
427
437
  # A new 1-byte Str holding `b`'s low 8 bits, the counterpart to `byteAt`.
428
438
  fun byteToStr(b: Int) -> Str =
429
439
  out := Array[Byte]().resize(1)
430
440
  out.set(0, Byte(b))
431
- return Str(data: out, start: 0, len: 1)
441
+ Str(data: out, start: 0, len: 1)
432
442
 
433
443
  fun isAsciiUpper(b: Int) -> Bool =
434
444
  b >= 65 && b <= 90 # 'A'..'Z'
@@ -462,54 +472,51 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
462
472
  # caller can test candidate positions/lengths freely).
463
473
  fun matchesAt(s: Str, sub: Str, offset: Int, sub_len: Int) -> Bool =
464
474
  if offset < 0 || offset + sub_len > s.length()
465
- return false
475
+ false
466
- j := 0
476
+ else
477
+ matchBytes(s, sub, offset, 0, sub_len)
478
+
479
+ fun matchBytes(s: Str, sub: Str, offset: Int, j: Int, sub_len: Int) -> Bool =
467
- while j < sub_len
480
+ if j >= sub_len
481
+ true
468
- if s.byteAt(offset + j) != sub.byteAt(j)
482
+ else if s.byteAt(offset + j) != sub.byteAt(j)
469
- return false
483
+ false
470
- j = j + 1
471
- return true
484
+ else
485
+ matchBytes(s, sub, offset, j + 1, sub_len)
472
486
 
473
487
  # Encodes a single Unicode codepoint (its raw integer value) as its own
474
- # UTF-8 `Str` (1-4 bytes) — the reverse of `Str.codePointAt`. `b0`/`b1`/`b2`
488
+ # UTF-8 `Str` (1-4 bytes) — the reverse of `Str.codePointAt`.
475
- # are declared ONCE up front and reassigned per branch (rather than
476
- # redeclared with `:=` in each `if`) — `if` bodies share one flat scope with
477
- # the rest of the function here (there's no per-branch isolation), so a
478
- # second `:=` for the same name would be a compile error.
479
489
  fun codePointToStr(cp: Int) -> Str =
480
490
  if cp < 0x80
481
- return byteToStr(cp)
491
+ byteToStr(cp)
482
- b0 := 0xC0 | {cp >> 6}
483
- b1 := 0x80 | {cp & 0x3F}
484
- if cp < 0x800
492
+ else if cp < 0x800
485
- return byteToStr(b0) + byteToStr(b1)
486
- b0 = 0xE0 | {cp >> 12}
487
- b1 = 0x80 | {{cp >> 6} & 0x3F}
493
+ byteToStr(0xC0 | {cp >> 6}) + byteToStr(0x80 | {cp & 0x3F})
488
- b2 := 0x80 | {cp & 0x3F}
489
- if cp < 0x10000
494
+ else if cp < 0x10000
490
- return byteToStr(b0) + byteToStr(b1) + byteToStr(b2)
491
- b0 = 0xF0 | {cp >> 18}
492
- b1 = 0x80 | {{cp >> 12} & 0x3F}
493
- b2 = 0x80 | {{cp >> 6} & 0x3F}
494
- b3 := 0x80 | {cp & 0x3F}
495
- return byteToStr(b0) + byteToStr(b1) + byteToStr(b2) + byteToStr(b3)
495
+ byteToStr(0xE0 | {cp >> 12}) + byteToStr(0x80 | {{cp >> 6} & 0x3F}) + byteToStr(0x80 | {cp & 0x3F})
496
+ else
497
+ byteToStr(0xF0 | {cp >> 18}) + byteToStr(0x80 | {{cp >> 12} & 0x3F}) + byteToStr(0x80 | {{cp >> 6} & 0x3F}) + byteToStr(0x80 | {cp & 0x3F})
496
498
 
497
499
  fun isTrimByte(b: Int) -> Bool =
498
500
  b == 32 || b == 9 || b == 10 || b == 13
499
501
 
500
502
  fun trimStartIndex(s: Str) -> Int =
501
- n := s.length()
503
+ trimStartFrom(s, 0)
504
+
502
- i := 0
505
+ fun trimStartFrom(s: Str, i: Int) -> Int =
503
- while i < n && isTrimByte(s.byteAt(i))
506
+ if i < s.length() && isTrimByte(s.byteAt(i))
504
- i = i + 1
507
+ trimStartFrom(s, i + 1)
505
- return i
508
+ else
509
+ i
506
510
 
507
511
  # Exclusive end index of `s` with trailing whitespace dropped.
508
512
  fun trimEndIndex(s: Str) -> Int =
509
- n := s.length()
513
+ trimEndFrom(s, s.length())
514
+
515
+ fun trimEndFrom(s: Str, n: Int) -> Int =
510
- while n > 0 && isTrimByte(s.byteAt(n - 1))
516
+ if n > 0 && isTrimByte(s.byteAt(n - 1))
511
- n = n - 1
517
+ trimEndFrom(s, n - 1)
512
- return n
518
+ else
519
+ n
513
520
 
514
521
  fun htmlEntity(b: Int) -> Str =
515
522
  match b
@@ -521,68 +528,72 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
521
528
  _ => ""
522
529
 
523
530
  fun escapeHtml(s: Str) -> Str =
531
+ escapeHtmlFrom(s, Buffer(), 0)
532
+
533
+ fun escapeHtmlFrom(s: Str, buf: Buffer, i: Int) -> Str =
524
- n := s.length()
534
+ if i >= s.length()
525
- buf := Buffer()
535
+ buf.toStr()
526
- i := 0
536
+ else
527
- while i < n
528
537
  b := s.byteAt(i)
529
538
  ent := htmlEntity(b)
530
539
  if ent.length() == 0
531
540
  buf.writeByte(Byte(b))
532
541
  else
533
542
  buf.write(ent)
534
- i = i + 1
535
- return buf.toStr()
543
+ escapeHtmlFrom(s, buf, i + 1)
536
544
 
537
545
  fun isRegExpMetaByte(b: Int) -> Bool =
538
546
  b == 94 || b == 36 || b == 92 || b == 46 || b == 42 || b == 43 || b == 63
539
547
  || b == 40 || b == 41 || b == 91 || b == 93 || b == 123 || b == 125 || b == 124
540
548
 
541
549
  fun escapeRegExpStr(s: Str) -> Str =
550
+ escapeRegExpFrom(s, Buffer(), 0)
551
+
552
+ fun escapeRegExpFrom(s: Str, buf: Buffer, i: Int) -> Str =
542
- n := s.length()
553
+ if i >= s.length()
543
- buf := Buffer()
554
+ buf.toStr()
544
- i := 0
555
+ else
545
- while i < n
546
556
  b := s.byteAt(i)
547
557
  if isRegExpMetaByte(b)
548
558
  buf.writeByte(Byte(92))
549
559
  buf.writeByte(Byte(b))
550
- i = i + 1
551
- return buf.toStr()
560
+ escapeRegExpFrom(s, buf, i + 1)
552
561
 
553
562
  # Length of the HTML entity starting at `i` (and writes its decoded byte
554
563
  # into `buf`), or 0 if none starts there.
555
564
  fun unescapeEntityAt(s: Str, i: Int, buf: Buffer) -> Int =
556
565
  if matchesAt(s, "&amp;", i, 5)
557
566
  buf.writeByte(Byte(38))
558
- return 5
567
+ 5
559
- if matchesAt(s, "&lt;", i, 4)
568
+ else if matchesAt(s, "&lt;", i, 4)
560
569
  buf.writeByte(Byte(60))
561
- return 4
570
+ 4
562
- if matchesAt(s, "&gt;", i, 4)
571
+ else if matchesAt(s, "&gt;", i, 4)
563
572
  buf.writeByte(Byte(62))
564
- return 4
573
+ 4
565
- if matchesAt(s, "&quot;", i, 6)
574
+ else if matchesAt(s, "&quot;", i, 6)
566
575
  buf.writeByte(Byte(34))
567
- return 6
576
+ 6
568
- if matchesAt(s, "&#39;", i, 5)
577
+ else if matchesAt(s, "&#39;", i, 5)
569
578
  buf.writeByte(Byte(39))
579
+ 5
570
- return 5
580
+ else
571
- return 0
581
+ 0
572
582
 
573
583
  fun unescapeHtml(s: Str) -> Str =
584
+ unescapeFrom(s, Buffer(), 0)
585
+
586
+ fun unescapeFrom(s: Str, buf: Buffer, i: Int) -> Str =
574
- n := s.length()
587
+ if i >= s.length()
575
- buf := Buffer()
588
+ buf.toStr()
576
- i := 0
589
+ else
577
- while i < n
590
+ entity := if s.byteAt(i) == 38 then unescapeEntityAt(s, i, buf) else 0
578
- k := 0
579
- if s.byteAt(i) == 38
591
+ step := if entity == 0
580
- k = unescapeEntityAt(s, i, buf)
581
- if k == 0
582
592
  buf.writeByte(Byte(s.byteAt(i)))
593
+ 1
583
- k = 1
594
+ else
584
- i = i + k
595
+ entity
585
- return buf.toStr()
596
+ unescapeFrom(s, buf, i + step)
586
597
 
587
598
  # Shared walker behind `words`/`camelCase`/`snakeCase`/`kebabCase`/`startCase`:
588
599
  # splits on non-word bytes and on a lower->upper "camel" transition, joining
@@ -592,25 +603,22 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
592
603
  # (`toLower`/`upperCase` use `mapCase` — they map every byte 1:1 including
593
604
  # non-word bytes like spaces/punctuation, which this function drops.)
594
605
  fun caseConvert(s: Str, sep: Str, mode: Int) -> Str =
606
+ caseFrom(s, sep, mode, Buffer(), 0, 0, 0)
607
+
608
+ fun caseFrom(s: Str, sep: Str, mode: Int, buf: Buffer, i: Int, word_index: Int, prev_byte: Int) -> Str =
595
- n := s.length()
609
+ if i >= s.length()
596
- buf := Buffer()
610
+ buf.toStr()
597
- word_index := 0
598
- prev_byte := 0
599
- i := 0
611
+ else
600
- while i < n
601
612
  b := s.byteAt(i)
602
613
  if !isWordByte(b)
603
- prev_byte = 0
614
+ caseFrom(s, sep, mode, buf, i + 1, word_index, 0)
604
615
  else
605
616
  is_word_start := prev_byte == 0 || isCamelBoundary(prev_byte, b)
606
- if is_word_start
607
- word_index = word_index + 1
617
+ next_index := if is_word_start then word_index + 1 else word_index
608
- if word_index > 1
618
+ if is_word_start && next_index > 1
609
- buf.write(sep)
619
+ buf.write(sep)
610
- buf.writeByte(Byte(caseConvertByte(b, mode, is_word_start, word_index)))
620
+ buf.writeByte(Byte(caseConvertByte(b, mode, is_word_start, next_index)))
611
- prev_byte = b
612
- i = i + 1
613
- return buf.toStr()
621
+ caseFrom(s, sep, mode, buf, i + 1, next_index, b)
614
622
 
615
623
  fun caseConvertByte(b: Int, mode: Int, is_word_start: Bool, word_index: Int) -> Int =
616
624
  match mode
@@ -623,14 +631,15 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
623
631
  # Simple 1:1 byte map — every byte (including non-word bytes like spaces and
624
632
  # punctuation) is preserved; only letters are case-mapped.
625
633
  fun mapCase(s: Str, upper: Bool) -> Str =
634
+ mapCaseFrom(s, upper, Buffer(), 0)
635
+
636
+ fun mapCaseFrom(s: Str, upper: Bool, buf: Buffer, i: Int) -> Str =
626
- n := s.length()
637
+ if i >= s.length()
627
- buf := Buffer()
638
+ buf.toStr()
628
- i := 0
639
+ else
629
- while i < n
630
640
  b := s.byteAt(i)
631
641
  buf.writeByte(Byte(if upper then toUpperByte(b) else toLowerByte(b)))
632
- i = i + 1
633
- return buf.toStr()
642
+ mapCaseFrom(s, upper, buf, i + 1)
634
643
 
635
644
  # 2-char cells (space padded), one per codepoint U+00C0..U+00FF. `#` = keep
636
645
  # the original character (`×`, `÷`).
@@ -736,12 +745,7 @@ test "sub of a 200000-byte string is a single copy"
736
745
  assert s.slice(-5, 200000) == "aaaaa"
737
746
 
738
747
  test "reverse of a 100000-char string"
739
- buf := Buffer()
740
- i := 0
741
- while i < 100000
742
- buf.writeByte(Byte(if i == 0 then 98 else 97))
743
- i = i + 1
744
- r := buf.toStr().reverse()
748
+ r := {"b" + "a".repeat(99999)}.reverse()
745
749
  assert r.length() == 100000
746
750
  assert r.byteAt(99999) == 98
747
751
  assert r.byteAt(0) == 97
@@ -753,33 +757,18 @@ test "escape and unescape of a 100000-char string"
753
757
  assert e.unescape() == s
754
758
 
755
759
  test "camelCase of a 100000-char string"
756
- buf := Buffer()
757
- i := 0
758
- while i < 50000
759
- buf.write("ab ")
760
- i = i + 1
761
- r := buf.toStr().camelCase()
760
+ r := "ab ".repeat(50000).camelCase()
762
761
  assert r.length() == 50000 * 2
763
762
  assert r.startsWith("abAbAb")
764
763
 
765
764
  test "runeLength of 100000 multi-byte chars"
766
- buf := Buffer()
767
- i := 0
768
- while i < 100000
769
- buf.write("é")
765
+ s := "é".repeat(100000)
770
- i = i + 1
771
- s := buf.toStr()
772
766
  assert s.length() == 200000
773
767
  assert s.runeLength() == 100000
774
768
  assert s.runeAt(99999) == "é"
775
769
 
776
770
  test "split into 10000 parts"
777
- buf := Buffer()
778
- i := 0
779
- while i < 10000
780
- buf.write("x,")
781
- i = i + 1
782
- parts := buf.toStr().split(",", 0)
771
+ parts := "x,".repeat(10000).split(",", 0)
783
772
  assert parts.length() == 10001
784
773
 
785
774
  test "replace swaps only the first occurrence"
std/Time.plum CHANGED
@@ -15,68 +15,68 @@ struct Time(value: Int) =
15
15
 
16
16
  # The current wall-clock time.
17
17
  fun now(io: Io) -> Time =
18
- return Time(value: Int(io.rawNowMillis()))
18
+ Time(value: Int(io.rawNowMillis()))
19
19
 
20
20
  fun toMillis(self) -> Int =
21
- return self.value
21
+ self.value
22
22
 
23
23
  fun toSeconds(self) -> Int =
24
- return floorDiv(self.value, 1000)
24
+ floorDiv(self.value, 1000)
25
25
 
26
26
  fun add(self, d: Duration) -> Time =
27
- return Time(value: self.value + d.value)
27
+ Time(value: self.value + d.value)
28
28
 
29
29
  fun sub(self, d: Duration) -> Time =
30
- return Time(value: self.value - d.value)
30
+ Time(value: self.value - d.value)
31
31
 
32
32
  # The `Duration` elapsed between `other` and `self` (`self - other`) —
33
33
  # positive if `self` is later than `other`.
34
34
  fun since(self, other: Time) -> Duration =
35
- return Duration(value: self.value - other.value)
35
+ Duration(value: self.value - other.value)
36
36
 
37
37
  fun isBefore(self, other: Time) -> Bool =
38
- return self.value < other.value
38
+ self.value < other.value
39
39
 
40
40
  fun isAfter(self, other: Time) -> Bool =
41
- return self.value > other.value
41
+ self.value > other.value
42
42
 
43
43
  fun equals(self, other: Time) -> Bool =
44
- return self.value == other.value
44
+ self.value == other.value
45
45
 
46
46
  # The proleptic-Gregorian calendar date this instant falls on, in UTC.
47
47
  fun date(self) -> Civil =
48
- return civilFromDays(floorDiv(self.value, Time.MillisPerDay))
48
+ civilFromDays(floorDiv(self.value, Time.MillisPerDay))
49
49
 
50
50
  fun year(self) -> Int =
51
- return self.date().year
51
+ self.date().year
52
52
 
53
53
  fun month(self) -> Int =
54
- return self.date().month
54
+ self.date().month
55
55
 
56
56
  fun day(self) -> Int =
57
- return self.date().day
57
+ self.date().day
58
58
 
59
59
  fun hour(self) -> Int =
60
- return floorMod(floorDiv(self.value, 3600000), 24)
60
+ floorMod(floorDiv(self.value, 3600000), 24)
61
61
 
62
62
  fun minute(self) -> Int =
63
- return floorMod(floorDiv(self.value, 60000), 60)
63
+ floorMod(floorDiv(self.value, 60000), 60)
64
64
 
65
65
  fun second(self) -> Int =
66
- return floorMod(floorDiv(self.value, 1000), 60)
66
+ floorMod(floorDiv(self.value, 1000), 60)
67
67
 
68
68
  fun millisecond(self) -> Int =
69
- return floorMod(self.value, 1000)
69
+ floorMod(self.value, 1000)
70
70
 
71
71
  # Day of the week: 0 = Sunday, ..., 6 = Saturday (1970-01-01 was a
72
72
  # Thursday, hence the `+ 4` offset from the epoch day).
73
73
  fun weekday(self) -> Int =
74
- return floorMod(floorDiv(self.value, Time.MillisPerDay) + 4, 7)
74
+ floorMod(floorDiv(self.value, Time.MillisPerDay) + 4, 7)
75
75
 
76
76
  # ISO 8601 / RFC 3339, always in UTC (`Z`): `YYYY-MM-DDTHH:MM:SS.mmmZ`.
77
77
  fun toStr(self) -> Str =
78
78
  d := self.date()
79
- return d.year.toStr().padStart("0", 4) + "-" + d.month.toStr().padStart("0", 2)
79
+ d.year.toStr().padStart("0", 4) + "-" + d.month.toStr().padStart("0", 2)
80
80
  + "-" + d.day.toStr().padStart("0", 2) + "T" + self.hour().toStr().padStart("0", 2)
81
81
  + ":" + self.minute().toStr().padStart("0", 2) + ":" + self.second().toStr().padStart("0", 2)
82
82
  + "." + self.millisecond().toStr().padStart("0", 3) + "Z"
@@ -95,7 +95,7 @@ struct Time(value: Int) =
95
95
  mp := { 5 * doy + 2 } / 153
96
96
  d := doy - { 153 * mp + 2 } / 5 + 1
97
97
  m := if mp < 10 then mp + 3 else mp - 9
98
- return Civil(year: if m <= 2 then y + 1 else y, month: m, day: d)
98
+ Civil(year: if m <= 2 then y + 1 else y, month: m, day: d)
99
99
 
100
100
  # Integer division rounding toward negative infinity, unlike `/`'s
101
101
  # round-toward-zero — needed so times before the epoch (negative `value`)
@@ -104,11 +104,11 @@ struct Time(value: Int) =
104
104
  fun floorDiv(a: Int, b: Int) -> Int =
105
105
  q := a / b
106
106
  r := a % b
107
- return if { { r < 0 && b > 0 } || { r > 0 && b < 0 } } then q - 1 else q
107
+ if { { r < 0 && b > 0 } || { r > 0 && b < 0 } } then q - 1 else q
108
108
 
109
109
  fun floorMod(a: Int, b: Int) -> Int =
110
110
  r := a % b
111
- return if { { r < 0 && b > 0 } || { r > 0 && b < 0 } } then r + b else r
111
+ if { { r < 0 && b > 0 } || { r > 0 && b < 0 } } then r + b else r
112
112
 
113
113
  # A Gregorian calendar date, decomposed from a day count by `civilFromDays`.
114
114
  struct Civil(year: Int, month: Int, day: Int)
@@ -118,49 +118,49 @@ struct Civil(year: Int, month: Int, day: Int)
118
118
  struct Duration(value: Int) =
119
119
 
120
120
  fun millis(n: Int) -> Duration =
121
- return Duration(value: n)
121
+ Duration(value: n)
122
122
 
123
123
  fun seconds(n: Int) -> Duration =
124
- return Duration(value: n * 1000)
124
+ Duration(value: n * 1000)
125
125
 
126
126
  fun minutes(n: Int) -> Duration =
127
- return Duration(value: n * 60000)
127
+ Duration(value: n * 60000)
128
128
 
129
129
  fun hours(n: Int) -> Duration =
130
- return Duration(value: n * 3600000)
130
+ Duration(value: n * 3600000)
131
131
 
132
132
  fun days(n: Int) -> Duration =
133
- return Duration(value: n * Time.MillisPerDay)
133
+ Duration(value: n * Time.MillisPerDay)
134
134
 
135
135
  fun toMillis(self) -> Int =
136
- return self.value
136
+ self.value
137
137
 
138
138
  fun toSeconds(self) -> Float =
139
- return Float(self.value) / 1000.0f
139
+ Float(self.value) / 1000.0f
140
140
 
141
141
  fun add(self, other: Duration) -> Duration =
142
- return Duration(value: self.value + other.value)
142
+ Duration(value: self.value + other.value)
143
143
 
144
144
  fun sub(self, other: Duration) -> Duration =
145
- return Duration(value: self.value - other.value)
145
+ Duration(value: self.value - other.value)
146
146
 
147
147
  fun negate(self) -> Duration =
148
- return Duration(value: -self.value)
148
+ Duration(value: -self.value)
149
149
 
150
150
  fun abs(self) -> Duration =
151
- return Duration(value: if self.value < 0 then -self.value else self.value)
151
+ Duration(value: if self.value < 0 then -self.value else self.value)
152
152
 
153
153
  fun isZero(self) -> Bool =
154
- return self.value == 0
154
+ self.value == 0
155
155
 
156
156
  fun isBefore(self, other: Duration) -> Bool =
157
- return self.value < other.value
157
+ self.value < other.value
158
158
 
159
159
  fun isAfter(self, other: Duration) -> Bool =
160
- return self.value > other.value
160
+ self.value > other.value
161
161
 
162
162
  fun equals(self, other: Duration) -> Bool =
163
- return self.value == other.value
163
+ self.value == other.value
164
164
 
165
165
  test "Time.toStr formats the epoch as ISO 8601 in UTC"
166
166
  assert Time(value: 0).toStr() == "1970-01-01T00:00:00.000Z"
std/Uuid.plum CHANGED
@@ -15,18 +15,18 @@ enum UuidError = InvalidUuid
15
15
  struct Uuid(value: Str) =
16
16
 
17
17
  fun toStr(self) -> Str =
18
- return self.value
18
+ self.value
19
19
 
20
20
  fun equals(self, other: Uuid) -> Bool =
21
- return self.value == other.value
21
+ self.value == other.value
22
22
 
23
23
  fun isNil(self) -> Bool =
24
- return self.value == Uuid.Nil
24
+ self.value == Uuid.Nil
25
25
 
26
26
  # The version nibble (1-5 for a well-formed RFC 4122 UUID), the first hex
27
27
  # digit of the third group (`xxxxxxxx-xxxx-Vxxx-...`), at string index 14.
28
28
  fun version(self) -> Int =
29
- return hexValue(self.value.byteAt(14))
29
+ hexValue(self.value.byteAt(14))
30
30
 
31
31
  # The variant bits, decoded from the high bits of the first hex digit of
32
32
  # the fourth group (`...-Nxxx-...`), at string index 19. Returns 0 for the
@@ -36,34 +36,39 @@ struct Uuid(value: Str) =
36
36
  fun variant(self) -> Int =
37
37
  n := hexValue(self.value.byteAt(19))
38
38
  if n & 0x8 == 0
39
- return 0
39
+ 0
40
- if n & 0x4 == 0
40
+ else if n & 0x4 == 0
41
- return 2
41
+ 2
42
- if n & 0x2 == 0
42
+ else if n & 0x2 == 0
43
+ 6
43
- return 6
44
+ else
44
- return 7
45
+ 7
45
46
 
46
47
  Nil = "00000000-0000-0000-0000-000000000000"
47
48
 
48
49
  fun nil() -> Uuid =
49
- return Uuid(value: Uuid.Nil)
50
+ Uuid(value: Uuid.Nil)
50
51
 
51
52
  # Parses the canonical `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` text form
52
53
  # (case-insensitive), failing with `Err(InvalidUuid)` if `s` isn't exactly that shape.
53
54
  fun fromStr(s: Str) -> Result[Uuid, UuidError] =
54
55
  if s.length() != 36
55
- return Err(InvalidUuid)
56
+ Err(InvalidUuid)
56
- i := 0
57
- while i < 36
58
- if i == 8 || i == 13 || i == 18 || i == 23
59
- # '-'
60
- if s.byteAt(i) != 45
57
+ else if shapeOk(s, 0)
58
+ Ok(Uuid(value: s.toLower()))
59
+ else
61
- return Err(InvalidUuid)
60
+ Err(InvalidUuid)
61
+
62
+ # Whether every byte of `s` from `i` on is a '-' at a group boundary or a hex digit elsewhere.
63
+ fun shapeOk(s: Str, i: Int) -> Bool =
64
+ if i >= 36
65
+ true
66
+ else
67
+ ok := if i == 8 || i == 13 || i == 18 || i == 23 then s.byteAt(i) == 45 else hexValue(s.byteAt(i)) >= 0
68
+ if ok
69
+ shapeOk(s, i + 1)
62
70
  else
63
- if hexValue(s.byteAt(i)) < 0
64
- return Err(InvalidUuid)
65
- i = i + 1
71
+ false
66
- return Ok(Uuid(value: s.toLower()))
67
72
 
68
73
  fun isValid(s: Str) -> Bool = match fromStr(s)
69
74
  Ok(_) => true
@@ -83,38 +88,41 @@ struct Uuid(value: Str) =
83
88
  s := hexDigits(time_low, 8) + "-" + hexDigits(time_mid, 4) + "-"
84
89
  + hexDigits(time_hi_and_version, 4) + "-" + hexDigits(clock_seq, 4) + "-"
85
90
  + hexDigits(node, 12)
86
- return Rolled(value: Uuid(value: s), rng: db.rng)
91
+ Rolled(value: Uuid(value: s), rng: db.rng)
87
92
 
88
93
  # The numeric value (0-15) of an ASCII hex digit byte, or -1 if it isn't one.
89
94
  fun hexValue(byte: Int) -> Int =
90
95
  # '0'-'9'
91
96
  if byte >= 48 && byte <= 57
92
- return byte - 48
97
+ byte - 48
93
98
  # 'a'-'f'
94
- if byte >= 97 && byte <= 102
99
+ else if byte >= 97 && byte <= 102
95
- return byte - 97 + 10
100
+ byte - 97 + 10
96
101
  # 'A'-'F'
97
- if byte >= 65 && byte <= 70
102
+ else if byte >= 65 && byte <= 70
98
- return byte - 65 + 10
103
+ byte - 65 + 10
99
- return -1
104
+ else
105
+ -1
100
106
 
101
107
  fun hexDigit(n: Int) -> Str =
102
108
  d := n & 0xF
103
109
  if d < 10
104
- return Int.digitChar(d)
110
+ Int.digitChar(d)
111
+ else
105
- match d
112
+ match d
106
- 10 => "a"
113
+ 10 => "a"
107
- 11 => "b"
114
+ 11 => "b"
108
- 12 => "c"
115
+ 12 => "c"
109
- 13 => "d"
116
+ 13 => "d"
110
- 14 => "e"
117
+ 14 => "e"
111
- _ => "f"
118
+ _ => "f"
112
119
 
113
120
  # The low `count` hex digits of `n`, most-significant first.
114
121
  fun hexDigits(n: Int, count: Int) -> Str =
115
122
  if count <= 0
116
- return ""
123
+ ""
124
+ else
117
- return hexDigits(n >> 4, count - 1) + hexDigit(n)
125
+ hexDigits(n >> 4, count - 1) + hexDigit(n)
118
126
 
119
127
  test "nil is the all-zero UUID and is recognized as such"
120
128
  assert Uuid.nil().toStr() == "00000000-0000-0000-0000-000000000000"
std/base64.plum CHANGED
@@ -21,15 +21,15 @@ enum Base64Error = InvalidBase64
21
21
 
22
22
  # Encode for PEM (RFC 1421): 64-character lines.
23
23
  fun encodePEM(data: Str) -> Str =
24
- return encode(data, "+", "/", "=", 64, "\r\n")
24
+ encode(data, "+", "/", "=", 64, "\r\n")
25
25
 
26
26
  # Encode for MIME (RFC 2045): 76-character lines.
27
27
  fun encodeMIME(data: Str) -> Str =
28
- return encode(data, "+", "/", "=", 76, "\r\n")
28
+ encode(data, "+", "/", "=", 76, "\r\n")
29
29
 
30
30
  # Encode for URLs (RFC 4648). Padding characters are stripped by default.
31
31
  fun encodeURL(data: Str, pad: Bool = false) -> Str =
32
- return encode(data, "-", "_", if pad then "=" else "", 0, "")
32
+ encode(data, "-", "_", if pad then "=" else "", 0, "")
33
33
 
34
34
  # Configurable encoding. The defaults are for RFC 4648. `pad` is the padding
35
35
  # character, or `""` to omit padding entirely; `linelen` is the output line
@@ -37,13 +37,17 @@ fun encodeURL(data: Str, pad: Bool = false) -> Str =
37
37
  fun encode(data: Str, at62: Str = "+", at63: Str = "/", pad: Str = "=", linelen: Int = 0, linesep: Str = "\r\n") -> Str =
38
38
  at62b := at62.byteAt(0)
39
39
  at63b := at63.byteAt(0)
40
- has_pad := pad.length() > 0
40
+ hasPad := pad.length() > 0
41
- padb := if has_pad then pad.byteAt(0) else 0
41
+ padb := if hasPad then pad.byteAt(0) else 0
42
42
  res := Buffer()
43
+ encodeFrom(data, res, 0, 0, at62b, at63b, hasPad, padb, linelen, linesep)
44
+ res.toStr()
45
+
46
+ # `encode`'s loop: writes the groups of `data` from byte `i` on into `res`.
47
+ # `lineChars` is how many characters the current output line holds so far.
48
+ fun encodeFrom(data: Str, res: Buffer, i: Int, lineChars: Int, at62b: Int, at63b: Int, hasPad: Bool, padb: Int, linelen: Int, linesep: Str) -> Unit =
43
49
  n := data.length()
44
- i := 0
45
- line_chars := 0
46
- while i < n
50
+ if i < n
47
51
  b0 := data.byteAt(i)
48
52
  has1 := i + 1 < n
49
53
  has2 := i + 2 < n
@@ -51,59 +55,60 @@ fun encode(data: Str, at62: Str = "+", at63: Str = "/", pad: Str = "=", linelen:
51
55
  b2 := if has2 then data.byteAt(i + 2) else 0
52
56
  res.writeByte(Byte(encodeByte(b0 >> 2, at62b, at63b)))
53
57
  res.writeByte(Byte(encodeByte({b0 & 0x03} << 4 | b1 >> 4, at62b, at63b)))
54
- line_chars = line_chars + 2
55
58
  if has1
56
59
  res.writeByte(Byte(encodeByte({b1 & 0x0F} << 2 | b2 >> 6, at62b, at63b)))
57
- line_chars = line_chars + 1
58
- else if has_pad
60
+ else if hasPad
59
61
  res.writeByte(Byte(padb))
60
- line_chars = line_chars + 1
61
62
  if has2
62
63
  res.writeByte(Byte(encodeByte(b2 & 0x3F, at62b, at63b)))
63
- line_chars = line_chars + 1
64
- else if has_pad
64
+ else if hasPad
65
65
  res.writeByte(Byte(padb))
66
+ third := if has1 || hasPad then 1 else 0
67
+ fourth := if has2 || hasPad then 1 else 0
66
- line_chars = line_chars + 1
68
+ written := lineChars + 2 + third + fourth
67
- i = i + 3
69
+ next := i + 3
68
- if linelen > 0 && line_chars >= linelen && i < n
70
+ if linelen > 0 && written >= linelen && next < n
69
71
  res.write(linesep)
72
+ encodeFrom(data, res, next, 0, at62b, at63b, hasPad, padb, linelen, linesep)
70
- line_chars = 0
73
+ else
71
- return res.toStr()
74
+ encodeFrom(data, res, next, written, at62b, at63b, hasPad, padb, linelen, linesep)
72
75
 
73
76
  # Encodes a single 6-bit value (0-63) as its base64 alphabet character.
74
77
  fun encodeByte(i: Int, at62: Int, at63: Int) -> Int =
75
78
  if i < 26
76
- return 65 + i # 'A'..'Z'
79
+ 65 + i # 'A'..'Z'
77
- if i < 52
80
+ else if i < 52
78
- return 97 + {i - 26} # 'a'..'z'
81
+ 97 + {i - 26} # 'a'..'z'
79
- if i < 62
82
+ else if i < 62
80
- return 48 + {i - 52} # '0'..'9'
83
+ 48 + {i - 52} # '0'..'9'
81
- if i == 62
84
+ else if i == 62
82
- return at62
85
+ at62
86
+ else
83
- return at63
87
+ at63
84
88
 
85
89
  # The inverse of `encodeByte`: a base64 alphabet character's 6-bit value, or
86
90
  # -1 if `b` isn't one of the 64 alphabet characters (whitespace/padding are
87
91
  # handled by the caller, not here).
88
92
  fun decodeByte(b: Int, at62: Int, at63: Int) -> Int =
89
93
  if b >= 65 && b <= 90
90
- return b - 65
94
+ b - 65
91
- if b >= 97 && b <= 122
95
+ else if b >= 97 && b <= 122
92
- return b - 97 + 26
96
+ b - 97 + 26
93
- if b >= 48 && b <= 57
97
+ else if b >= 48 && b <= 57
94
- return b - 48 + 52
98
+ b - 48 + 52
95
- if b == at62
99
+ else if b == at62
96
- return 62
100
+ 62
97
- if b == at63
101
+ else if b == at63
102
+ 63
98
- return 63
103
+ else
99
- return -1
104
+ -1
100
105
 
101
106
  fun isBase64Whitespace(b: Int) -> Bool =
102
107
  b == 32 || b == 9 || b == 10 || b == 13
103
108
 
104
109
  # Decode for URLs (RFC 4648).
105
110
  fun decodeUrl(data: Str) -> Result[Str, Base64Error] =
106
- return decode(data, "-", "_", "=")
111
+ decode(data, "-", "_", "=")
107
112
 
108
113
  # Configurable decoding. The defaults are for RFC 4648. Missing padding is
109
114
  # not an error. Non-base64 data, other than whitespace (which can appear at
@@ -111,27 +116,32 @@ fun decodeUrl(data: Str) -> Result[Str, Base64Error] =
111
116
  fun decode(data: Str, at62: Str = "+", at63: Str = "/", pad: Str = "=") -> Result[Str, Base64Error] =
112
117
  at62b := at62.byteAt(0)
113
118
  at63b := at63.byteAt(0)
114
- has_pad := pad.length() > 0
119
+ hasPad := pad.length() > 0
115
- padb := if has_pad then pad.byteAt(0) else -1
120
+ padb := if hasPad then pad.byteAt(0) else -1
116
121
  res := Buffer()
122
+ decodeFrom(data, res, 0, 0, 0, at62b, at63b, padb)
123
+
124
+ # `decode`'s loop: the bytes of `data` from `i` on, with `bits` / `nbits`
125
+ # the pending bits not yet written out as a whole byte.
126
+ fun decodeFrom(data: Str, res: Buffer, i: Int, bits: Int, nbits: Int, at62b: Int, at63b: Int, padb: Int) -> Result[Str, Base64Error] =
117
- n := data.length()
127
+ if i >= data.length()
118
- i := 0
119
- bits := 0
120
- nbits := 0
121
- while i < n
128
+ Ok(res.toStr())
129
+ else
122
130
  b := data.byteAt(i)
123
- i = i + 1
124
131
  if isBase64Whitespace(b) || b == padb
132
+ decodeFrom(data, res, i + 1, bits, nbits, at62b, at63b, padb)
125
- continue
133
+ else
126
- v := decodeByte(b, at62b, at63b)
134
+ v := decodeByte(b, at62b, at63b)
127
- if v < 0
135
+ if v < 0
128
- return Err(InvalidBase64)
136
+ Err(InvalidBase64)
137
+ else
129
- bits = {bits << 6} | v
138
+ acc := {bits << 6} | v
130
- nbits = nbits + 6
131
- if nbits >= 8
139
+ if nbits + 6 >= 8
132
- nbits = nbits - 8
140
+ left := nbits + 6 - 8
133
- res.writeByte(Byte({bits >> nbits} & 0xFF))
141
+ res.writeByte(Byte({acc >> left} & 0xFF))
134
- return Ok(res.toStr())
142
+ decodeFrom(data, res, i + 1, acc, left, at62b, at63b, padb)
143
+ else
144
+ decodeFrom(data, res, i + 1, acc, nbits + 6, at62b, at63b, padb)
135
145
 
136
146
  test "statics are reached through the Base64 namespace and round-trip"
137
147
  assert decode(encodePEM("hello"))! == "hello"
std/game/Affine.plum CHANGED
@@ -27,29 +27,31 @@ struct Affine(a: Float, b: Float, c: Float, d: Float, e: Float, f: Float) =
27
27
  fun inverse(self) -> Affine =
28
28
  det := self.a * self.d - self.b * self.c
29
29
  if det == 0.0
30
- return Affine.Identity
30
+ Affine.Identity
31
+ else
31
- ia := self.d / det
32
+ ia := self.d / det
32
- ib := 0.0 - self.b / det
33
+ ib := 0.0 - self.b / det
33
- ic := 0.0 - self.c / det
34
+ ic := 0.0 - self.c / det
34
- id := self.a / det
35
+ id := self.a / det
35
- Affine(
36
+ Affine(
36
- a: ia, b: ib, c: ic, d: id,
37
+ a: ia, b: ib, c: ic, d: id,
37
- e: 0.0 - {ia * self.e + ic * self.f},
38
+ e: 0.0 - {ia * self.e + ic * self.f},
38
- f: 0.0 - {ib * self.e + id * self.f})
39
+ f: 0.0 - {ib * self.e + id * self.f})
39
40
 
40
41
  # The transform that undoes this one, or None if it is singular.
41
42
  fun invert(self) -> Option[Affine] =
42
43
  det := self.a * self.d - self.b * self.c
43
44
  if det == 0.0 || {det * 0.0} != 0.0
44
- return None
45
+ None
46
+ else
45
- ia := self.d / det
47
+ ia := self.d / det
46
- ib := 0.0 - self.b / det
48
+ ib := 0.0 - self.b / det
47
- ic := 0.0 - self.c / det
49
+ ic := 0.0 - self.c / det
48
- id := self.a / det
50
+ id := self.a / det
49
- Some(Affine(
51
+ Some(Affine(
50
- a: ia, b: ib, c: ic, d: id,
52
+ a: ia, b: ib, c: ic, d: id,
51
- e: 0.0 - {ia * self.e + ic * self.f},
53
+ e: 0.0 - {ia * self.e + ic * self.f},
52
- f: 0.0 - {ib * self.e + id * self.f}))
54
+ f: 0.0 - {ib * self.e + id * self.f}))
53
55
 
54
56
  fun scaleX(self) -> Float =
55
57
  math.hypot(self.a, self.b)
std/game/Anim.plum CHANGED
@@ -75,20 +75,21 @@ fun animParLength(steps: List[Anim], acc: Float) -> Float = match steps
75
75
 
76
76
  fun animAt(a: Anim, t: Float) -> AnimPose =
77
77
  if t < 0.0
78
- return animIdentity()
78
+ animIdentity()
79
+ else
79
- match a
80
+ match a
80
- MoveBy(dx, dy, secs) =>
81
+ MoveBy(dx, dy, secs) =>
81
- p := animProgress(secs, t)
82
+ p := animProgress(secs, t)
82
- AnimPose(dx: dx * p, dy: dy * p, rotation: 0.0, scaleX: 1.0, scaleY: 1.0)
83
+ AnimPose(dx: dx * p, dy: dy * p, rotation: 0.0, scaleX: 1.0, scaleY: 1.0)
83
- RotateBy(radians, secs) =>
84
+ RotateBy(radians, secs) =>
84
- AnimPose(dx: 0.0, dy: 0.0, rotation: radians * animProgress(secs, t), scaleX: 1.0, scaleY: 1.0)
85
+ AnimPose(dx: 0.0, dy: 0.0, rotation: radians * animProgress(secs, t), scaleX: 1.0, scaleY: 1.0)
85
- ScaleTo(sx, sy, secs) =>
86
+ ScaleTo(sx, sy, secs) =>
86
- p := animProgress(secs, t)
87
+ p := animProgress(secs, t)
87
- AnimPose(dx: 0.0, dy: 0.0, rotation: 0.0, scaleX: 1.0 + {sx - 1.0} * p, scaleY: 1.0 + {sy - 1.0} * p)
88
+ AnimPose(dx: 0.0, dy: 0.0, rotation: 0.0, scaleX: 1.0 + {sx - 1.0} * p, scaleY: 1.0 + {sy - 1.0} * p)
88
- Delay(_) => animIdentity()
89
+ Delay(_) => animIdentity()
89
- Seq(steps) => animSeqAt(steps, t, animIdentity())
90
+ Seq(steps) => animSeqAt(steps, t, animIdentity())
90
- Par(steps) => animParAt(steps, t, animIdentity())
91
+ Par(steps) => animParAt(steps, t, animIdentity())
91
- Forever(inner) => animForeverAt(inner, t)
92
+ Forever(inner) => animForeverAt(inner, t)
92
93
 
93
94
  # Finished steps contribute their final pose; the first unfinished one its partial pose.
94
95
  fun animSeqAt(steps: List[Anim], t: Float, acc: AnimPose) -> AnimPose = match steps
@@ -107,8 +108,9 @@ fun animParAt(steps: List[Anim], t: Float, acc: AnimPose) -> AnimPose = match st
107
108
  fun animForeverAt(inner: Anim, t: Float) -> AnimPose =
108
109
  lap := animLength(inner)
109
110
  if lap <= 0.0 || lap >= animForever()
110
- return animAt(inner, t)
111
+ animAt(inner, t)
112
+ else
111
- animAt(inner, t - {t / lap}.floor() * lap)
113
+ animAt(inner, t - {t / lap}.floor() * lap)
112
114
 
113
115
  fun animNear(a: Float, b: Float) -> Bool =
114
116
  {a - b}.abs() < 1e-6
std/game/input.plum CHANGED
@@ -229,10 +229,7 @@ struct Input(held: Held, events: Slice[InputEvent], pos: Vec2, wheel: Float) =
229
229
 
230
230
  # Went down this frame.
231
231
  fun isKeyPressed(self, key: Int) -> Bool =
232
- for i := range self.events.length()
233
- if self.events.at(i).isKeyDownOf(key)
232
+ 0.to(self.events.length()).find(|i| self.events.at(i).isKeyDownOf(key)).isSome()
234
- return true
235
- false
236
233
 
237
234
  # The left mouse button, or a touch.
238
235
  fun isMouseDown(self) -> Bool =
@@ -251,16 +248,10 @@ struct Input(held: Held, events: Slice[InputEvent], pos: Vec2, wheel: Float) =
251
248
  Pointer(pos: self.pos, down: self.held.mouse, pressed: self.pointerPressed(), released: self.pointerReleased())
252
249
 
253
250
  fun pointerPressed(self) -> Bool =
254
- for i := range self.events.length()
255
- if self.events.at(i).isPointerDown()
251
+ 0.to(self.events.length()).find(|i| self.events.at(i).isPointerDown()).isSome()
256
- return true
257
- false
258
252
 
259
253
  fun pointerReleased(self) -> Bool =
260
- for i := range self.events.length()
261
- if self.events.at(i).isPointerUp()
254
+ 0.to(self.events.length()).find(|i| self.events.at(i).isPointerUp()).isSome()
262
- return true
263
- false
264
255
 
265
256
  # What happened to a UI element: pressed on it, released after a press on it,
266
257
  # clicked (pressed and released on it), or the pointer entered or left it.
std/game/scene.plum CHANGED
@@ -71,13 +71,14 @@ struct Rect(x: Float, y: Float, w: Float, h: Float) =
71
71
 
72
72
  # The smallest box holding `a` (when there is one) and `b`.
73
73
  fun union(a: Option[Rect], b: Rect) -> Rect =
74
+ match a
74
- if Some(ra) := a
75
+ Some(ra) =>
75
- x0 := ra.x.min(b.x)
76
+ x0 := ra.x.min(b.x)
76
- y0 := ra.y.min(b.y)
77
+ y0 := ra.y.min(b.y)
77
- x1 := {ra.x + ra.w}.max(b.x + b.w)
78
+ x1 := {ra.x + ra.w}.max(b.x + b.w)
78
- y1 := {ra.y + ra.h}.max(b.y + b.h)
79
+ y1 := {ra.y + ra.h}.max(b.y + b.h)
79
- return Rect(x: x0, y: y0, w: x1 - x0, h: y1 - y0)
80
+ Rect(x: x0, y: y0, w: x1 - x0, h: y1 - y0)
80
- b
81
+ None => b
81
82
 
82
83
  fun contains(self, px: Float, py: Float) -> Bool =
83
84
  px >= self.x && px <= self.x + self.w && py >= self.y && py <= self.y + self.h
@@ -104,15 +105,15 @@ enum SceneNode[M] =
104
105
 
105
106
  # The bounding box of the scene in its own space (all zero when empty).
106
107
  fun bounds(self) -> Rect =
107
- if Some(r) := self.boundsWith(Affine.Identity)
108
+ match self.boundsWith(Affine.Identity)
108
- return r
109
+ Some(r) => r
109
- Rect(x: 0.0, y: 0.0, w: 0.0, h: 0.0)
110
+ None => Rect(x: 0.0, y: 0.0, w: 0.0, h: 0.0)
110
111
 
111
112
  # Child indices from the root down to the topmost hit leaf; empty on a miss.
112
113
  fun hitPath(self, x: Float, y: Float) -> Slice[Int] =
113
- if Some(p) := self.hitWith(x, y)
114
+ match self.hitWith(x, y)
114
- return p
115
+ Some(p) => p
115
- Slice[Int]()
116
+ None => Slice[Int]()
116
117
 
117
118
  # The id of the innermost Clickable node under (x, y), or None. Later siblings win.
118
119
  fun hitId(self, x: Float, y: Float) -> Option[Int] =
@@ -276,8 +277,9 @@ enum SceneNode[M] =
276
277
 
277
278
  fun hitLeaf(hit: Bool) -> Option[Slice[Int]] =
278
279
  if hit
279
- return Some(Slice[Int]())
280
+ Some(Slice[Int]())
281
+ else
280
- None
282
+ None
281
283
 
282
284
  # `i` followed by the path `sub`.
283
285
  fun hitPrepend(i: Int, sub: Slice[Int]) -> Slice[Int] =
std/game/ui.plum CHANGED
@@ -22,14 +22,11 @@ struct UiState(x: Float, y: Float, down: Bool, hot: Option[Int], captured: Optio
22
22
 
23
23
  struct UiStep(ui: UiState, events: List[UiEvent])
24
24
 
25
- fun uiSame(a: Option[Int], b: Option[Int]) -> Bool =
25
+ fun uiSame(a: Option[Int], b: Option[Int]) -> Bool = match a
26
- if Some(va) := a
26
+ Some(va) => match b
27
- if Some(vb) := b
28
- return va == vb
27
+ Some(vb) => va == vb
29
- return false
28
+ None => false
30
- if Some(vb) := b
29
+ None => b.isNone()
31
- return false
32
- true
33
30
 
34
31
  # Exit for the old hot id and Enter for the new one when they differ.
35
32
  fun uiHover(out: Slice[UiEvent], old: Option[Int], now: Option[Int]) =
@@ -42,61 +39,58 @@ fun uiHover(out: Slice[UiEvent], old: Option[Int], now: Option[Int]) =
42
39
  fun init() -> UiState =
43
40
  UiState(x: 0.0, y: 0.0, down: false, hot: None, captured: None)
44
41
 
42
+ # The state after one pointer input, pushing the events it raises onto `out`.
43
+ # A capture left over without a held button is stale.
44
+ fun uiTransition(out: Slice[UiEvent], ui: UiState, input: InputEvent, hit: Option[Int]) -> UiState =
45
+ cap: Option[Int] := if ui.down then ui.captured else None
46
+ match input
47
+ PointerDown(_, _) =>
48
+ uiHover(out, ui.hot, hit)
49
+ newCap := match hit
50
+ Some(h) =>
51
+ out.push(UiEvent(id: h, kind: Press))
52
+ Some(h)
53
+ None => None
54
+ UiState(..ui, down: true, hot: hit, captured: newCap)
55
+ PointerMove(_, _) => match cap
56
+ Some(c) =>
57
+ now: Option[Int] := if uiSame(hit, cap) then cap else None
58
+ uiHover(out, ui.hot, now)
59
+ UiState(..ui, hot: now, captured: cap)
60
+ None =>
61
+ uiHover(out, ui.hot, hit)
62
+ UiState(..ui, hot: hit, captured: cap)
63
+ PointerUp(_, _) =>
64
+ match cap
65
+ Some(c) =>
66
+ out.push(UiEvent(id: c, kind: Release))
67
+ if uiSame(hit, cap)
68
+ out.push(UiEvent(id: c, kind: Click))
69
+ None =>
70
+ uiHover(out, ui.hot, hit)
71
+ UiState(..ui, down: false, hot: hit, captured: None)
72
+ _ => UiState(..ui, captured: cap)
73
+
45
74
  # A key changes nothing here (keys go to the game).
46
75
  fun step(ui: UiState, input: InputEvent, hit: Option[Int]) -> UiStep =
47
76
  maybePos := input.position()
48
77
  if maybePos.isNone()
49
- return UiStep(ui: ui, events: Nil)
78
+ UiStep(ui: ui, events: Nil)
79
+ else
50
- pos := maybePos!
80
+ pos := maybePos!
51
- out := Slice[UiEvent]()
81
+ out := Slice[UiEvent]()
52
- # a capture left over without a held button is stale
53
- cap: Option[Int] := ui.captured
54
- if !ui.down
55
- cap = None
56
- hot: Option[Int] := ui.hot
57
- down := ui.down
58
- match input
59
- PointerDown(_, _) =>
60
- cap = None
61
- uiHover(out, hot, hit)
82
+ next := uiTransition(out, ui, input, hit)
62
- hot = hit
63
- down = true
64
- if Some(h) := hit
65
- out.push(UiEvent(id: h, kind: Press))
66
- cap = Some(h)
67
- PointerMove(_, _) =>
68
- if Some(c) := cap
69
- now: Option[Int] := None
70
- if uiSame(hit, cap)
71
- now = cap
72
- uiHover(out, hot, now)
73
- hot = now
74
- else
75
- uiHover(out, hot, hit)
76
- hot = hit
77
- PointerUp(_, _) =>
78
- if Some(c) := cap
79
- out.push(UiEvent(id: c, kind: Release))
80
- if uiSame(hit, cap)
81
- out.push(UiEvent(id: c, kind: Click))
82
- cap = None
83
- hot = hit
84
- else
85
- uiHover(out, hot, hit)
86
- hot = hit
87
- down = false
88
- _ => 0
89
- UiStep(ui: UiState(x: pos.x, y: pos.y, down: down, hot: hot, captured: cap), events: List.fromSlice(out))
83
+ UiStep(ui: UiState(..next, x: pos.x, y: pos.y), events: List.fromSlice(out))
90
84
 
91
85
  fun pressed(ui: UiState, id: Int) -> Bool =
92
- if Some(c) := ui.captured
86
+ match ui.captured
93
- return c == id && uiSame(ui.hot, ui.captured)
87
+ Some(c) => c == id && uiSame(ui.hot, ui.captured)
94
- false
88
+ None => false
95
89
 
96
90
  fun hovered(ui: UiState, id: Int) -> Bool =
97
- if Some(h) := ui.hot
91
+ match ui.hot
98
- return h == id
92
+ Some(h) => h == id
99
- false
93
+ None => false
100
94
 
101
95
  # A tagged, translated rectangle with a label whose colour follows the state.
102
96
  # The messages of the Clickables that `events` clicked, in order, read from `view`.
@@ -105,18 +99,20 @@ fun messages[M](view: SceneNode[M], events: List[UiEvent]) -> List[M] = match ev
105
99
  Cons(e, rest) =>
106
100
  later := messages(view, rest)
107
101
  if e.kind != Click
108
- return later
109
- if Some(m) := view.msgOf(e.id)
110
- return Cons(head: m, tail: later)
111
- later
102
+ later
103
+ else
104
+ match view.msgOf(e.id)
105
+ Some(m) => Cons(head: m, tail: later)
106
+ None => later
112
107
 
113
108
  # A button that sends `msg` when clicked; `id` identifies it for hover and press.
114
109
  fun button[M](id: Int, msg: M, label: Str, x: Float, y: Float, w: Float, h: Float, ui: UiState) -> SceneNode[M] =
115
- color := uiIdleColor()
116
- if pressed(ui, id)
110
+ color := if pressed(ui, id)
117
- color = uiPressedColor()
111
+ uiPressedColor()
118
112
  else if hovered(ui, id)
119
- color = uiHoverColor()
113
+ uiHoverColor()
114
+ else
115
+ uiIdleColor()
120
116
  Clickable(id: id, msg: msg, child: Group(transform: Translate(dx: x, dy: y), children: [
121
117
  RectShape(x: 0.0, y: 0.0, w: w, h: h, color: color),
122
118
  Text(text: label, x: 4.0, y: 4.0, size: h * 0.5, color: Color.White)]))
@@ -136,11 +132,7 @@ fun uiUp(x: Float) -> InputEvent = PointerUp(x: x, y: 0.0)
136
132
  fun uiMove(x: Float) -> InputEvent = PointerMove(x: x, y: 0.0)
137
133
 
138
134
  fun uiCount(s: UiStep, k: UiKind) -> Int =
139
- n := 0
140
- for e := range s.events
135
+ s.events.fold(0, |n, e| if e.kind == k then n + 1 else n)
141
- if e.kind == k
142
- n = n + 1
143
- n
144
136
 
145
137
  fun uiIs(e: UiEvent, id: Int, kind: UiKind) -> Bool = e.id == id && e.kind == kind
146
138
 
std/http.plum CHANGED
@@ -36,7 +36,7 @@ struct Response(status: Int, headers: Map[Str, Str], body: Str) =
36
36
  # Parses `body` as JSON. Fails the same way `Json.fromStr` does for a
37
37
  # response body that isn't valid JSON.
38
38
  fun json(self) -> Result[Json, JsonError] =
39
- return Json.fromStr(self.body)
39
+ Json.fromStr(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
@@ -51,7 +51,7 @@ struct Response(status: Int, headers: Map[Str, Str], body: Str) =
51
51
  # when the body itself is arbitrary binary data.
52
52
 
53
53
  fun emptyHeaders() -> Map[Str, Str] =
54
- return Map.empty()
54
+ Map.empty()
55
55
 
56
56
  # Packs `headers` into the `"Key: Value"`-per-line format `rawHttpRequest`
57
57
  # expects for its own `headers` argument.
@@ -63,21 +63,22 @@ fun encodeHeaders(headers: Map[Str, Str]) -> Str =
63
63
  buf.write(e.first)
64
64
  buf.write(": ")
65
65
  buf.write(e.second)
66
- return buf.toStr()
66
+ buf.toStr()
67
67
 
68
68
  # The reverse of `encodeHeaders`, for the response headers `rawHttpRequest`
69
69
  # packs into its result.
70
70
  fun decodeHeaders(raw: Str) -> Map[Str, Str] =
71
71
  result := emptyHeaders()
72
72
  if raw == ""
73
- return result
73
+ result
74
+ else
74
- for line := range raw.split("\n", 0)
75
+ for line := range raw.split("\n", 0)
75
- idx := line.indexOf(": ")
76
+ idx := line.indexOf(": ")
76
- if idx >= 0
77
+ if idx >= 0
77
- key := line.sub(0, idx)
78
+ key := line.sub(0, idx)
78
- val := line.sub(idx + 2, line.length())
79
+ val := line.sub(idx + 2, line.length())
79
- result.set(key, val)
80
+ result.set(key, val)
80
- return result
81
+ result
81
82
 
82
83
  # Performs a single HTTP request and waits for the full response. Fails
83
84
  # only for a transport-level problem (DNS failure, connection refused, TLS
@@ -93,35 +94,36 @@ fun request(io: Io, method: Str, url: Str, headers: Map[Str, Str], body: Str) ->
93
94
  parts := meta.split("\x01", 3)
94
95
  flag := parts.get(0).unwrapOr("")
95
96
  if flag != "1"
96
- return Err(HttpFailed)
97
+ Err(HttpFailed)
98
+ else
97
- match Int.parse(parts.get(1).unwrapOr(""))
99
+ match Int.parse(parts.get(1).unwrapOr(""))
98
- Ok(status) => Ok(Response(status: status, headers: decodeHeaders(parts.get(2).unwrapOr("")), body: resp_body))
100
+ Ok(status) => Ok(Response(status: status, headers: decodeHeaders(parts.get(2).unwrapOr("")), body: resp_body))
99
- Err(e) => Err(BadResponse)
101
+ Err(e) => Err(BadResponse)
100
102
 
101
103
  fun get(io: Io, url: Str, headers: Map[Str, Str]) -> Result[Response, HttpError] =
102
- return request(io, "GET", url, headers, "")
104
+ request(io, "GET", url, headers, "")
103
105
 
104
106
  fun head(io: Io, url: Str, headers: Map[Str, Str]) -> Result[Response, HttpError] =
105
- return request(io, "HEAD", url, headers, "")
107
+ request(io, "HEAD", url, headers, "")
106
108
 
107
109
  fun delete(io: Io, url: Str, headers: Map[Str, Str]) -> Result[Response, HttpError] =
108
- return request(io, "DELETE", url, headers, "")
110
+ request(io, "DELETE", url, headers, "")
109
111
 
110
112
  fun post(io: Io, url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, HttpError] =
111
- return request(io, "POST", url, headers, body)
113
+ request(io, "POST", url, headers, body)
112
114
 
113
115
  fun put(io: Io, url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, HttpError] =
114
- return request(io, "PUT", url, headers, body)
116
+ request(io, "PUT", url, headers, body)
115
117
 
116
118
  fun patch(io: Io, url: Str, headers: Map[Str, Str], body: Str) -> Result[Response, HttpError] =
117
- return request(io, "PATCH", url, headers, body)
119
+ request(io, "PATCH", url, headers, body)
118
120
 
119
121
  # Convenience wrapper: sends `body` as a JSON `Str`, adding a
120
122
  # `Content-Type: application/json` header, and parses the response back as
121
123
  # JSON via `Response.json()`.
122
124
  fun postJson(io: Io, url: Str, headers: Map[Str, Str], body: Json) -> Result[Response, HttpError] =
123
125
  headers.set("Content-Type", "application/json")
124
- return post(io, url, headers, body.toStr())
126
+ post(io, url, headers, body.toStr())
125
127
 
126
128
  test "encodeHeaders/decodeHeaders round-trip a header map"
127
129
  h := emptyHeaders()
std/math.plum CHANGED
@@ -10,23 +10,26 @@ import std/Float
10
10
  # one body.
11
11
  fun powFloat(base: Float, y: Float) -> Float =
12
12
  if y == 0.0f
13
- return 1.0f
13
+ 1.0f
14
+ else
14
- yi := Int(y)
15
+ yi := Int(y)
15
- if Float(yi) == y
16
+ if Float(yi) == y
16
- neg := yi < 0
17
+ neg := yi < 0
17
- n := if neg then -yi else yi
18
+ n := if neg then -yi else yi
18
- result := 1.0f
19
+ result := powLoop(1.0f, base, n)
19
- b := base
20
- m := n
21
- while m > 0
22
- if m % 2 == 1
23
- result = result * b
24
- b = b * b
25
- m = m / 2
26
- return if neg then 1.0f / result else result
20
+ if neg then 1.0f / result else result
27
- if base < 0.0f
21
+ else if base < 0.0f
28
- return 0.0f / 0.0f
22
+ 0.0f / 0.0f
23
+ else
29
- return exp(y * ln(base))
24
+ exp(y * ln(base))
25
+
26
+ # Square-and-multiply over the exponent bits of `m`.
27
+ fun powLoop(result: Float, b: Float, m: Int) -> Float =
28
+ if m > 0
29
+ next := if m % 2 == 1 then result * b else result
30
+ powLoop(next, b * b, m / 2)
31
+ else
32
+ result
30
33
 
31
34
 
32
35
  # Natural exponential, e^x, via range reduction (halve x until |x| <= 0.5,
@@ -34,72 +37,81 @@ fun powFloat(base: Float, y: Float) -> Float =
34
37
  # result back up the same number of halvings).
35
38
  fun exp(x: Float) -> Float =
36
39
  if x != x
37
- return x
40
+ x
38
- if x > 700.0f
41
+ else if x > 700.0f
39
- return 1.0f / 0.0f
42
+ 1.0f / 0.0f
40
- if x < -700.0f
43
+ else if x < -700.0f
44
+ 0.0f
45
+ else
41
- return 0.0f
46
+ expReduce(x, 0)
47
+
42
- v := x
48
+ fun expReduce(v: Float, k: Int) -> Float =
43
- k := 0
44
- while v > 0.5f || v < -0.5f
49
+ if v > 0.5f || v < -0.5f
45
- v = v / 2.0f
50
+ expReduce(v / 2.0f, k + 1)
46
- k = k + 1
47
- term := 1.0f
48
- sum := 1.0f
49
- n := 1
51
+ else
52
+ squareTimes(expSeries(v, 1.0f, 1.0f, 1), k)
53
+
54
+ fun expSeries(v: Float, term: Float, sum: Float, n: Int) -> Float =
50
- while n < 25
55
+ if n < 25
51
- term = term * v / Float(n)
56
+ t := term * v / Float(n)
52
- sum = sum + term
57
+ expSeries(v, t, sum + t, n + 1)
53
- n = n + 1
54
- result := sum
58
+ else
55
- i := 0
59
+ sum
60
+
61
+ fun squareTimes(result: Float, k: Int) -> Float =
56
- while i < k
62
+ if k > 0
57
- result = result * result
63
+ squareTimes(result * result, k - 1)
58
- i = i + 1
64
+ else
59
- return result
65
+ result
60
66
 
61
67
  # Natural logarithm, via range reduction to v in [1, 2) plus the
62
68
  # fast-converging series ln(v) = 2*atanh((v-1)/(v+1)).
63
69
  fun ln(x: Float) -> Float =
64
70
  if x != x || x < 0.0f
65
- return 0.0f / 0.0f
71
+ 0.0f / 0.0f
66
- if x == 0.0f
72
+ else if x == 0.0f
67
- return -1.0f / 0.0f
73
+ -1.0f / 0.0f
68
- if x > Float.Max
74
+ else if x > Float.Max
75
+ x
76
+ else
69
- return x
77
+ lnDown(x, 0)
78
+
70
- v := x
79
+ fun lnDown(v: Float, k: Int) -> Float =
71
- k := 0
72
- while v >= 2.0f
80
+ if v >= 2.0f
73
- v = v / 2.0f
81
+ lnDown(v / 2.0f, k + 1)
82
+ else
74
- k = k + 1
83
+ lnUp(v, k)
84
+
85
+ fun lnUp(v: Float, k: Int) -> Float =
75
- while v < 1.0f
86
+ if v < 1.0f
76
- v = v * 2.0f
87
+ lnUp(v * 2.0f, k - 1)
77
- k = k - 1
88
+ else
78
- t := {v - 1.0f} / {v + 1.0f}
89
+ t := {v - 1.0f} / {v + 1.0f}
79
- t2 := t * t
90
+ t2 := t * t
80
- term := t
81
- sum := t
82
- n := 1
83
- while n < 30
84
- term = term * t2
85
- sum = sum + term / Float(2 * n + 1)
91
+ sum := lnSeries(t2, t, t, 1)
86
- n = n + 1
87
- return Float(k) * Float.Ln2 + 2.0f * sum
92
+ Float(k) * Float.Ln2 + 2.0f * sum
93
+
94
+ fun lnSeries(t2: Float, term: Float, sum: Float, n: Int) -> Float =
95
+ if n < 30
96
+ t := term * t2
97
+ lnSeries(t2, t, sum + t / Float(2 * n + 1), n + 1)
98
+ else
99
+ sum
88
100
 
89
101
  # Square root via Newton's method, iterating to a fixed point.
90
102
  fun sqrt(x: Float) -> Float =
91
103
  if x < 0.0f
92
- return 0.0f / 0.0f
104
+ 0.0f / 0.0f
93
- if x == 0.0f || x != x
105
+ else if x == 0.0f || x != x
94
- return x
106
+ x
95
- guess := x
107
+ else
96
- prev := 0.0f
108
+ sqrtFrom(x, x, 0.0f, 0)
109
+
97
- i := 0
110
+ fun sqrtFrom(x: Float, guess: Float, prev: Float, i: Int) -> Float =
98
- while guess != prev && i < 100
111
+ if guess != prev && i < 100
99
- prev = guess
100
- guess = 0.5f * {guess + x / guess}
112
+ sqrtFrom(x, 0.5f * {guess + x / guess}, guess, i + 1)
101
- i = i + 1
113
+ else
102
- return guess
114
+ guess
103
115
 
104
116
  # Reduces `x` into roughly `[-Float.Pi, Float.Pi]` by subtracting the nearest multiple of
105
117
  # `Float.Tau` — the range `sin`/`cos`'s Taylor series below actually converge
@@ -109,96 +121,105 @@ fun sqrt(x: Float) -> Float =
109
121
  # constants to avoid this, which isn't attempted here.
110
122
  fun reduceToPi(x: Float) -> Float =
111
123
  k := Int(x / Float.Tau + {if x >= 0.0f then 0.5f else -0.5f})
112
- return x - Float(k) * Float.Tau
124
+ x - Float(k) * Float.Tau
113
125
 
114
126
  fun sin(x: Float) -> Float =
115
127
  if x != x || x > Float.Max || x < -Float.Max
116
- return 0.0f / 0.0f
128
+ 0.0f / 0.0f
129
+ else
117
- r := reduceToPi(x)
130
+ r := reduceToPi(x)
118
- r2 := r * r
131
+ sinSeries(r * r, r, r, 1)
132
+
119
- term := r
133
+ fun sinSeries(r2: Float, term: Float, sum: Float, n: Int) -> Float =
120
- sum := r
121
- n := 1
122
- while n < 10
134
+ if n < 10
123
- term = term * {-r2} / Float({2 * n} * {2 * n + 1})
135
+ t := term * {-r2} / Float({2 * n} * {2 * n + 1})
124
- sum = sum + term
136
+ sinSeries(r2, t, sum + t, n + 1)
125
- n = n + 1
137
+ else
126
- return sum
138
+ sum
127
139
 
128
140
  fun cos(x: Float) -> Float =
129
141
  if x != x || x > Float.Max || x < -Float.Max
130
- return 0.0f / 0.0f
142
+ 0.0f / 0.0f
143
+ else
131
- return sin(x + Float.HalfPi)
144
+ sin(x + Float.HalfPi)
132
145
 
133
146
  fun tan(x: Float) -> Float =
134
- return sin(x) / cos(x)
147
+ sin(x) / cos(x)
135
148
 
136
149
  # Arctangent, via repeated argument-halving (`atan(x) = 2*atan(x / (1 +
137
150
  # sqrt(1+x^2)))`) until `|x| <= 0.5` (where the Taylor series below converges
138
151
  # quickly), then doubling the result back up the same number of times.
139
152
  fun atan(x: Float) -> Float =
140
153
  if x != x
154
+ x
141
- return x
155
+ else
142
- neg := x < 0.0f
156
+ neg := x < 0.0f
143
- v := if neg then -x else x
157
+ v := if neg then -x else x
144
- k := 0
158
+ result := atanReduce(v, 0)
159
+ if neg then -result else result
160
+
161
+ fun atanReduce(v: Float, k: Int) -> Float =
145
- while v > 0.5f && k < 8
162
+ if v > 0.5f && k < 8
146
- v = v / {1.0f + sqrt(1.0f + v * v)}
163
+ atanReduce(v / {1.0f + sqrt(1.0f + v * v)}, k + 1)
147
- k = k + 1
148
- v2 := v * v
149
- term := v
150
- sum := v
151
- n := 1
164
+ else
152
- while n < 20
153
- term = term * {-v2}
154
- sum = sum + term / Float(2 * n + 1)
165
+ sum := atanSeries(v * v, v, v, 1)
155
- n = n + 1
156
- scale := Float(1 << k)
166
+ scale := Float(1 << k)
157
- result := sum * scale
167
+ sum * scale
168
+
169
+ fun atanSeries(v2: Float, term: Float, sum: Float, n: Int) -> Float =
170
+ if n < 20
171
+ t := term * {-v2}
158
- return if neg then -result else result
172
+ atanSeries(v2, t, sum + t / Float(2 * n + 1), n + 1)
173
+ else
174
+ sum
159
175
 
160
176
  fun asin(x: Float) -> Float =
161
177
  if x != x || x < -1.0f || x > 1.0f
162
- return 0.0f / 0.0f
178
+ 0.0f / 0.0f
163
- if x == 1.0f
179
+ else if x == 1.0f
164
- return Float.HalfPi
180
+ Float.HalfPi
165
- if x == -1.0f
181
+ else if x == -1.0f
166
- return -Float.HalfPi
182
+ -Float.HalfPi
183
+ else
167
- return atan(x / sqrt(1.0f - x * x))
184
+ atan(x / sqrt(1.0f - x * x))
168
185
 
169
186
  fun acos(x: Float) -> Float =
170
- return Float.HalfPi - asin(x)
187
+ Float.HalfPi - asin(x)
171
188
 
172
189
  # Angle (in radians) of the point `(x, y)` from the origin, in the correct
173
190
  # quadrant for any sign combination of `x`/`y` (unlike plain `atan(y/x)`,
174
191
  # which can't distinguish opposite quadrants).
175
192
  fun atan2(y: Float, x: Float) -> Float =
176
193
  if x > 0.0f
177
- return atan(y / x)
194
+ atan(y / x)
178
- if x < 0.0f && y >= 0.0f
195
+ else if x < 0.0f && y >= 0.0f
179
- return atan(y / x) + Float.Pi
196
+ atan(y / x) + Float.Pi
180
- if x < 0.0f && y < 0.0f
197
+ else if x < 0.0f && y < 0.0f
181
- return atan(y / x) - Float.Pi
198
+ atan(y / x) - Float.Pi
182
- if x == 0.0f && y > 0.0f
199
+ else if x == 0.0f && y > 0.0f
183
- return Float.HalfPi
200
+ Float.HalfPi
184
- if x == 0.0f && y < 0.0f
201
+ else if x == 0.0f && y < 0.0f
185
- return -Float.HalfPi
202
+ -Float.HalfPi
203
+ else
186
- return 0.0f
204
+ 0.0f
187
205
 
188
206
  fun hypot(a: Float, b: Float) -> Float =
189
- return sqrt(a * a + b * b)
207
+ sqrt(a * a + b * b)
190
208
 
191
209
  # Cube root via Newton's method (fixed iteration count, unlike `sqrt`'s
192
210
  # converge-to-a-fixed-point loop, since the cubic update step doesn't reach an
193
211
  # exact fixed point in float precision as reliably as the quadratic one does).
194
212
  fun cbrt(x: Float) -> Float =
195
213
  if x == 0.0f || x != x
214
+ x
196
- return x
215
+ else
197
- neg := x < 0.0f
216
+ neg := x < 0.0f
198
- v := if neg then -x else x
217
+ v := if neg then -x else x
199
- guess := v
218
+ guess := cbrtFrom(v, v, 0)
200
- i := 0
201
- while i < 60
202
- guess = {2.0f * guess + v / {guess * guess}} / 3.0f
203
- i = i + 1
204
- return if neg then -guess else guess
219
+ if neg then -guess else guess
220
+
221
+ fun cbrtFrom(v: Float, guess: Float, i: Int) -> Float =
222
+ if i < 60
223
+ cbrtFrom(v, {2.0f * guess + v / {guess * guess}} / 3.0f, i + 1)
224
+ else
225
+ guess
std/os.plum CHANGED
@@ -57,36 +57,41 @@ fun stderr() -> Str =
57
57
  # `libs/std/str.plum` — so this works for binary content too, not just text).
58
58
  fun readFile(io: Io, path: Str) -> Result[Str, IoError] =
59
59
  if !exists(io, path)
60
- return Err(NoSuchPath)
60
+ Err(NoSuchPath)
61
+ else
61
- return Ok(io.rawReadFile(path))
62
+ Ok(io.rawReadFile(path))
62
63
 
63
64
  # Writes `data` to `path`, replacing its previous contents (or creating it).
64
65
  fun writeFile(io: Io, path: Str, data: Str) -> Result[Unit, IoError] =
65
66
  if io.rawWriteFile(path, data) != 1
66
- return Err(IoFailed)
67
+ Err(IoFailed)
68
+ else
67
- Ok(Unit)
69
+ Ok(Unit)
68
70
 
69
71
  fun exists(io: Io, path: Str) -> Bool =
70
- return io.rawExists(path) == 1
72
+ io.rawExists(path) == 1
71
73
 
72
74
  fun mkdir(io: Io, path: Str) -> Result[Unit, IoError] =
73
75
  if io.rawMkdir(path) != 1
74
- return Err(IoFailed)
76
+ Err(IoFailed)
77
+ else
75
- Ok(Unit)
78
+ Ok(Unit)
76
79
 
77
80
  # Removes the file (not directory) at `path`.
78
81
  fun remove(io: Io, path: Str) -> Result[Unit, IoError] =
79
82
  if !exists(io, path)
80
- return Err(NoSuchPath)
83
+ Err(NoSuchPath)
84
+ else
81
- if io.rawRemove(path) != 1
85
+ if io.rawRemove(path) != 1
82
- return Err(IoFailed)
86
+ Err(IoFailed)
87
+ else
83
- Ok(Unit)
88
+ Ok(Unit)
84
89
 
85
90
  # Whether `path` exists and is reachable — this VM has no notion of a
86
91
  # process' effective uid/gid, so (unlike POSIX `access(2)`) there is no mode
87
92
  # argument to check permission bits against.
88
93
  fun access(io: Io, path: Str) -> Bool =
89
- return exists(io, path)
94
+ exists(io, path)
90
95
 
91
96
  # Appends `data` to the file at `path`, creating it (with just `data` as its
92
97
  # contents) if it doesn't already exist. There's no host-level "open for
@@ -95,15 +100,17 @@ fun access(io: Io, path: Str) -> Bool =
95
100
  fun appendFile(io: Io, path: Str, data: Str) -> Result[Unit, IoError] =
96
101
  if exists(io, path)
97
102
  existing := readFile(io, path)?
98
- return writeFile(io, path, existing + data)
103
+ writeFile(io, path, existing + data)
104
+ else
99
- writeFile(io, path, data)
105
+ writeFile(io, path, data)
100
106
 
101
107
  # Unix permission bits only (e.g. `0o644`) — this VM has no Windows ACL
102
108
  # equivalent to fall back to.
103
109
  fun chmod(io: Io, path: Str, mode: Int) -> Result[Unit, IoError] =
104
110
  if io.rawChmod(path, mode) != 1
105
- return Err(IoFailed)
111
+ Err(IoFailed)
112
+ else
106
- Ok(Unit)
113
+ Ok(Unit)
107
114
 
108
115
  # There is no host primitive for changing file ownership (it needs a uid/gid
109
116
  # syscall this VM doesn't expose), unlike the permission-bits-only `chmod`.
@@ -134,8 +141,9 @@ fun lutimes(path: Str, atime: Int, mtime: Int) =
134
141
 
135
142
  fun link(io: Io, existing_path: Str, new_path: Str) -> Result[Unit, IoError] =
136
143
  if io.rawLink(existing_path, new_path) != 1
137
- return Err(IoFailed)
144
+ Err(IoFailed)
145
+ else
138
- Ok(Unit)
146
+ Ok(Unit)
139
147
 
140
148
  # Would need a real `Stat` struct type (size/mode/mtime/uid/gid/...) to
141
149
  # return anything useful — no such type exists in the stdlib yet.
@@ -148,9 +156,10 @@ fun lstat(path: Str) =
148
156
  fun mkdtemp(io: Io, prefix: Str) -> Result[Str, IoError] =
149
157
  path := prefix + Uuid.v4(Random.seeded(io.randomSeed())).value.toStr()
150
158
  if exists(io, path)
151
- return mkdtemp(io, prefix)
159
+ mkdtemp(io, prefix)
160
+ else
152
- mkdir(io, path)?
161
+ mkdir(io, path)?
153
- return Ok(path)
162
+ Ok(path)
154
163
 
155
164
  # Would need a host-side open-file-descriptor table (this VM's other file
156
165
  # ops are all one-shot: open+read/write+close in a single host call) plus a
@@ -165,41 +174,48 @@ fun opendir(path: Str) =
165
174
  # The names of `path`'s directory entries (not full paths).
166
175
  fun readdir(io: Io, path: Str) -> Result[Slice[Str], IoError] =
167
176
  if !exists(io, path)
168
- return Err(NoSuchPath)
177
+ Err(NoSuchPath)
178
+ else
169
- # skipping empty names handles both a genuinely empty directory (whose
179
+ # skipping empty names handles both a genuinely empty directory (whose
170
- # joined `""` would otherwise split into one bogus `""` entry) and
180
+ # joined `""` would otherwise split into one bogus `""` entry) and
171
- # `rawReadDir`'s "unreadable" fallback (already ruled out by the `exists`
181
+ # `rawReadDir`'s "unreadable" fallback (already ruled out by the `exists`
172
- # check above) the same way — no directory entry is ever named `""`.
182
+ # check above) the same way — no directory entry is ever named `""`.
173
- names := Slice[Str]()
183
+ names := Slice[Str]()
174
- for n := range io.rawReadDir(path).split("\n", 0)
184
+ for n := range io.rawReadDir(path).split("\n", 0)
175
- if n != ""
185
+ if n != ""
176
- names.push(n)
186
+ names.push(n)
177
- return Ok(names)
187
+ Ok(names)
178
188
 
179
189
  fun readlink(io: Io, path: Str) -> Result[Str, IoError] =
180
190
  if !exists(io, path)
181
- return Err(NoSuchPath)
191
+ Err(NoSuchPath)
192
+ else
182
- return Ok(io.rawReadlink(path))
193
+ Ok(io.rawReadlink(path))
183
194
 
184
195
  fun realpath(io: Io, path: Str) -> Result[Str, IoError] =
185
196
  if !exists(io, path)
186
- return Err(NoSuchPath)
197
+ Err(NoSuchPath)
198
+ else
187
- return Ok(io.rawRealpath(path))
199
+ Ok(io.rawRealpath(path))
188
200
 
189
201
  fun rename(io: Io, old_path: Str, new_path: Str) -> Result[Unit, IoError] =
190
202
  if !exists(io, old_path)
191
- return Err(NoSuchPath)
203
+ Err(NoSuchPath)
204
+ else
192
- if io.rawRename(old_path, new_path) != 1
205
+ if io.rawRename(old_path, new_path) != 1
193
- return Err(IoFailed)
206
+ Err(IoFailed)
207
+ else
194
- Ok(Unit)
208
+ Ok(Unit)
195
209
 
196
210
  # Removes an empty directory. (`remove` above covers plain files.)
197
211
  fun rmdir(io: Io, path: Str) -> Result[Unit, IoError] =
198
212
  if !exists(io, path)
199
- return Err(NoSuchPath)
213
+ Err(NoSuchPath)
214
+ else
200
- if io.rawRemoveDir(path) != 1
215
+ if io.rawRemoveDir(path) != 1
201
- return Err(IoFailed)
216
+ Err(IoFailed)
217
+ else
202
- Ok(Unit)
218
+ Ok(Unit)
203
219
 
204
220
  # See `lstat` — needs a `Stat` struct type.
205
221
  fun stat(path: Str) =
@@ -211,17 +227,20 @@ fun statfs(path: Str) =
211
227
 
212
228
  fun symlink(io: Io, target: Str, path: Str) -> Result[Unit, IoError] =
213
229
  if io.rawSymlink(target, path) != 1
214
- return Err(IoFailed)
230
+ Err(IoFailed)
231
+ else
215
- Ok(Unit)
232
+ Ok(Unit)
216
233
 
217
234
  # Resizes the file at `path` to exactly `len` bytes — truncated if shorter,
218
235
  # zero-padded if longer.
219
236
  fun truncate(io: Io, path: Str, len: Int) -> Result[Unit, IoError] =
220
237
  if !exists(io, path)
221
- return Err(NoSuchPath)
238
+ Err(NoSuchPath)
239
+ else
222
- if io.rawTruncate(path, len) != 1
240
+ if io.rawTruncate(path, len) != 1
223
- return Err(IoFailed)
241
+ Err(IoFailed)
242
+ else
224
- Ok(Unit)
243
+ Ok(Unit)
225
244
 
226
245
  # See `lutimes` — same missing syscall.
227
246
  fun utimes(path: Str, atime: Int, mtime: Int) =
@@ -313,9 +332,10 @@ test "link creates a second name for the same file"
313
332
 
314
333
  test "readFile/remove/rmdir report errors for missing paths"
315
334
  assert readFile(io, "/tmp/plum_os_test_does_not_exist.txt").unwrapOr("gone") == "gone"
316
- failed := 0
317
- if Err(e) := remove(io, "/tmp/plum_os_test_does_not_exist.txt")
335
+ removeFailed := match remove(io, "/tmp/plum_os_test_does_not_exist.txt")
318
- failed = failed + 1
336
+ Err(e) => 1
337
+ Ok(_) => 0
319
- if Err(e) := rmdir(io, "/tmp/plum_os_test_does_not_exist_dir")
338
+ rmdirFailed := match rmdir(io, "/tmp/plum_os_test_does_not_exist_dir")
320
- failed = failed + 1
339
+ Err(e) => 1
340
+ Ok(_) => 0
321
- assert failed == 2
341
+ assert removeFailed + rmdirFailed == 2