plum

#treesitter#compiler#wasm

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

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


2c8333e — Peter John 2026-11-10T10:42:10+05:30
std collections: O(n) List.toArray, merge sort, checked indexing, Slice combinators, Map[K, V](), Heap.by
compiler/cli/tests/cli/main.rs CHANGED
@@ -13,4 +13,5 @@ mod main_result_test;
13
13
  mod no_fbip_test;
14
14
  mod old_forms_test;
15
15
  mod replay_test;
16
+ mod std_bounds_test;
16
17
  mod test_scope_test;
compiler/cli/tests/cli/std_bounds_test.rs ADDED
@@ -0,0 +1,88 @@
1
+ #![allow(non_snake_case)]
2
+ //! std's checked indexing: `Slice.at`, `Deque.at`, `Str.byteAt` and `Str.get` out of range
3
+ //! stop the program with the index and the length, instead of reading another slot.
4
+ use std::process::Command;
5
+
6
+ fn plumBin() -> std::path::PathBuf {
7
+ let mut path = std::env::current_exe().unwrap();
8
+ path.pop();
9
+ if path.ends_with("deps") {
10
+ path.pop();
11
+ }
12
+ path.push("plum");
13
+ path
14
+ }
15
+
16
+ /// Runs `body` as `main`'s body and returns (success, stderr).
17
+ fn run(name: &str, body: &str) -> (bool, String) {
18
+ let dir = std::env::temp_dir().join(format!("plum_bounds_{}_{}", name, std::process::id()));
19
+ std::fs::create_dir_all(&dir).unwrap();
20
+ let src = dir.join(format!("{name}.plum"));
21
+ let text = format!(
22
+ "import std/Int\nimport std/Str\nimport std/Io\nimport std/Option\nimport std/Slice\nimport std/Deque\n\nfun main(io: Io) =\n{body}"
23
+ );
24
+ std::fs::write(&src, text).unwrap();
25
+ let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
26
+ let out = Command::new(plumBin())
27
+ .current_dir(root)
28
+ .args(["run", src.to_str().unwrap()])
29
+ .output()
30
+ .expect("failed to run plum");
31
+ (out.status.success(), String::from_utf8_lossy(&out.stderr).to_string())
32
+ }
33
+
34
+ fn expectCrash(name: &str, body: &str, msg: &str) {
35
+ let (ok, stderr) = run(name, body);
36
+ assert!(!ok, "{name}: expected a crash; stderr: {stderr}");
37
+ assert!(stderr.contains(msg), "{name}: stderr was: {stderr}");
38
+ }
39
+
40
+ #[test]
41
+ fn slice_at_past_a_pop_crashes() {
42
+ expectCrash(
43
+ "slice_pop",
44
+ " s := Slice[Int]()\n s.push(1)\n s.push(2)\n _ := s.pop()\n io.printLn(\"{s.at(1)}\")\n",
45
+ "Slice.at: index 1 out of range for length 1",
46
+ );
47
+ }
48
+
49
+ #[test]
50
+ fn slice_view_at_minus_one_crashes() {
51
+ expectCrash(
52
+ "slice_view",
53
+ " s := Slice[Int]()\n s.push(1)\n s.push(2)\n v := s.slice(1, 2)\n io.printLn(\"{v.at(-1)}\")\n",
54
+ "Slice.at: index -1 out of range for length 1",
55
+ );
56
+ }
57
+
58
+ #[test]
59
+ fn deque_at_out_of_range_crashes() {
60
+ expectCrash(
61
+ "deque",
62
+ " d := Deque[Int]()\n d.pushBack(1)\n io.printLn(\"{d.at(1)}\")\n",
63
+ "Deque.at: index 1 out of range for length 1",
64
+ );
65
+ }
66
+
67
+ #[test]
68
+ fn str_byte_at_and_get_out_of_range_crash() {
69
+ expectCrash(
70
+ "str_byte",
71
+ " s := \"abcdef\".sub(1, 3)\n io.printLn(\"{s.byteAt(2)}\")\n",
72
+ "Str.byteAt: index 2 out of range for length 2",
73
+ );
74
+ expectCrash(
75
+ "str_get",
76
+ " io.printLn(\"ab\".get(-1))\n",
77
+ "Str.byteAt: index -1 out of range for length 2",
78
+ );
79
+ }
80
+
81
+ #[test]
82
+ fn in_range_reads_still_work() {
83
+ let (ok, stderr) = run(
84
+ "fine",
85
+ " s := Slice[Int]()\n s.push(4)\n d := Deque[Int]()\n d.pushBack(5)\n io.printLn(\"{s.at(0)} {d.at(0)} {\"xy\".byteAt(1)}\")\n",
86
+ );
87
+ assert!(ok, "stderr: {stderr}");
88
+ }
docs/std.md CHANGED
@@ -57,10 +57,11 @@ fun main() =
57
57
  ```
58
58
 
59
59
  - **Search:** `contains`, `startsWith`, `endsWith`, `indexOf`
60
- - **Cut:** `sub`, `slice`, `split(separator, limit)`, `trim`, `trimStart`, `trimEnd`, `truncate`
60
+ - **Cut:** `sub`, `slice`, `split(separator, limit)`, `trim`, `trimStart`, `trimEnd`, `truncate`. `trim` strips ASCII whitespace and Unicode's other White_Space characters (U+00A0, U+3000, U+2028, ...). `truncate(n)` cuts at a character boundary, never inside a multi-byte character.
61
61
  - **Change:** `replace`, `replaceAll`, `repeat`, `reverse`, `padStart`, `padEnd`
62
62
  - **Case:** `upperCase`, `lowerCase`, `capitalize`, `camelCase`, `snakeCase`, `kebabCase`
63
- - **Unicode:** `length` counts bytes; `runeLength` and `runeAt` count characters
63
+ - **Unicode:** `length` counts bytes; `runeLength` and `runeAt` count characters. `runeAt(i)` is an `Option[Str]`, `None` past the last character.
64
+ - **Bytes:** `byteAt(i)` and `get(i)` crash with the index and the length out of range, so a substring never reads its source's bytes outside it.
64
65
 
65
66
  To build a string in steps, use `Buffer`: `write`, `writeByte`, `toStr`.
66
67
 
@@ -82,9 +83,12 @@ fun main() =
82
83
  second := xs.at(1) # the value, or crash when out of range
83
84
  ```
84
85
 
85
- - **Read:** `get`, `at`, `first`, `last`, `head`, `length`, `contains`, `findValue`
86
- - **Change:** `push`, `pop`, `set`, `add`, `remove`, `removeAt`, `clear`, `sort`, `reverse`, `shuffle`
87
- - **Other:** `slice` (a view that shares storage), `sublist` (a copy), `chunk`, `join`, `drop`
86
+ - **Read:** `get`, `at`, `first`, `last`, `length`, `isEmpty`, `contains`, `findValue`. `at` crashes with the index and the length out of range (also on a view, and past a `pop`).
87
+ - **Loop:** `fold`, `each`, `map`, `filter`, `find(pred)`, `any`, `all`, as on `List`
88
+ - **Change:** `push`, `pop`, `set`, `add`, `remove`, `removeAt`, `clear`, `reverse`, `shuffle`
89
+ - **Other:** `sort(before)` (a new slice; a stable merge sort, O(n log n)), `slice` (a view that shares storage), `sublist` (a copy), `chunk`, `join`, `drop`, and with `std/Map` imported `groupBy(key)` (a `Map` from each key to its elements, in order)
90
+
91
+ Renamed or removed: `Slice.head` (use `first`), `Set.toList` is now `toSlice`.
88
92
 
89
93
  **`Array`** has a fixed size: `Array.filled(n, value)`, `get`, `set`, `length`. **`Grid`** is a 2D array: `Grid.filled(w, h, value)`, `get(x, y)`, `set(x, y, value)`.
90
94
 
@@ -101,10 +105,10 @@ fun main() =
101
105
  ann := ages.get("ann").unwrapOr(0)
102
106
  ```
103
107
 
104
- - **`Map`:** `get`, `set`, `has`, `remove`, `keys`, `values`, `entries`, `length`. `Map.empty()` makes an empty one, but needs a type: `m: Map[Str, Int] := Map.empty()`
105
- - **`Set`:** `add`, `has`, `remove`, `length`, `toList`
106
- - **`Deque`:** a queue you can use from both ends: `pushBack`, `pushFront`, `popBack`, `popFront`
107
- - **`Heap`:** always gives back the smallest item first: `push`, `pop`, `peek`
108
+ - **`Map`:** `get`, `set`, `has`, `remove`, `keys`, `values`, `entries`, `length`. `Map[Str, Int]()` makes an empty one, like `Slice[T]()` and `Set[T]()` (`m: Map[Str, Int] := Map.empty()` too). `with(k, v)` is what a map literal `[k => v]` is built with: it sets the key in the map itself and returns it, so it is `set` that chains, not a copy
109
+ - **`Set`:** `add`, `has`, `remove`, `length`, `toSlice`
110
+ - **`Deque`:** a queue you can use from both ends: `pushBack`, `pushFront`, `popBack`, `popFront`, `get`, `at` (crashes out of range)
111
+ - **`Heap`:** gives back first the item nothing comes `before`: `h: Heap[Int] := Heap.by(|a, b| a < b)`, or `Heap.byKey(|n| n.cost)` by a key of any type with `<`; `push`, `pop`, `peek`
108
112
 
109
113
  ## Functional collections
110
114
 
@@ -175,7 +179,7 @@ fun main(io: Io) =
175
179
  io.printLn(text)
176
180
  ```
177
181
 
178
- - **`os`:** `readFile`, `writeFile`, `appendFile`, `exists`, `mkdir`, `remove`, `rename`, `copyFile`, `readdir`
182
+ - **`os`:** `readFile`, `writeFile`, `appendFile`, `exists`, `mkdir`, `remove`, `rename`, `copyFile`, `readdir`. There is no `stat`, `open`, `chown` or `utimes`: the host has no such call.
179
183
  - **`http`:** `get`, `post`, `put`, `patch`, `delete`, `head`, `postJson`. A `Response` has `status`, `headers`, `body`, `ok()` and `json()`
180
184
 
181
185
  ## Utilities
examples/games/orb_run.plum CHANGED
@@ -399,7 +399,7 @@ fun isRestartKey(e: InputEvent) -> Bool = match e
399
399
  _ => false
400
400
 
401
401
  # Whether the tick's input has one of the restart keys going down, or Escape.
402
- fun pressedRestart(input: Input) -> Bool = 0.until(input.events.length()).find(|i| isRestartKey(input.events.at(i))).isSome()
402
+ fun pressedRestart(input: Input) -> Bool = input.events.any(|e| isRestartKey(e))
403
403
 
404
404
  fun pressedEscape(input: Input) -> Bool = input.isKeyPressed(Key.Escape)
405
405
 
std/Deque.plum CHANGED
@@ -5,6 +5,7 @@ import std/Slice
5
5
  import std/Option
6
6
  import std/Int
7
7
  import std/Float
8
+ import std/Str
8
9
 
9
10
  # A double-ended queue: a ring buffer over `Array[T]`. `buf`'s length is the
10
11
  # capacity, `head` the index of the front element, `size` the number in use;
@@ -70,9 +71,10 @@ struct Deque[T](mut buf: Array[T], mut head: Int, mut size: Int) =
70
71
  else
71
72
  Some(self.buf.get({self.head + i} % self.buf.length()))
72
73
 
73
- # the `i`'th element from the front, unchecked (the `for x := range deque` protocol)
74
+ # The `i`'th element from the front (the `for x := range deque` protocol). Crashes with
75
+ # the index and the length when `i` is out of range.
74
76
  fun at(self, i: Int) -> T =
75
- self.buf.get({self.head + i} % self.buf.length())
77
+ if i < 0 || i >= self.size then slice.outOfRange("Deque.at", i, self.size) else self.buf.get({self.head + i} % self.buf.length())
76
78
 
77
79
  fun clear(self) -> Unit =
78
80
  self.head = 0
std/Heap.plum CHANGED
@@ -5,15 +5,22 @@ import std/Slice
5
5
  import std/Option
6
6
  import std/Int
7
7
  import std/Float
8
+ import std/Str
8
9
 
9
- # A binary MIN-heap ordered by a key function: `pop` returns the element whose
10
+ # A binary MIN-heap ordered by `before(a, b)`, "does a come out before b": `pop`
11
+ # returns an element no other element comes before. `h: Heap[Int] := Heap.by(|a, b| a < b)`
10
- # `key(x)` is smallest. Ordering by an explicit `fn(T) -> Float` (rather than a
12
+ # is an empty heap; `Heap.byKey(|n| n.f)` orders by a key (of any type with `<`), which
11
- # duck-typed `lt` method) lets one type be queued under different priorities and
12
- # fits A* directly: `Heap[Node](key: |n| n.f)`. The key is recomputed on each
13
+ # fits A* directly. The order is asked on each comparison, so keep it cheap
13
- # comparison, so keep it cheap and don't mutate an element's key while it is in
14
+ # and don't change an element's order while it is in the heap. `push`/`pop` are
14
- # the heap. `push`/`pop` are O(log n); `peek`/`length` are O(1). Equal keys pop in
15
+ # O(log n); `peek`/`length` are O(1). Equal elements pop in no guaranteed order.
15
- # no guaranteed order.
16
- struct Heap[T](items: Slice[T], key: fn(T) -> Float) =
16
+ struct Heap[T](items: Slice[T], before: fn(T, T) -> Bool) =
17
+ # An empty heap ordered by `before`.
18
+ fun by(before: fn(T, T) -> Bool) -> Heap[T] =
19
+ Heap(items: Slice[T](), before: before)
20
+
21
+ # An empty heap that pops the element with the smallest `key` first.
22
+ fun byKey[K](key: fn(T) -> K) -> Heap[T] =
23
+ Heap(items: Slice[T](), before: |a, b| key(a) < key(b))
17
24
 
18
25
  fun length(self) -> Int =
19
26
  self.items.length()
@@ -25,12 +32,12 @@ struct Heap[T](items: Slice[T], key: fn(T) -> Float) =
25
32
  self.items.clear()
26
33
 
27
34
  fun swap(self, i: Int, j: Int) -> Unit =
28
- a := self.items.data.get(i)
35
+ a := self.items.atUnchecked(i)
29
- self.items.data.set(i, self.items.data.get(j))
36
+ self.items.putAt(i, self.items.atUnchecked(j))
30
- self.items.data.set(j, a)
37
+ self.items.putAt(j, a)
31
38
 
32
39
  fun less(self, i: Int, j: Int) -> Bool =
33
- self.key(self.items.data.get(i)) < self.key(self.items.data.get(j))
40
+ self.before(self.items.atUnchecked(i), self.items.atUnchecked(j))
34
41
 
35
42
  fun siftUp(self, i: Int) -> Unit =
36
43
  p := {i - 1} / 2
@@ -52,27 +59,25 @@ struct Heap[T](items: Slice[T], key: fn(T) -> Float) =
52
59
  self.items.push(v)
53
60
  self.siftUp(self.items.length() - 1)
54
61
 
55
- # The smallest element without removing it, or None if empty.
62
+ # The first element without removing it, or None if empty.
56
63
  fun peek(self) -> Option[T] =
57
- if self.items.length() == 0
64
+ self.items.first()
58
- None
59
- else
60
- Some(self.items.data.get(0))
61
65
 
62
- # Removes and returns the smallest element, or None if empty.
66
+ # Removes and returns the first element, or None if empty.
63
67
  fun pop(self) -> Option[T] =
64
68
  n := self.items.length()
65
69
  if n == 0
66
70
  None
67
71
  else
68
- top := self.items.data.get(0)
72
+ top := self.items.atUnchecked(0)
69
- self.items.data.set(0, self.items.data.get(n - 1))
73
+ last := self.items.pop()!
74
+ if n > 1
70
- self.items.size = n - 1
75
+ self.items.putAt(0, last)
71
- self.siftDown(0)
76
+ self.siftDown(0)
72
77
  Some(top)
73
78
 
74
79
  test "heap_pop_order: 1000 pseudo-random keys pop in ascending order"
75
- h := Heap[Int](items: Slice[Int](), key: |x| Float(x))
80
+ h: Heap[Int] := Heap.by(|a, b| a < b)
76
81
  _ := 1.to(1000).fold(12345, |x, _|
77
82
  next := {x * 1103515245 + 12345} % 2147483648
78
83
  h.push(next % 100000)
@@ -88,7 +93,7 @@ test "heap_pop_order: 1000 pseudo-random keys pop in ascending order"
88
93
  assert h.pop().unwrapOr(-1) == -1
89
94
 
90
95
  test "peek shows the minimum and Float keys order records"
91
- h := Heap[Float](items: Slice[Float](), key: |x| 0.0 - x)
96
+ h: Heap[Float] := Heap.byKey(|x| 0.0 - x)
92
97
  h.push(1.5)
93
98
  h.push(9.5)
94
99
  h.push(4.0)
@@ -96,3 +101,16 @@ test "peek shows the minimum and Float keys order records"
96
101
  assert h.pop()! == 9.5
97
102
  assert h.pop()! == 4.0
98
103
  assert h.length() == 1
104
+
105
+ test "byKey orders by a key of any type, and before can make a max-heap"
106
+ h: Heap[Str] := Heap.byKey(|s| s.length())
107
+ h.push("ccc")
108
+ h.push("a")
109
+ h.push("bb")
110
+ assert h.pop()! == "a" && h.pop()! == "bb" && h.pop()! == "ccc"
111
+ assert h.pop().isNone() && h.peek().isNone()
112
+ g: Heap[Int] := Heap.by(|a, b| a > b)
113
+ for i := range 100
114
+ g.push({i * 37} % 100)
115
+ assert g.peek()! == 99
116
+ assert 0.until(100).fold(true, |ok, i| ok && g.pop()! == 99 - i)
std/List.plum CHANGED
@@ -85,8 +85,14 @@ enum List[T] =
85
85
  out.push(x)
86
86
  out
87
87
 
88
+ # Sized once, then filled: O(n) (`Array.push` copies the whole array each time).
88
89
  fun toArray(self) -> Array[T] =
89
- self.fold(Array[T](), |out, x| out.push(x))
90
+ out := Array[T]().resize(self.length())
91
+ _ := self.fold(0, |i, x|
92
+ out.set(i, x)
93
+ i + 1
94
+ )
95
+ out
90
96
 
91
97
  fun toStr(self) -> Str =
92
98
  res := Buffer()
std/Map.plum CHANGED
@@ -42,6 +42,10 @@ struct Map[K, V](mut index: Array[Int], mut hashes: Array[Int], mut keys: Array[
42
42
  m.allocate(16)
43
43
  m
44
44
 
45
+ # `Map[Str, Int]()` is the empty map too, like `Slice[T]()` and `Set[T]()`.
46
+ fun init() -> Map[K, V] =
47
+ Map.empty()
48
+
45
49
  # Installs empty storage for `cap` index slots (a power of two).
46
50
  fun allocate(self, cap: Int) -> Unit =
47
51
  n := cap - cap / 4
@@ -206,6 +210,24 @@ struct Map[K, V](mut index: Array[Int], mut hashes: Array[Int], mut keys: Array[
206
210
  out.push(self.vals.get(i))
207
211
  out
208
212
 
213
+
214
+ # ---- extensions of std types that need a Map (Slice can't import Map: Map uses Slice) ----
215
+
216
+ primitive Slice[T] =
217
+ # The elements grouped by `key`, each group in order, the groups in the order their
218
+ # keys first appear: `words.groupBy(|w| w.length())`.
219
+ fun groupBy[K](self, key: fn(T) -> K) -> Map[K, Slice[T]] =
220
+ out: Map[K, Slice[T]] := Map.empty()
221
+ for x := range self
222
+ k := key(x)
223
+ match out.get(k)
224
+ Some(g) => g.push(x)
225
+ None =>
226
+ g := Slice[T]()
227
+ g.push(x)
228
+ out.set(k, g)
229
+ out
230
+
209
231
  test "get/set/has round-trip and set replaces an existing key in place"
210
232
  m: Map[Str, Int] := Map.empty()
211
233
  assert m.has("a") == false
std/Set.plum CHANGED
@@ -32,12 +32,9 @@ struct Set[T](map: Map[T, Bool]) =
32
32
  fun clear(self) -> Unit =
33
33
  self.map.clear()
34
34
 
35
- # Every member, in insertion order.
35
+ # Every member, in insertion order, as a new `Slice` (was `toList`).
36
- fun toList(self) -> Slice[T] =
36
+ fun toSlice(self) -> Slice[T] =
37
- result := Slice[T]()
38
- for k := range self.map.keys()
37
+ self.map.keys()
39
- result.push(k)
40
- result
41
38
 
42
39
  test "set_dedup: adding duplicates keeps one copy"
43
40
  s := Set[Int]()
@@ -62,11 +59,11 @@ test "remove and clear"
62
59
  s.clear()
63
60
  assert s.isEmpty()
64
61
 
65
- test "toList returns each member once"
62
+ test "toSlice returns each member once"
66
63
  s := Set[Int]()
67
64
  s.add(5)
68
65
  s.add(5)
69
66
  s.add(7)
70
- l := s.toList()
67
+ l := s.toSlice()
71
68
  assert l.length() == 2
72
69
  assert l.get(0)! + l.get(1)! == 12
std/Slice.plum CHANGED
@@ -41,10 +41,57 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
41
41
  self.data.set(self.start + i, v)
42
42
  Some(old)
43
43
 
44
- # the element at index i, unchecked (the `for x := range list` protocol; i must be in range)
44
+ # The element at index i (the `for x := range list` protocol). Crashes with the index
45
+ # and the length when i is out of range: a view never reads its parent's slots, and a
46
+ # popped slot is never read back.
45
47
  fun at(self, i: Int) -> T =
48
+ if i < 0 || i >= self.size then outOfRange("Slice.at", i, self.size) else self.data.get(self.start + i)
49
+
50
+ # `at` without the range check, for std's own loops whose index is proven in range.
51
+ fun atUnchecked(self, i: Int) -> T =
46
52
  self.data.get(self.start + i)
47
53
 
54
+ fun isEmpty(self) -> Bool =
55
+ self.size == 0
56
+
57
+ # Left fold over the elements, in order: `f(f(f(acc, x0), x1), x2)`.
58
+ fun fold[A](self, acc: A, f: fn(A, T) -> A) -> A =
59
+ foldFrom(self, 0, acc, f)
60
+
61
+ # Calls `f` on each element, in order.
62
+ fun each(self, f: fn(T) -> Unit) -> Unit =
63
+ eachFrom(self, 0, f)
64
+
65
+ # A new slice of `f` of each element, in order.
66
+ fun map[B](self, f: fn(T) -> B) -> Slice[B] =
67
+ mapFrom(self, 0, f, Slice[B]())
68
+
69
+ # A new slice of the elements for which `keep` holds, in order.
70
+ fun filter(self, keep: fn(T) -> Bool) -> Slice[T] =
71
+ filterFrom(self, 0, keep, Slice[T]())
72
+
73
+ # The first element for which `keep` holds, or None. Stops at the first hit.
74
+ fun find(self, keep: fn(T) -> Bool) -> Option[T] =
75
+ i := self.indexWhere(keep, 0)
76
+ if i < 0 then None else Some(self.data.get(self.start + i))
77
+
78
+ # The index of the first element at or after `i` for which `keep` holds, or -1.
79
+ fun indexWhere(self, keep: fn(T) -> Bool, i: Int) -> Int =
80
+ if i >= self.size
81
+ -1
82
+ else if keep(self.data.get(self.start + i))
83
+ i
84
+ else
85
+ self.indexWhere(keep, i + 1)
86
+
87
+ # Whether `keep` holds for some element. Stops at the first hit.
88
+ fun any(self, keep: fn(T) -> Bool) -> Bool =
89
+ self.indexWhere(keep, 0) >= 0
90
+
91
+ # Whether `keep` holds for every element (true when empty). Stops at the first miss.
92
+ fun all(self, keep: fn(T) -> Bool) -> Bool =
93
+ allFrom(self, 0, keep)
94
+
48
95
  # Rewrites every slot with `f(old)` and returns the same list (no new list).
49
96
  fun mapInPlace(self, f: fn(T) -> T) -> Slice[T] =
50
97
  for i := range self.size
@@ -160,22 +207,21 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
160
207
  self.swapInwards(i + 1, j - 1)
161
208
 
162
209
  # Returns a NEW list with `self`'s elements sorted, using `before(a, b)` as
163
- # the "does a belong before b" comparator. Insertion sort (O(n^2)).
210
+ # the "does a belong before b" comparator. A stable merge sort, O(n log n): runs
211
+ # of `SortRun` elements are insertion sorted in place, then merged pairwise
212
+ # through one scratch array, back and forth. Equal elements keep their order.
164
213
  fun sort(self, before: fn(T, T) -> Bool) -> Slice[T] =
165
214
  result := self.sublist(0, self.size)
166
- for i := range 1.until(result.size)
215
+ n := result.size
216
+ if n > 1
217
+ sortRuns(result.data, 0, n, before)
218
+ if n > SortRun
219
+ scratch := Array[T]().resize(n)
167
- result.insertBefore(result.data.get(result.start + i), i - 1, before)
220
+ if mergePasses(result.data, scratch, n, SortRun, before)
221
+ result.data = scratch
222
+ result.cap = n
168
223
  result
169
224
 
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 =
173
- if j >= 0 && before(x, self.data.get(self.start + j))
174
- self.data.set(self.start + j + 1, self.data.get(self.start + j))
175
- self.insertBefore(x, j - 1, before)
176
- else
177
- self.data.set(self.start + j + 1, x)
178
-
179
225
  # Returns the first element equal to `search`, or None.
180
226
  fun findValue(self, search: T) -> Option[T] =
181
227
  i := self.indexFrom(search, 0)
@@ -194,13 +240,6 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
194
240
  else
195
241
  Some(self.data.get(self.start + 0))
196
242
 
197
- # the first element, or None when the list is empty (the typed tail of `find`)
198
- fun head(self) -> Option[T] =
199
- if self.size == 0
200
- None
201
- else
202
- Some(self.data.get(self.start + 0))
203
-
204
243
  # returns the last element in the list
205
244
  fun last(self) -> Option[T] =
206
245
  if self.size == 0
@@ -253,11 +292,6 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
253
292
  result.push(self.sublist(i, i + size))
254
293
  result
255
294
 
256
- # Grouping by an arbitrary key type would need `Map[K, Slice[T]]`, but
257
- # `Map.plum` depends on this file. Not implemented.
258
- fun groupBy(self) =
259
- todo
260
-
261
295
  fun join(self, sep: Str = ",") -> Str =
262
296
  res := Buffer()
263
297
  for i := range self.size
@@ -269,6 +303,106 @@ struct Slice[T](mut data: Array[T], mut start: Int, mut size: Int, mut cap: Int)
269
303
  fun toStr(self) -> Str =
270
304
  "[" + self.join(",") + "]"
271
305
 
306
+ # Stops the program: index `i` is out of range for a length `n` (`what` names the call).
307
+ fun outOfRange[T](what: Str, i: Int, n: Int) -> T =
308
+ crash "{what}: index {i} out of range for length {n}"
309
+
310
+ # The loops of `each`, `map`, `filter` and `all`, from index `i` on. They are direct tail
311
+ # calls, not `for` loops, so the function they are given is only called (a `for` body is a
312
+ # closure of its own, which would capture it).
313
+ fun eachFrom[T](xs: Slice[T], i: Int, f: fn(T) -> Unit) -> Unit =
314
+ if i < xs.size
315
+ f(xs.data.get(xs.start + i))
316
+ eachFrom(xs, i + 1, f)
317
+
318
+ fun mapFrom[T, B](xs: Slice[T], i: Int, f: fn(T) -> B, out: Slice[B]) -> Slice[B] =
319
+ if i >= xs.size
320
+ out
321
+ else
322
+ out.push(f(xs.data.get(xs.start + i)))
323
+ mapFrom(xs, i + 1, f, out)
324
+
325
+ fun filterFrom[T](xs: Slice[T], i: Int, keep: fn(T) -> Bool, out: Slice[T]) -> Slice[T] =
326
+ if i >= xs.size
327
+ out
328
+ else
329
+ x := xs.data.get(xs.start + i)
330
+ if keep(x)
331
+ out.push(x)
332
+ filterFrom(xs, i + 1, keep, out)
333
+
334
+ fun allFrom[T](xs: Slice[T], i: Int, keep: fn(T) -> Bool) -> Bool =
335
+ if i >= xs.size
336
+ true
337
+ else if !keep(xs.data.get(xs.start + i))
338
+ false
339
+ else
340
+ allFrom(xs, i + 1, keep)
341
+
342
+ # `fold`'s loop: folds the elements of `xs` from index `i` on into `acc`.
343
+ fun foldFrom[T, A](xs: Slice[T], i: Int, acc: A, f: fn(A, T) -> A) -> A =
344
+ if i >= xs.size
345
+ acc
346
+ else
347
+ foldFrom(xs, i + 1, f(acc, xs.data.get(xs.start + i)), f)
348
+
349
+ # ---- sort's merge sort, over the backing array of a fresh copy ----
350
+
351
+ # The length of the runs `sort` insertion sorts before merging.
352
+ SortRun = 16
353
+
354
+ # Insertion sorts each run of `SortRun` elements of `a[lo..n)`, from `lo` on.
355
+ fun sortRuns[T](a: Array[T], lo: Int, n: Int, before: fn(T, T) -> Bool) -> Unit =
356
+ if lo < n
357
+ hi := if lo + SortRun < n then lo + SortRun else n
358
+ insertRun(a, lo, lo + 1, hi, before)
359
+ sortRuns(a, hi, n, before)
360
+
361
+ # Insertion sorts `a[lo..hi)`, given that `a[lo..i)` is sorted.
362
+ fun insertRun[T](a: Array[T], lo: Int, i: Int, hi: Int, before: fn(T, T) -> Bool) -> Unit =
363
+ if i < hi
364
+ insertDown(a, lo, a.get(i), i - 1, before)
365
+ insertRun(a, lo, i + 1, hi, before)
366
+
367
+ # Shifts the elements of `a[lo..j]` that `x` belongs before one slot up, then puts `x` in
368
+ # the gap. Only a strict `before` moves an element, so equal ones keep their order.
369
+ fun insertDown[T](a: Array[T], lo: Int, x: T, j: Int, before: fn(T, T) -> Bool) -> Unit =
370
+ if j >= lo && before(x, a.get(j))
371
+ a.set(j + 1, a.get(j))
372
+ insertDown(a, lo, x, j - 1, before)
373
+ else
374
+ a.set(j + 1, x)
375
+
376
+ # Merges sorted runs of `width` from `src` into `dst`, doubling the width until one run
377
+ # covers `n`. True when the sorted elements end up in `dst`'s role of the first call (the
378
+ # scratch array), false when they end in `src`'s.
379
+ fun mergePasses[T](src: Array[T], dst: Array[T], n: Int, width: Int, before: fn(T, T) -> Bool) -> Bool =
380
+ mergePass(src, dst, 0, n, width, before)
381
+ if width * 2 >= n
382
+ true
383
+ else
384
+ !mergePasses(dst, src, n, width * 2, before)
385
+
386
+ # One pass: merges the run pairs `[lo, lo+width)` and `[lo+width, lo+2*width)` of `src`
387
+ # into `dst`, from `lo` on. A lone last run is copied.
388
+ fun mergePass[T](src: Array[T], dst: Array[T], lo: Int, n: Int, width: Int, before: fn(T, T) -> Bool) -> Unit =
389
+ if lo < n
390
+ mid := if lo + width < n then lo + width else n
391
+ hi := if mid + width < n then mid + width else n
392
+ mergeRun(src, dst, lo, mid, mid, hi, lo, before)
393
+ mergePass(src, dst, hi, n, width, before)
394
+
395
+ # Merges `src[i..mid)` and `src[j..hi)` into `dst` from `k` on. A tie takes the left
396
+ # element, which keeps the sort stable.
397
+ fun mergeRun[T](src: Array[T], dst: Array[T], i: Int, mid: Int, j: Int, hi: Int, k: Int, before: fn(T, T) -> Bool) -> Unit =
398
+ if k < hi
399
+ if i < mid && {j >= hi || !before(src.get(j), src.get(i))}
400
+ dst.set(k, src.get(i))
401
+ mergeRun(src, dst, i + 1, mid, j, hi, k + 1, before)
402
+ else
403
+ dst.set(k, src.get(j))
404
+ mergeRun(src, dst, i, mid, j + 1, hi, k + 1, before)
405
+
272
406
  # ---- regression tests ----
273
407
 
274
408
  test "list add set remove at remove clear reverse all work correctly"
@@ -489,7 +623,6 @@ test "every method indexes from the view's start"
489
623
  v := xs.slice(1, 5)
490
624
  assert v.first()! == 1
491
625
  assert v.last()! == 7
492
- assert v.head()! == 1
493
626
  assert v.contains(5) && !v.contains(9) && !v.contains(8)
494
627
  assert v.findValue(3)! == 3
495
628
  assert v.sort(|a, b| a < b).toStr() == "[1,3,5,7]"
std/Str.plum CHANGED
@@ -6,6 +6,7 @@ import std/Int
6
6
  import std/Float
7
7
  import std/Byte
8
8
  import std/Array
9
+ import std/Option
9
10
 
10
11
  # A Str is an immutable byte sequence: an ordinary record holding a view
11
12
  # `[start, start + len)` of a packed `Array[Byte]`. Not a compiler special
@@ -22,8 +23,13 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
22
23
  fun length(self) -> Int =
23
24
  self.len
24
25
 
25
- # The raw byte value (0-255) at index `i`, unchecked (`i` must be in range).
26
+ # The raw byte value (0-255) at index `i`. Crashes with the index and the length when
27
+ # `i` is out of range (a substring never reads its source's bytes outside it).
26
28
  fun byteAt(self, i: Int) -> Int =
29
+ if i < 0 || i >= self.len then slice.outOfRange("Str.byteAt", i, self.len) else self.data.get(self.start + i).toInt()
30
+
31
+ # `byteAt` without the range check, for std's own loops whose index is proven in range.
32
+ fun byteAtUnchecked(self, i: Int) -> Int =
27
33
  self.data.get(self.start + i).toInt()
28
34
 
29
35
  # A copy that owns exactly its own bytes (no longer shares a larger source).
@@ -43,7 +49,7 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
43
49
  if i >= s.length()
44
50
  h
45
51
  else
46
- hashFrom(s, i + 1, {h ^ s.byteAt(i)} * 0x100000001b3)
52
+ hashFrom(s, i + 1, {h ^ s.byteAtUnchecked(i)} * 0x100000001b3)
47
53
 
48
54
  # The single-character substring at index `i`. (Was declared to return a
49
55
  # `Char` type, but `Char` was never actually defined anywhere in `libs/std` —
@@ -71,7 +77,7 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
71
77
  # is a misuse this can't detect and returns a meaningless answer.
72
78
  fun codePointByteLength(self, i: Int) -> Int =
73
79
  b := self.byteAt(i)
74
- if b < 0x80
80
+ n := if b < 0x80
75
81
  1
76
82
  else if b & 0xE0 == 0xC0
77
83
  2
@@ -79,6 +85,8 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
79
85
  3
80
86
  else
81
87
  4
88
+ # A character cut off by the end of the string counts only the bytes there are.
89
+ if i + n > self.len then self.len - i else n
82
90
 
83
91
  # Decodes the single Unicode codepoint (as its raw integer value) starting
84
92
  # at byte index `i`.
@@ -88,11 +96,11 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
88
96
  if n == 1
89
97
  b0
90
98
  else if n == 2
91
- {b0 & 0x1F} << 6 | {self.byteAt(i + 1) & 0x3F}
99
+ {b0 & 0x1F} << 6 | {self.byteAtUnchecked(i + 1) & 0x3F}
92
100
  else if n == 3
93
- {b0 & 0x0F} << 12 | {self.byteAt(i + 1) & 0x3F} << 6 | {self.byteAt(i + 2) & 0x3F}
101
+ {b0 & 0x0F} << 12 | {self.byteAtUnchecked(i + 1) & 0x3F} << 6 | {self.byteAtUnchecked(i + 2) & 0x3F}
94
102
  else
95
- {b0 & 0x07} << 18 | {self.byteAt(i + 1) & 0x3F} << 12 | {self.byteAt(i + 2) & 0x3F} << 6 | {self.byteAt(i + 3) & 0x3F}
103
+ {b0 & 0x07} << 18 | {self.byteAtUnchecked(i + 1) & 0x3F} << 12 | {self.byteAtUnchecked(i + 2) & 0x3F} << 6 | {self.byteAtUnchecked(i + 3) & 0x3F}
96
104
 
97
105
  # Number of Unicode CHARACTERS (codepoints) — as opposed to `length`,
98
106
  # which counts bytes and only agrees with this for pure-ASCII text.
@@ -108,13 +116,17 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
108
116
  # The `charIndex`-th Unicode character, re-encoded as its own (1-4 byte)
109
117
  # `Str`. Unlike `get` (which indexes by BYTE and can split a character in
110
118
  # half), this always returns a complete character.
119
+ # None when `charIndex` is negative or past the last character.
111
- fun runeAt(self, charIndex: Int) -> Str =
120
+ fun runeAt(self, charIndex: Int) -> Option[Str] =
121
+ if charIndex < 0
122
+ None
123
+ else
112
- i := runeStart(self, 0, charIndex)
124
+ i := runeStart(self, 0, charIndex)
113
- self.sub(i, i + self.codePointByteLength(i))
125
+ if i >= self.len then None else Some(self.sub(i, i + self.codePointByteLength(i)))
114
126
 
115
127
  # Byte index of the character `k` characters on from byte index `i`.
116
128
  fun runeStart(s: Str, i: Int, k: Int) -> Int =
117
- if k > 0
129
+ if k > 0 && i < s.len
118
130
  runeStart(s, i + s.codePointByteLength(i), k - 1)
119
131
  else
120
132
  i
@@ -235,7 +247,7 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
235
247
  buf.write(new)
236
248
  replaceFrom(s, old, new, i + old.length(), buf)
237
249
  else
238
- buf.writeByte(Byte(s.byteAt(i)))
250
+ buf.writeByte(Byte(s.byteAtUnchecked(i)))
239
251
  replaceFrom(s, old, new, i + 1, buf)
240
252
 
241
253
  # Byte index of the first occurrence of `sub`, or -1 (same as `indexOf`).
@@ -360,7 +372,7 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
360
372
  else
361
373
  cl := s.codePointByteLength(i)
362
374
  if cl == 1
363
- buf.writeByte(Byte(s.byteAt(i)))
375
+ buf.writeByte(Byte(s.byteAtUnchecked(i)))
364
376
  else
365
377
  cp := s.codePointAt(i)
366
378
  in1 := cp >= 0xC0 && cp < 0x100
@@ -408,7 +420,9 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
408
420
  # Truncates `self` to at most `length` bytes (INCLUDING the "..." suffix,
409
421
  # lodash's default `omission` string) if it's longer than `length`; returns
410
422
  # `self` unchanged otherwise. `length` too small to fit the full "..."
411
- # itself just returns as many of its leading bytes as fit.
423
+ # itself just returns as many of its leading bytes as fit. The cut backs up to the
424
+ # start of a character, so a multi-byte character is never split
425
+ # (`"aéééé".truncate(5)` is `"a..."`).
412
426
  fun truncate(self, length: Int) -> Str =
413
427
  omission := "..."
414
428
  if self.length() <= length
@@ -416,7 +430,7 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
416
430
  else if length <= omission.length()
417
431
  omission.sub(0, length)
418
432
  else
419
- self.sub(0, length - omission.length()) + omission
433
+ self.sub(0, runeBoundary(self, length - omission.length())) + omission
420
434
 
421
435
  fun unescape(self) -> Str =
422
436
  unescapeHtml(self)
@@ -479,7 +493,7 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
479
493
  fun matchBytes(s: Str, sub: Str, offset: Int, j: Int, sub_len: Int) -> Bool =
480
494
  if j >= sub_len
481
495
  true
482
- else if s.byteAt(offset + j) != sub.byteAt(j)
496
+ else if s.byteAtUnchecked(offset + j) != sub.byteAtUnchecked(j)
483
497
  false
484
498
  else
485
499
  matchBytes(s, sub, offset, j + 1, sub_len)
@@ -496,15 +510,42 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
496
510
  else
497
511
  byteToStr(0xF0 | {cp >> 18}) + byteToStr(0x80 | {{cp >> 12} & 0x3F}) + byteToStr(0x80 | {{cp >> 6} & 0x3F}) + byteToStr(0x80 | {cp & 0x3F})
498
512
 
513
+ # The largest byte index at most `i` that starts a character (or is the end): backs up
514
+ # over continuation bytes (`10xxxxxx`).
515
+ fun runeBoundary(s: Str, i: Int) -> Int =
516
+ if i > 0 && i < s.len && s.byteAtUnchecked(i) & 0xC0 == 0x80
517
+ runeBoundary(s, i - 1)
518
+ else
519
+ i
520
+
521
+ # ASCII whitespace: space, tab, newline, vertical tab, form feed, carriage return.
499
522
  fun isTrimByte(b: Int) -> Bool =
500
- b == 32 || b == 9 || b == 10 || b == 13
523
+ b == 32 || b >= 9 && b <= 13
524
+
525
+ # Unicode's White_Space characters past ASCII: U+0085, U+00A0, U+1680, U+2000..U+200A,
526
+ # U+2028, U+2029, U+202F, U+205F, U+3000.
527
+ fun isSpaceRune(cp: Int) -> Bool =
528
+ cp == 0x85 || cp == 0xA0 || cp == 0x1680 || cp >= 0x2000 && cp <= 0x200A || cp == 0x2028 || cp == 0x2029 || cp == 0x202F || cp == 0x205F || cp == 0x3000
529
+
530
+ # How many bytes of whitespace start at byte `i` (0 if none).
531
+ fun spaceAt(s: Str, i: Int) -> Int =
532
+ b := s.byteAtUnchecked(i)
533
+ if isTrimByte(b)
534
+ 1
535
+ else if b < 0xC2
536
+ 0
537
+ else if isSpaceRune(s.codePointAt(i))
538
+ s.codePointByteLength(i)
539
+ else
540
+ 0
501
541
 
502
542
  fun trimStartIndex(s: Str) -> Int =
503
543
  trimStartFrom(s, 0)
504
544
 
505
545
  fun trimStartFrom(s: Str, i: Int) -> Int =
506
- if i < s.length() && isTrimByte(s.byteAt(i))
546
+ w := if i < s.length() then spaceAt(s, i) else 0
547
+ if w > 0
507
- trimStartFrom(s, i + 1)
548
+ trimStartFrom(s, i + w)
508
549
  else
509
550
  i
510
551
 
@@ -513,10 +554,18 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
513
554
  trimEndFrom(s, s.length())
514
555
 
515
556
  fun trimEndFrom(s: Str, n: Int) -> Int =
516
- if n > 0 && isTrimByte(s.byteAt(n - 1))
517
- trimEndFrom(s, n - 1)
557
+ if n <= 0
518
- else
519
558
  n
559
+ else
560
+ b := s.byteAtUnchecked(n - 1)
561
+ if isTrimByte(b)
562
+ trimEndFrom(s, n - 1)
563
+ else if b < 0x80
564
+ n
565
+ else
566
+ # The last character: back up from its last byte to its first.
567
+ i := runeBoundary(s, n - 1)
568
+ if i + spaceAt(s, i) == n && spaceAt(s, i) > 0 then trimEndFrom(s, i) else n
520
569
 
521
570
  fun htmlEntity(b: Int) -> Str =
522
571
  match b
@@ -534,7 +583,7 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
534
583
  if i >= s.length()
535
584
  buf.toStr()
536
585
  else
537
- b := s.byteAt(i)
586
+ b := s.byteAtUnchecked(i)
538
587
  ent := htmlEntity(b)
539
588
  if ent.length() == 0
540
589
  buf.writeByte(Byte(b))
@@ -553,7 +602,7 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
553
602
  if i >= s.length()
554
603
  buf.toStr()
555
604
  else
556
- b := s.byteAt(i)
605
+ b := s.byteAtUnchecked(i)
557
606
  if isRegExpMetaByte(b)
558
607
  buf.writeByte(Byte(92))
559
608
  buf.writeByte(Byte(b))
@@ -587,9 +636,9 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
587
636
  if i >= s.length()
588
637
  buf.toStr()
589
638
  else
590
- entity := if s.byteAt(i) == 38 then unescapeEntityAt(s, i, buf) else 0
639
+ entity := if s.byteAtUnchecked(i) == 38 then unescapeEntityAt(s, i, buf) else 0
591
640
  step := if entity == 0
592
- buf.writeByte(Byte(s.byteAt(i)))
641
+ buf.writeByte(Byte(s.byteAtUnchecked(i)))
593
642
  1
594
643
  else
595
644
  entity
@@ -609,7 +658,7 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
609
658
  if i >= s.length()
610
659
  buf.toStr()
611
660
  else
612
- b := s.byteAt(i)
661
+ b := s.byteAtUnchecked(i)
613
662
  if !isWordByte(b)
614
663
  caseFrom(s, sep, mode, buf, i + 1, word_index, 0)
615
664
  else
@@ -637,7 +686,7 @@ struct Str(data: Array[Byte], start: Int, len: Int) =
637
686
  if i >= s.length()
638
687
  buf.toStr()
639
688
  else
640
- b := s.byteAt(i)
689
+ b := s.byteAtUnchecked(i)
641
690
  buf.writeByte(Byte(if upper then toUpperByte(b) else toLowerByte(b)))
642
691
  mapCaseFrom(s, upper, buf, i + 1)
643
692
 
@@ -772,7 +821,8 @@ test "runeLength of 100000 multi-byte chars"
772
821
  s := "é".repeat(100000)
773
822
  assert s.length() == 200000
774
823
  assert s.runeLength() == 100000
775
- assert s.runeAt(99999) == "é"
824
+ assert s.runeAt(99999)! == "é"
825
+ assert s.runeAt(100000).isNone() && s.runeAt(-1).isNone()
776
826
 
777
827
  test "split into 10000 parts"
778
828
  parts := "x,".repeat(10000).split(",", 0)
@@ -826,7 +876,7 @@ test "Str edge cases: empties, sub bounds, replaceAll growth, split ends, utf8 r
826
876
  assert "a,b".split("abc,b", 0).length() == 1
827
877
  assert "aé".reverse() == "éa"
828
878
  assert "日本語".reverse() == "語本日"
829
- assert "日本語".runeAt(2) == "語"
879
+ assert "日本語".runeAt(2)! == "語"
830
880
  assert " é ".trim() == "é"
831
881
  assert !"ab".startsWith("abc")
832
882
  assert !"ab".endsWith("xab")
std/game/Game.plum CHANGED
@@ -258,7 +258,7 @@ struct Game[S: Reducer[M], M](
258
258
  ctx.keepOnly(true)
259
259
  back := self.tree.withRoot(spliced(self.tree.root, applied.root, key))
260
260
  begin: Turn[S, M] := Turn(tree: back, store: self.store, restart: false, exit: false)
261
- turn := 0.until(ctx.out.length()).fold(begin, |tu, i| tu.take(ctx.out.at(i), key))
261
+ turn := ctx.out.fold(begin, |tu, c| tu.take(c, key))
262
262
  flushed := turn.store.flush(io)
263
263
  pointer := lastPointer(input.events, self.pointer)
264
264
  if turn.restart && !turn.exit
@@ -484,7 +484,7 @@ fun routeAll[M](t: SceneTree[M], ctx: Ctx[M], evs: Slice[InputEvent], i: Int, at
484
484
 
485
485
  # Where the pointer is after the events of `evs`, from `at`.
486
486
  fun lastPointer(evs: Slice[InputEvent], at: Vec2) -> Vec2 =
487
- 0.until(evs.length()).fold(at, |p, j| evs.at(j).position().unwrapOr(p))
487
+ evs.fold(at, |p, e| e.position().unwrapOr(p))
488
488
 
489
489
  # A tick's game commands taken so far: the tree and store after the messages, and whether
490
490
  # a `Restart` or an `Exit` came.
@@ -659,9 +659,9 @@ fun gonScreen(g: Game[GState, GMsg]) -> Str = match g.screenTree().root.top()
659
659
  _ => "?"
660
660
  None => "none"
661
661
 
662
- fun gcount(log: Slice[Str], prefix: Str) -> Int = 0.until(log.length()).fold(0, |n, i| if log.at(i).startsWith(prefix) then n + 1 else n)
662
+ fun gcount(log: Slice[Str], prefix: Str) -> Int = log.fold(0, |n, l| if l.startsWith(prefix) then n + 1 else n)
663
663
 
664
- fun gexact(log: Slice[Str], want: Str) -> Int = 0.until(log.length()).fold(0, |n, i| if log.at(i) == want then n + 1 else n)
664
+ fun gexact(log: Slice[Str], want: Str) -> Int = log.fold(0, |n, l| if l == want then n + 1 else n)
665
665
 
666
666
  # The ids of the actors drawn, in order, with their alphas and world x (`id@alpha@x`).
667
667
  fun gdrawn(g: Game[GState, GMsg]) -> Str =
std/game/input.plum CHANGED
@@ -232,7 +232,7 @@ struct Input(held: Held, events: Slice[InputEvent], pos: Vec2, wheel: Float) =
232
232
 
233
233
  # Went down this frame.
234
234
  fun isKeyPressed(self, key: Int) -> Bool =
235
- 0.until(self.events.length()).find(|i| self.events.at(i).isKeyDownOf(key)).isSome()
235
+ self.events.any(|e| e.isKeyDownOf(key))
236
236
 
237
237
  # The left mouse button, or a touch.
238
238
  fun isMouseDown(self) -> Bool =
@@ -251,10 +251,10 @@ struct Input(held: Held, events: Slice[InputEvent], pos: Vec2, wheel: Float) =
251
251
  Pointer(pos: self.pos, down: self.held.mouse, pressed: self.pointerPressed(), released: self.pointerReleased())
252
252
 
253
253
  fun pointerPressed(self) -> Bool =
254
- 0.until(self.events.length()).find(|i| self.events.at(i).isPointerDown()).isSome()
254
+ self.events.any(|e| e.isPointerDown())
255
255
 
256
256
  fun pointerReleased(self) -> Bool =
257
- 0.until(self.events.length()).find(|i| self.events.at(i).isPointerUp()).isSome()
257
+ self.events.any(|e| e.isPointerUp())
258
258
 
259
259
  # A game's clock and input between frames: the input not yet given to a tick (`pending`),
260
260
  # the wall time not yet ticked (`acc`), the ticks run this frame (`n`) and in all
std/os.plum CHANGED
@@ -112,11 +112,6 @@ fun chmod(io: Io, path: Str, mode: Int) -> Result[Unit, IoError] =
112
112
  else
113
113
  Ok(Unit)
114
114
 
115
- # There is no host primitive for changing file ownership (it needs a uid/gid
116
- # syscall this VM doesn't expose), unlike the permission-bits-only `chmod`.
117
- fun chown(path: Str, uid: Int, gid: Int) =
118
- todo
119
-
120
115
  fun copyFile(io: Io, src: Str, dest: Str) -> Result[Unit, IoError] =
121
116
  data := readFile(io, src)?
122
117
  writeFile(io, dest, data)
@@ -130,26 +125,12 @@ fun cp(io: Io, src: Str, dest: Str) -> Result[Unit, IoError] =
130
125
  fun lchmod(io: Io, path: Str, mode: Int) -> Result[Unit, IoError] =
131
126
  chmod(io, path, mode)
132
127
 
133
- # See `chown` — no uid/gid syscall exposed by this VM.
134
- fun lchown(path: Str, uid: Int, gid: Int) =
135
- todo
136
-
137
- # Setting a file's atime/mtime needs a syscall (`utimensat`/`SetFileTime`)
138
- # this VM doesn't expose (`std::fs` itself has no equivalent either).
139
- fun lutimes(path: Str, atime: Int, mtime: Int) =
140
- todo
141
-
142
128
  fun link(io: Io, existing_path: Str, new_path: Str) -> Result[Unit, IoError] =
143
129
  if io.rawLink(existing_path, new_path) != 1
144
130
  Err(IoFailed)
145
131
  else
146
132
  Ok(Unit)
147
133
 
148
- # Would need a real `Stat` struct type (size/mode/mtime/uid/gid/...) to
149
- # return anything useful — no such type exists in the stdlib yet.
150
- fun lstat(path: Str) =
151
- todo
152
-
153
134
  # Creates a fresh directory named `prefix` followed by a random suffix,
154
135
  # retrying on the (astronomically unlikely) chance of a collision, and
155
136
  # returns the path actually created.
@@ -161,16 +142,6 @@ fun mkdtemp(io: Io, prefix: Str) -> Result[Str, IoError] =
161
142
  mkdir(io, path)?
162
143
  Ok(path)
163
144
 
164
- # Would need a host-side open-file-descriptor table (this VM's other file
165
- # ops are all one-shot: open+read/write+close in a single host call) plus a
166
- # `File` handle type — neither exists yet.
167
- fun open(path: Str, flags: Int) =
168
- todo
169
-
170
- # See `open` — same missing handle-table/type problem, for directories.
171
- fun opendir(path: Str) =
172
- todo
173
-
174
145
  # The names of `path`'s directory entries (not full paths).
175
146
  fun readdir(io: Io, path: Str) -> Result[Slice[Str], IoError] =
176
147
  if !exists(io, path)
@@ -217,14 +188,6 @@ fun rmdir(io: Io, path: Str) -> Result[Unit, IoError] =
217
188
  else
218
189
  Ok(Unit)
219
190
 
220
- # See `lstat` — needs a `Stat` struct type.
221
- fun stat(path: Str) =
222
- todo
223
-
224
- # Needs a filesystem-info struct type, same gap as `stat`.
225
- fun statfs(path: Str) =
226
- todo
227
-
228
191
  fun symlink(io: Io, target: Str, path: Str) -> Result[Unit, IoError] =
229
192
  if io.rawSymlink(target, path) != 1
230
193
  Err(IoFailed)
@@ -242,16 +205,6 @@ fun truncate(io: Io, path: Str, len: Int) -> Result[Unit, IoError] =
242
205
  else
243
206
  Ok(Unit)
244
207
 
245
- # See `lutimes` — same missing syscall.
246
- fun utimes(path: Str, atime: Int, mtime: Int) =
247
- todo
248
-
249
- # Would need an async/callback mechanism to deliver filesystem change events
250
- # into a running Plum program — nothing like that exists in this VM (every
251
- # host call here is a synchronous, one-shot request/response).
252
- fun watch(filename: Str) =
253
- todo
254
-
255
208
  test "writeFile/readFile/appendFile/remove round-trip on a real file"
256
209
  dir := mkdtemp(io, "/tmp/plum_os_test_")!
257
210
  path := dir + "/a.txt"
tests/std/collections.plum ADDED
@@ -0,0 +1,149 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Str
4
+ import std/Option
5
+ import std/List
6
+ import std/Slice
7
+ import std/Array
8
+ import std/Map
9
+ import std/Set
10
+ import std/Deque
11
+ import std/Heap
12
+
13
+ struct Rec(k: Int, tag: Int)
14
+
15
+ fun countdown(n: Int) -> Slice[Int] =
16
+ xs := Slice[Int]()
17
+ for i := range n
18
+ xs.push(n - i)
19
+ xs
20
+
21
+ fun sortedOk(xs: Slice[Int]) -> Bool =
22
+ 0.until(xs.length() - 1).fold(true, |ok, i| ok && xs.at(i) <= xs.at(i + 1))
23
+
24
+ test "List.toArray of 200000 elements is sized once and keeps the order"
25
+ nil: List[Int] := Nil
26
+ xs := 1.to(200000).fold(nil, |acc, i| Cons(head: i, tail: acc))
27
+ a := xs.toArray()
28
+ assert a.length() == 200000
29
+ assert a.get(0) == 200000 && a.get(199999) == 1
30
+ e: List[Str] := Nil
31
+ assert e.toArray().length() == 0
32
+ assert ["a", "b"].toArray().get(1) == "b"
33
+
34
+ test "sort: 100000 reversed, sorted, equal and empty inputs"
35
+ big := countdown(100000).sort(|a, b| a < b)
36
+ assert big.length() == 100000
37
+ assert big.at(0) == 1 && big.at(99999) == 100000
38
+ assert sortedOk(big)
39
+ assert sortedOk(big.sort(|a, b| a < b))
40
+ assert Slice[Int]().sort(|a, b| a < b).length() == 0
41
+ one := Slice[Int]()
42
+ one.push(5)
43
+ assert one.sort(|a, b| a < b).toStr() == "[5]"
44
+ for n := range 40
45
+ xs := Slice[Int]()
46
+ for i := range n
47
+ xs.push({i * 7919} % 13)
48
+ assert sortedOk(xs.sort(|a, b| a < b))
49
+ assert xs.sort(|a, b| a < b).length() == n
50
+
51
+ test "sort is stable: equal keys keep their order, across merged runs"
52
+ xs := Slice[Rec]()
53
+ for i := range 1000
54
+ xs.push(Rec(k: {i * 31} % 7, tag: i))
55
+ s := xs.sort(|a, b| a.k < b.k)
56
+ ok := 0.until(999).fold(true, |acc, i|
57
+ a := s.at(i)
58
+ b := s.at(i + 1)
59
+ acc && {a.k < b.k || a.k == b.k && a.tag < b.tag}
60
+ )
61
+ assert ok
62
+
63
+ test "sort leaves the receiver and its views as they were"
64
+ xs := countdown(50)
65
+ v := xs.slice(10, 40)
66
+ s := v.sort(|a, b| a < b)
67
+ assert s.at(0) == 11 && s.at(29) == 40
68
+ assert v.at(0) == 40 && xs.at(0) == 50
69
+
70
+ test "Slice fold, each, map, filter, find, any, all, isEmpty"
71
+ xs := countdown(10)
72
+ assert xs.fold(0, |a, x| a + x) == 55
73
+ assert xs.map(|x| x * 2).at(0) == 20
74
+ assert xs.map(|x| "{x}").join("") == "10987654321"
75
+ assert xs.filter(|x| x % 2 == 0).toStr() == "[10,8,6,4,2]"
76
+ assert xs.find(|x| x < 4)! == 3
77
+ assert xs.find(|x| x > 100).isNone()
78
+ assert xs.any(|x| x == 7) && !xs.any(|x| x == 70)
79
+ assert xs.all(|x| x > 0) && !xs.all(|x| x > 1)
80
+ assert Slice[Int]().all(|x| false) && !Slice[Int]().any(|x| true)
81
+ assert Slice[Int]().isEmpty() && !xs.isEmpty()
82
+ seen := Slice[Int]()
83
+ xs.slice(2, 5).each(|x| seen.push(x))
84
+ assert seen.toStr() == "[8,7,6]"
85
+ assert xs.slice(2, 5).fold(0, |a, x| a + x) == 21
86
+
87
+ test "find stops at the first hit"
88
+ xs := countdown(1000)
89
+ calls := Array.filled(1, 0)
90
+ found := xs.find(|x|
91
+ calls.set(0, calls.get(0) + 1)
92
+ x == 998
93
+ )
94
+ assert found! == 998 && calls.get(0) == 3
95
+
96
+ test "groupBy keeps each group in order and the groups by first key"
97
+ words := ["bb", "a", "cc", "ddd", "e"].toSlice()
98
+ g := words.groupBy(|w| w.length())
99
+ assert g.length() == 3
100
+ assert g.get(2)!.join(",") == "bb,cc"
101
+ assert g.get(1)!.join(",") == "a,e"
102
+ assert g.keys().toStr() == "[2,1,3]"
103
+ assert Slice[Int]().groupBy(|x| x).isEmpty()
104
+
105
+ test "Map[K, V]() is an empty map, like Slice[T]() and Set[T]()"
106
+ m := Map[Str, Int]()
107
+ assert m.isEmpty()
108
+ m.set("a", 1)
109
+ assert m.get("a")! == 1
110
+ n := Map[Int, Slice[Int]]()
111
+ assert n.length() == 0
112
+
113
+ test "Set.toSlice gives the members in insertion order"
114
+ s := Set[Int]()
115
+ s.add(3)
116
+ s.add(1)
117
+ s.add(3)
118
+ assert s.toSlice().toStr() == "[3,1]"
119
+
120
+ test "Heap.by and Heap.byKey"
121
+ h: Heap[Int] := Heap.by(|a, b| a < b)
122
+ for i := range 500
123
+ h.push({i * 7919} % 1009)
124
+ prev := Array.filled(1, -1)
125
+ for _ := range 500
126
+ v := h.pop()!
127
+ assert v >= prev.get(0)
128
+ prev.set(0, v)
129
+ assert h.isEmpty() && h.pop().isNone()
130
+ r: Heap[Rec] := Heap.byKey(|r| r.k)
131
+ r.push(Rec(k: 3, tag: 0))
132
+ r.push(Rec(k: 1, tag: 1))
133
+ r.push(Rec(k: 2, tag: 2))
134
+ assert r.peek()!.tag == 1
135
+ assert r.pop()!.tag == 1 && r.pop()!.tag == 2 && r.pop()!.tag == 0
136
+
137
+ test "bounds: get is None out of range, and in-range at still reads"
138
+ xs := countdown(3)
139
+ _ := xs.pop()
140
+ assert xs.get(2).isNone() && xs.get(-1).isNone()
141
+ assert xs.at(1) == 2
142
+ v := xs.slice(1, 2)
143
+ assert v.get(-1).isNone() && v.get(1).isNone() && v.at(0) == 2
144
+ d := Deque[Int]()
145
+ d.pushBack(1)
146
+ d.pushFront(0)
147
+ assert d.at(0) == 0 && d.at(1) == 1 && d.get(2).isNone()
148
+ assert "abc".byteAt(2) == 99
149
+ assert "abc".sub(1, 2).byteAt(0) == 98
tests/std/text.plum ADDED
@@ -0,0 +1,38 @@
1
+ import std/Int
2
+ import std/Str
3
+ import std/Option
4
+ import std/Slice
5
+
6
+ test "truncate backs up to a character boundary"
7
+ t := "aéééé".truncate(5)
8
+ assert t == "a..."
9
+ assert t.runeLength() == 4
10
+ assert "aéééé".truncate(6) == "aé..."
11
+ assert "日本語です".truncate(7) == "日..."
12
+ assert "abcdef".truncate(5) == "ab..."
13
+ assert "abc".truncate(5) == "abc"
14
+
15
+ test "runeAt is None out of range"
16
+ assert "ab".runeAt(5).isNone()
17
+ assert "ab".runeAt(2).isNone()
18
+ assert "ab".runeAt(-1).isNone()
19
+ assert "aé".runeAt(1)! == "é"
20
+ assert "".runeAt(0).isNone()
21
+
22
+ test "trim strips ASCII and Unicode whitespace"
23
+ assert " plum ".trim() == "plum"
24
+ assert "\t\n\r\u000B\u000Cplum\u000C".trim() == "plum"
25
+ assert "  plum  ".trim() == "plum"
26
+ assert "
x
".trimStart() == "x
"
27
+ assert "
x
".trimEnd() == "
x"
28
+ assert "é ".trim() == "é"
29
+ assert " ".trim() == ""
30
+ assert " ".trim() == ""
31
+ assert "xé".trimEnd() == "xé"
32
+ assert "日本".trim() == "日本"
33
+
34
+ test "a cut-off character at the end counts only its bytes"
35
+ s := "aé".sub(0, 2)
36
+ assert s.length() == 2
37
+ assert s.runeLength() == 2
38
+ assert s.codePointByteLength(1) == 1