plum

#treesitter#compiler#wasm

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

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


314d861 — Peter John 2026-11-09T02:36:52+05:30
std/game_enum_tree: the persistent scene tree in the branch's language
std/game_enum_tree/EBody.plum ADDED
@@ -0,0 +1,148 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Bool
6
+ import std/math
7
+ import std/Io
8
+ import std/game/Vec2
9
+ import std/game/Affine
10
+ import std/game/Color
11
+ import std/game/gfx
12
+ import std/game_enum_tree/ECtx
13
+
14
+ # A plain body for a persistent scene tree (`ETree[EBody]` in an `EStage[EBody]`): the
15
+ # transform, size, colour and flags of master's std/game_enum_tree `EBody`, with no
16
+ # behaviour. A body with a size paints a filled rectangle; one without (a group) paints
17
+ # nothing and is never hit.
18
+ #
19
+ # The branch has no inheritance, so a game with behaviour defines its own body type and
20
+ # the stage is generic over it. Any type with these methods can be the stage's `T`:
21
+ #
22
+ # key(self) -> Int # its id: how kills, spawns and updates find it
23
+ # gone(self) -> Bool # dead: its parent drops it with its subtree
24
+ # shown(self) -> Bool # drawn and hit: visible and not dead
25
+ # local(self) -> Affine # into its parent's coordinates (`ebody.localOf`)
26
+ # opacity(self) -> Float # its alpha, multiplied down the tree
27
+ # hit(self, p: Vec2) -> Bool # `p` in its own coordinates is inside it
28
+ # step(self, ctx: ECtx[T], dt: Float) -> T # its next version (itself if unchanged)
29
+ # paint(self, io: Io, m: Affine, alpha: Float)
30
+ #
31
+ # An enum of kinds that each hold an `EBody` (`| Walker(body: EBody, speed: Float)`), or
32
+ # one struct with the fields a game needs, both work; std/game_enum_tree's tests use the
33
+ # first, benchmarks/scene_trees the second. A body is a value: nothing changes it after
34
+ # it is built, and a step makes its next version with a spread, which the compiler writes
35
+ # in place when nothing else holds the old one.
36
+ struct EBody(
37
+ id: Int,
38
+ x: Float, y: Float, width: Float, height: Float,
39
+ originX: Float, originY: Float,
40
+ scaleX: Float, scaleY: Float,
41
+ rotation: Float,
42
+ color: Color,
43
+ visible: Bool,
44
+ dead: Bool) =
45
+
46
+ # A group at (x, y), unscaled and unrotated: no size, paints nothing.
47
+ fun group(id: Int, x: Float, y: Float) -> EBody =
48
+ EBody(
49
+ id: id, x: x, y: y, width: 0.0, height: 0.0, originX: 0.0, originY: 0.0,
50
+ scaleX: 1.0, scaleY: 1.0, rotation: 0.0, color: Color.White, visible: true, dead: false)
51
+
52
+ # A group at (x, y), scaled by `s` and turned by `r` radians about its own (0, 0).
53
+ fun turned(id: Int, x: Float, y: Float, s: Float, r: Float) -> EBody =
54
+ EBody(
55
+ id: id, x: x, y: y, width: 0.0, height: 0.0, originX: 0.0, originY: 0.0,
56
+ scaleX: s, scaleY: s, rotation: r, color: Color.White, visible: true, dead: false)
57
+
58
+ # A `w` by `h` rectangle with its top-left at (x, y).
59
+ fun rect(id: Int, x: Float, y: Float, w: Float, h: Float, c: Color) -> EBody =
60
+ EBody(
61
+ id: id, x: x, y: y, width: w, height: h, originX: 0.0, originY: 0.0,
62
+ scaleX: 1.0, scaleY: 1.0, rotation: 0.0, color: c, visible: true, dead: false)
63
+
64
+ fun key(self) -> Int = self.id
65
+
66
+ fun gone(self) -> Bool = self.dead
67
+
68
+ # Whether this body and its subtree are drawn and hit: visible and not dead.
69
+ fun shown(self) -> Bool = self.visible && !self.dead
70
+
71
+ fun opacity(self) -> Float = self.color.a
72
+
73
+ # The transform into the parent's coordinates: translate to the position, rotate and
74
+ # scale about the origin.
75
+ fun local(self) -> Affine =
76
+ localOf(self.x, self.y, self.originX, self.originY, self.scaleX, self.scaleY, self.rotation)
77
+
78
+ # Whether `p`, a point in this body's own coordinates, is inside its width by height box.
79
+ fun hit(self, p: Vec2) -> Bool = hitBox(self.width, self.height, p)
80
+
81
+ # A plain body doesn't change.
82
+ fun step(self, ctx: ECtx[EBody], dt: Float) -> EBody = self
83
+
84
+ fun paint(self, io: Io, m: Affine, alpha: Float) =
85
+ if self.width > 0.0 && self.height > 0.0
86
+ paintBox(io, m, alpha, self.width, self.height, self.color)
87
+
88
+ # Copies with one thing changed.
89
+
90
+ fun at(self, x: Float, y: Float) -> EBody = EBody(..self, x: x, y: y)
91
+
92
+ fun moveBy(self, dx: Float, dy: Float) -> EBody = EBody(..self, x: self.x + dx, y: self.y + dy)
93
+
94
+ fun rotateTo(self, r: Float) -> EBody = EBody(..self, rotation: r)
95
+
96
+ fun scaleTo(self, sx: Float, sy: Float) -> EBody = EBody(..self, scaleX: sx, scaleY: sy)
97
+
98
+ # Its rotation and scale about (ox, oy), in its own coordinates.
99
+ fun pivotAt(self, ox: Float, oy: Float) -> EBody = EBody(..self, originX: ox, originY: oy)
100
+
101
+ fun tint(self, c: Color) -> EBody = EBody(..self, color: c)
102
+
103
+ fun withVisible(self, v: Bool) -> EBody = EBody(..self, visible: v)
104
+
105
+ # Dead: returned from `step`, its parent drops it with its subtree.
106
+ fun killed(self) -> EBody = EBody(..self, dead: true)
107
+
108
+ # The transform of a body at (x, y) with its origin, scale and rotation (master's
109
+ # `Actor.local`): translate to the position, rotate and scale about the origin.
110
+ fun localOf(x: Float, y: Float, originX: Float, originY: Float, scaleX: Float, scaleY: Float, rotation: Float) -> Affine =
111
+ cs := math.cos(rotation)
112
+ sn := math.sin(rotation)
113
+ a := cs * scaleX
114
+ b := sn * scaleX
115
+ c := 0.0 - sn * scaleY
116
+ d := cs * scaleY
117
+ Affine(
118
+ a: a, b: b, c: c, d: d,
119
+ e: x + originX - {a * originX + c * originY},
120
+ f: y + originY - {b * originX + d * originY})
121
+
122
+ # Whether `p` is inside a `w` by `h` box at (0, 0); a box with no size is never hit.
123
+ fun hitBox(w: Float, h: Float, p: Vec2) -> Bool =
124
+ w > 0.0 && h > 0.0 && p.x >= 0.0 && p.x <= w && p.y >= 0.0 && p.y <= h
125
+
126
+ # A `w` by `h` box at (0, 0) seen through `m`, filled with `c` at `alpha`.
127
+ fun paintBox(io: Io, m: Affine, alpha: Float, w: Float, h: Float, c: Color) =
128
+ sx := w * m.scaleX()
129
+ sy := h * m.scaleY()
130
+ p := m.apply(Vec2(x: w / 2.0, y: h / 2.0))
131
+ gfx.drawRect(io, p.x - sx / 2.0, p.y - sy / 2.0, sx, sy, c.withAlpha(c.a * alpha))
132
+
133
+ test "a rect body is its size and hides when it is dead"
134
+ r := EBody.rect(7, 1.0, 2.0, 4.0, 3.0, Color.Red)
135
+ assert r.width == 4.0 && r.height == 3.0 && r.key() == 7
136
+ assert r.shown()
137
+ assert !r.killed().shown()
138
+ assert !r.withVisible(false).shown()
139
+ assert r.moveBy(1.0, 2.0).x == 2.0
140
+ assert r.hit(Vec2(x: 2.0, y: 1.0))
141
+ assert !EBody.group(1, 0.0, 0.0).hit(Vec2(x: 0.0, y: 0.0))
142
+
143
+ test "local translates, then turns and scales about the origin"
144
+ b := EBody.turned(1, 10.0, 20.0, 2.0, 0.0).pivotAt(1.0, 1.0)
145
+ p := b.local().apply(Vec2(x: 1.0, y: 1.0))
146
+ assert p.x == 11.0 && p.y == 21.0
147
+ q := b.local().apply(Vec2(x: 2.0, y: 1.0))
148
+ assert q.x == 13.0 && q.y == 21.0
std/game_enum_tree/ECtx.plum ADDED
@@ -0,0 +1,57 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Slice
6
+ import std/game/Affine
7
+ import std/game_enum_tree/ETree
8
+
9
+ # What a step changes besides the bodies, applied once the step's walk is over
10
+ # (`EStage.apply`): a new node under the body `parent` (by id), on top of its children, or
11
+ # the end of the body `id` and its subtree.
12
+ enum ECmd[T] =
13
+ | ESpawn(parent: Int, node: ETree[T])
14
+ | EKill(id: Int)
15
+
16
+ # What the step hands each body in place of a parent link: the context of the body's
17
+ # parent. `up` is the parent's world transform and `alpha` its accumulated opacity, so a
18
+ # body's own world transform is `ctx.worldOf(self.local())` and its alpha
19
+ # `ctx.alphaOf(self.opacity())`, computed only when it asks. `out` takes the commands a
20
+ # body pushes for after the walk (`ctx.out.push(ESpawn(..))`, `ctx.out.push(EKill(..))`).
21
+ #
22
+ # fun step(self, ctx: ECtx[Body], dt: Float) -> Body =
23
+ # ctx.out.push(ESpawn(parent: 0, node: etree.leaf(Bullet(..))))
24
+ # Ship(..self, x: self.x + self.vx * dt)
25
+ #
26
+ # A context is a value. The walk makes one for each parent with children (`under`), with
27
+ # one multiply, and hands it to every child: the lazy world transform of master's `ECtx`
28
+ # without the cached field and the `retarget` that master needs to reuse one context.
29
+ #
30
+ # Master's context also carries the game's dispatcher (`actions`); the branch's game
31
+ # library has none, so this one doesn't.
32
+ struct ECtx[T](up: Affine, alpha: Float, out: Slice[ECmd[T]]) =
33
+
34
+ # The context above a stage's root: the identity transform, full opacity, no commands.
35
+ fun init() -> ECtx[T] =
36
+ ECtx(up: Affine.Identity, alpha: 1.0, out: Slice[ECmd[T]]())
37
+
38
+ # The world transform of a child whose own transform is `local`.
39
+ fun worldOf(self, local: Affine) -> Affine = self.up.mul(local)
40
+
41
+ # The accumulated alpha of a child whose own is `a`.
42
+ fun alphaOf(self, a: Float) -> Float = self.alpha * a
43
+
44
+ # The context for the children of a child with the transform `local` and opacity `a`:
45
+ # the same commands, the child's world transform above them.
46
+ fun under(self, local: Affine, a: Float) -> ECtx[T] =
47
+ ECtx(up: self.up.mul(local), alpha: self.alpha * a, out: self.out)
48
+
49
+ test "under multiplies the child's transform into the parent's"
50
+ c := ECtx[Int]()
51
+ m := Affine(a: 2.0, b: 0.0, c: 0.0, d: 2.0, e: 1.0, f: 0.0)
52
+ u := c.under(m, 0.5).under(m, 0.5)
53
+ assert u.up.a == 4.0 && u.up.e == 3.0
54
+ assert u.alpha == 0.25
55
+ assert u.worldOf(m).e == 7.0
56
+ u.out.push(EKill(id: 3))
57
+ assert c.out.length() == 1
std/game_enum_tree/EStage.plum ADDED
@@ -0,0 +1,555 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Bool
6
+ import std/Str
7
+ import std/Option
8
+ import std/List
9
+ import std/Slice
10
+ import std/Array
11
+ import std/Map
12
+ import std/Set
13
+ import std/math
14
+ import std/Io
15
+ import std/game/Vec2
16
+ import std/game/Affine
17
+ import std/game/Color
18
+ import std/game/gfx
19
+ import std/game_enum_tree/ETree
20
+ import std/game_enum_tree/EBody
21
+ import std/game_enum_tree/ECtx
22
+
23
+ # A persistent scene tree: master's std/game_enum_tree `EStage`, generic over the body
24
+ # type `T` (see std/game_enum_tree/EBody for the methods a body needs). The root is an
25
+ # `ETree[T]`, a left-child, right-sibling tree of bodies, and a stage is a value: every
26
+ # change returns a new stage. While something holds the old stage it stays as it was, a
27
+ # snapshot; when nothing does, the compiler reuses its cells for the new one.
28
+ #
29
+ # s := EStage.of(EBody.group(0, 0.0, 0.0)) # a root group, id 0
30
+ # s2 := s.add(0, etree.leaf(EBody.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
31
+ # ctx := ECtx[EBody]()
32
+ # s3 := s2.step(ctx, dt) # every body's next version, then the commands in ctx.out
33
+ # s3.draw(io)
34
+ #
35
+ # Bodies are referred to by `key()`: `add(parent, n)`, `update(id, f)`, `find(id)`,
36
+ # `kill(id)`, `ESpawn(parent, n)`, `EKill(id)`. Each finds its body by searching down from
37
+ # the root, O(n); `step` applies all of a tick's commands in its own walk.
38
+ #
39
+ # Children are kept in draw order: a parent is drawn before its children, and siblings
40
+ # first to last. Hit testing goes the other way, topmost first: children before their
41
+ # parent, later siblings before earlier ones.
42
+ #
43
+ # Unlike master's, the walks (`step`, `apply`) rebuild every link node they pass instead
44
+ # of returning an unchanged chain as it was: sharing needs the old node after the match,
45
+ # and that use would stop the compiler from writing the new node into the old one's cell.
46
+ # A step over a stage nothing else holds therefore allocates no link nodes at all, and
47
+ # one over a kept stage copies all of them.
48
+ struct EStage[T](root: ETree[T], camX: Float, camY: Float, camScale: Float) =
49
+
50
+ # A stage whose root is the body `top`.
51
+ fun of(top: T) -> EStage[T] =
52
+ EStage(root: etree.leaf(top), camX: 0.0, camY: 0.0, camScale: 1.0)
53
+
54
+ # The same camera over another tree.
55
+ fun withRoot(self, r: ETree[T]) -> EStage[T] = EStage(..self, root: r)
56
+
57
+ fun pan(self, x: Float, y: Float) -> EStage[T] = EStage(..self, camX: x, camY: y)
58
+
59
+ fun zoom(self, s: Float) -> EStage[T] = EStage(..self, camScale: s)
60
+
61
+ # The number of bodies.
62
+ fun count(self) -> Int = self.root.count()
63
+
64
+ # The body with this id, if any.
65
+ fun find(self, id: Int) -> Option[T] = self.root.find(|b| b.key() == id)
66
+
67
+ # The stage with `n` added as the last child of the body `parent`; unchanged if there is
68
+ # no such body.
69
+ fun add(self, parent: Int, n: ETree[T]) -> EStage[T] =
70
+ self.withRoot(self.root.replace(|b| b.key() == parent, |p| p.addChild(n)))
71
+
72
+ # The stage with the body `id` replaced by `f(body)`; everything off its path is shared.
73
+ fun update(self, id: Int, f: fn(T) -> T) -> EStage[T] =
74
+ self.withRoot(self.root.update(|b| b.key() == id, f))
75
+
76
+ # The stage without the body `id` and its subtree.
77
+ fun kill(self, id: Int) -> EStage[T] = self.withRoot(self.root.filter(|b| b.key() != id))
78
+
79
+ # The next tick: every live body's `step`, parents before children, siblings in order,
80
+ # each given its parent's context under `ctx` (the context above the root). A body that
81
+ # returns a dead version is dropped with its subtree. Every command in `ctx.out` takes
82
+ # effect after the step, as `apply` would apply it, and `ctx.out` is left empty. Those
83
+ # pushed before the step are applied in its own walk: a body killed this way is dropped
84
+ # without its `step`, and a spawned node goes on top of its parent's children
85
+ # unstepped. Those pushed during the step (by the bodies) are applied by `apply` once
86
+ # the walk is over, as a second batch.
87
+ fun step(self, ctx: ECtx[T], dt: Float) -> EStage[T] =
88
+ w := EWalk.of(ctx.out)
89
+ ctx.out.clear()
90
+ empty: ETree[T] := EEmpty
91
+ r := estep(self.root, ctx, dt, w, empty)
92
+ s := EStage(..self, root: r).apply(ctx.out)
93
+ ctx.out.clear()
94
+ s
95
+
96
+ # The stage with the commands applied, in one pass over the tree: every `EKill` body
97
+ # goes with its subtree, and every `ESpawn` node goes on top of its parent's children,
98
+ # in the order pushed. A spawn whose parent is not on the stage, or is killed by the
99
+ # same batch, is dropped.
100
+ fun apply(self, cmds: Slice[ECmd[T]]) -> EStage[T] =
101
+ if cmds.length() == 0
102
+ self
103
+ else
104
+ w := EWalk.of(cmds)
105
+ empty: ETree[T] := EEmpty
106
+ EStage(..self, root: eapply(self.root, w, empty))
107
+
108
+ # What `draw` would draw, in order: each shown body with its stage transform and alpha,
109
+ # a parent before its children, siblings first to last.
110
+ fun flatten(self) -> Slice[EDrawn[T]] =
111
+ out := Slice[EDrawn[T]]()
112
+ ecollect(self.root, Affine.Identity, 1.0, out)
113
+ out
114
+
115
+ # The topmost shown body at a stage point.
116
+ fun hit(self, x: Float, y: Float) -> Option[T] = ehit(self.root, Vec2(x: x, y: y))
117
+
118
+ fun draw(self, io: Io) =
119
+ gfx.setCamera(io, self.camX, self.camY, self.camScale)
120
+ edraw(self.root, io, Affine.Identity, 1.0)
121
+ gfx.resetCamera(io)
122
+
123
+ # One entry of the draw list: a shown body, its stage transform and its alpha.
124
+ struct EDrawn[T](body: T, m: Affine, alpha: Float)
125
+
126
+ # The largest id range the bitsets cover is [0, 2^22).
127
+ BitsCap = 4194304
128
+
129
+ # The largest id seen in a batch, and whether all of them fit the bitsets.
130
+ struct EScan(mut top: Int, mut ok: Bool) =
131
+ fun see(self, id: Int) =
132
+ if id < 0 || id >= BitsCap
133
+ self.ok = false
134
+ else if id > self.top
135
+ self.top = id
136
+
137
+ # A batch of commands as a walk uses them: the ids to drop, and the nodes to add under
138
+ # each parent id, in the order pushed. The walk asks about every body, so beside the set
139
+ # and the map it keeps a bitset of each (one bit per id up to the batch's largest): most
140
+ # answers are a shift and a mask, and only a body with spawns does a hash lookup. Ids
141
+ # below 0 or from 2^22 up make that batch use the set and the map alone.
142
+ struct EWalk[T](
143
+ kills: Set[Int], spawns: Map[Int, Slice[ETree[T]]],
144
+ hasKills: Bool, hasSpawns: Bool,
145
+ bitsOk: Bool, killBits: Array[Int], spawnBits: Array[Int]) =
146
+
147
+ fun of(cmds: Slice[ECmd[T]]) -> EWalk[T] =
148
+ kills := Set[Int]()
149
+ spawns: Map[Int, Slice[ETree[T]]] := Map.empty()
150
+ scan := EScan(top: 0, ok: true)
151
+ for c := range cmds
152
+ match c
153
+ EKill(id) =>
154
+ kills.add(id)
155
+ scan.see(id)
156
+ ESpawn(parent, node) =>
157
+ scan.see(parent)
158
+ if Some(xs) := spawns.get(parent)
159
+ xs.push(node)
160
+ else
161
+ ys := Slice[ETree[T]]()
162
+ ys.push(node)
163
+ spawns.set(parent, ys)
164
+ words := if scan.ok && cmds.length() > 0 then scan.top / 64 + 1 else 0
165
+ killBits := Array[Int]().resize(words)
166
+ spawnBits := Array[Int]().resize(words)
167
+ if words > 0
168
+ for c := range cmds
169
+ match c
170
+ EKill(id) => ewalkSet(killBits, id)
171
+ ESpawn(parent, _) => ewalkSet(spawnBits, parent)
172
+ EWalk(
173
+ kills: kills, spawns: spawns,
174
+ hasKills: kills.length() > 0, hasSpawns: spawns.length() > 0,
175
+ bitsOk: scan.ok, killBits: killBits, spawnBits: spawnBits)
176
+
177
+ # Whether the body `id` is killed by this batch.
178
+ fun killed(self, id: Int) -> Bool =
179
+ if !self.hasKills
180
+ false
181
+ else if self.bitsOk
182
+ ewalkHas(self.killBits, id)
183
+ else
184
+ self.kills.has(id)
185
+
186
+ # The nodes to add under the body `id`, as a chain in the order pushed (empty if none).
187
+ fun spawnsUnder(self, id: Int) -> ETree[T] =
188
+ if !self.hasSpawns || {self.bitsOk && !ewalkHas(self.spawnBits, id)}
189
+ EEmpty
190
+ else
191
+ match self.spawns.get(id)
192
+ Some(xs) => etree.etreeChainFrom(xs, 0)
193
+ None => EEmpty
194
+
195
+ fun ewalkSet(bits: Array[Int], id: Int) =
196
+ w := id / 64
197
+ bits.set(w, bits.get(w) | {1 << {id % 64}})
198
+
199
+ fun ewalkHas(bits: Array[Int], id: Int) -> Bool =
200
+ w := id / 64
201
+ if id < 0 || w >= bits.length() then false else {{bits.get(w) >> {id % 64}} & 1} == 1
202
+
203
+ # The chain `t` one step on, under `ctx` (the context of the chain's parent), without the
204
+ # bodies `w` kills, and followed by `extra` (the parent's spawns, unstepped). A body with
205
+ # children (or spawns) gets one context for them, made from its transform before its
206
+ # step. Every kept node is rebuilt: in place when nothing else holds `t`.
207
+ fun estep[T](t: ETree[T], ctx: ECtx[T], dt: Float, w: EWalk[T], extra: ETree[T]) -> ETree[T] = match t
208
+ EEmpty => extra
209
+ ENode(b, k, n) =>
210
+ if b.gone() || {w.hasKills && w.killed(b.key())}
211
+ estep(n, ctx, dt, w, extra)
212
+ else
213
+ xs := if w.hasSpawns then w.spawnsUnder(b.key()) else EEmpty
214
+ walkKids := !k.isEmpty() || !xs.isEmpty()
215
+ cc := if walkKids then ctx.under(b.local(), b.opacity()) else ctx
216
+ nb := b.step(ctx, dt)
217
+ if nb.gone()
218
+ estep(n, ctx, dt, w, extra)
219
+ else
220
+ k2 := if walkKids then estep(k, cc, dt, w, xs) else k
221
+ ENode(value: nb, firstChild: k2, nextSibling: estep(n, ctx, dt, w, extra))
222
+
223
+ # The chain `t` without the bodies `w` kills and followed by `extra`, with the same done
224
+ # in every subtree: `apply`'s walk.
225
+ fun eapply[T](t: ETree[T], w: EWalk[T], extra: ETree[T]) -> ETree[T] = match t
226
+ EEmpty => extra
227
+ ENode(b, k, n) =>
228
+ if w.killed(b.key())
229
+ eapply(n, w, extra)
230
+ else
231
+ xs := w.spawnsUnder(b.key())
232
+ k2 := if k.isEmpty() && xs.isEmpty() then k else eapply(k, w, xs)
233
+ ENode(value: b, firstChild: k2, nextSibling: eapply(n, w, extra))
234
+
235
+ fun ecollect[T](t: ETree[T], parent: Affine, alpha: Float, out: Slice[EDrawn[T]]) =
236
+ if ENode(b, k, n) := t
237
+ if b.shown()
238
+ m := parent.mul(b.local())
239
+ a := alpha * b.opacity()
240
+ out.push(EDrawn(body: b, m: m, alpha: a))
241
+ ecollect(k, m, a, out)
242
+ ecollect(n, parent, alpha, out)
243
+
244
+ fun edraw[T](t: ETree[T], io: Io, parent: Affine, alpha: Float) =
245
+ if ENode(b, k, n) := t
246
+ if b.shown()
247
+ m := parent.mul(b.local())
248
+ a := alpha * b.opacity()
249
+ b.paint(io, m, a)
250
+ edraw(k, io, m, a)
251
+ edraw(n, io, parent, alpha)
252
+
253
+ # The topmost shown body under `p` (a point in the chain's parent's coordinates): later
254
+ # siblings first, and in each, its children before itself.
255
+ fun ehit[T](t: ETree[T], p: Vec2) -> Option[T] = match t
256
+ EEmpty => None
257
+ ENode(b, k, n) =>
258
+ match ehit(n, p)
259
+ Some(found) => Some(found)
260
+ None =>
261
+ if b.shown()
262
+ q := b.local().inverse().apply(p)
263
+ match ehit(k, q)
264
+ Some(found) => Some(found)
265
+ None => if b.hit(q) then Some(b) else None
266
+ else
267
+ None
268
+
269
+ # --- tests ---
270
+
271
+ # A body for the tests: a plain one, or one of four kinds with behaviour, each around an
272
+ # `EBody`.
273
+ enum TBody =
274
+ | TPlain(body: EBody)
275
+ # moves by vx per second; dies when `ttl` runs out (never if it starts at -1)
276
+ | TDrifter(body: EBody, vx: Float, ttl: Int)
277
+ # spawns a drifter under the root (id 0) each step, with ids from `next` on
278
+ | TSpawner(body: EBody, next: Int)
279
+ # keeps the world transform and alpha its context gave it in its last step
280
+ | TProbe(body: EBody, seen: Affine, seenA: Float)
281
+ # pushes `EKill(target)` in each step
282
+ | TKiller(body: EBody, target: Int)
283
+
284
+ fun base(self) -> EBody = match self
285
+ TPlain(b) => b
286
+ TDrifter(b, _, _) => b
287
+ TSpawner(b, _) => b
288
+ TProbe(b, _, _) => b
289
+ TKiller(b, _) => b
290
+
291
+ fun key(self) -> Int = self.base().id
292
+
293
+ fun gone(self) -> Bool = self.base().dead
294
+
295
+ fun shown(self) -> Bool = self.base().shown()
296
+
297
+ fun opacity(self) -> Float = self.base().color.a
298
+
299
+ fun local(self) -> Affine = self.base().local()
300
+
301
+ fun hit(self, p: Vec2) -> Bool = self.base().hit(p)
302
+
303
+ fun paint(self, io: Io, m: Affine, alpha: Float) = self.base().paint(io, m, alpha)
304
+
305
+ fun step(self, ctx: ECtx[TBody], dt: Float) -> TBody = match self
306
+ TPlain(_) => self
307
+ TDrifter(b, vx, ttl) =>
308
+ if ttl == 0
309
+ TDrifter(body: b.killed(), vx: vx, ttl: ttl)
310
+ else
311
+ TDrifter(body: b.moveBy(vx * dt, 0.0), vx: vx, ttl: if ttl > 0 then ttl - 1 else ttl)
312
+ TSpawner(b, next) =>
313
+ ctx.out.push(ESpawn(parent: 0, node: tdrifter(next, 0.0, 0.0, -1)))
314
+ TSpawner(body: b, next: next + 1)
315
+ TProbe(b, _, _) => TProbe(body: b, seen: ctx.worldOf(b.local()), seenA: ctx.alphaOf(b.color.a))
316
+ TKiller(b, target) =>
317
+ ctx.out.push(EKill(id: target))
318
+ self
319
+
320
+ fun tdrifter(id: Int, x: Float, vx: Float, ttl: Int) -> ETree[TBody] =
321
+ b := EBody(
322
+ id: id, x: x, y: 0.0, width: 10.0, height: 10.0, originX: 0.0, originY: 0.0,
323
+ scaleX: 1.0, scaleY: 1.0, rotation: 0.0, color: Color.White, visible: true, dead: false)
324
+ etree.leaf(TDrifter(body: b, vx: vx, ttl: ttl))
325
+
326
+ fun tspawner(id: Int, next: Int) -> ETree[TBody] = etree.leaf(TSpawner(body: EBody.group(id, 0.0, 0.0), next: next))
327
+
328
+ fun tkiller(id: Int, target: Int) -> ETree[TBody] = etree.leaf(TKiller(body: EBody.group(id, 0.0, 0.0), target: target))
329
+
330
+ fun tprobe(id: Int, x: Float, y: Float, r: Float) -> TBody =
331
+ b := EBody(
332
+ id: id, x: x, y: y, width: 1.0, height: 1.0, originX: 2.0, originY: 1.0,
333
+ scaleX: 0.5, scaleY: 3.0, rotation: r, color: Color.White.withAlpha(0.5), visible: true, dead: false)
334
+ TProbe(body: b, seen: Affine.Identity, seenA: 0.0)
335
+
336
+ fun trect(id: Int, x: Float, y: Float, w: Float) -> ETree[TBody] = etree.leaf(TPlain(body: EBody.rect(id, x, y, w, w, Color.Red)))
337
+
338
+ fun tgroup(id: Int, x: Float, y: Float, s: Float, r: Float, kids: List[ETree[TBody]]) -> ETree[TBody] =
339
+ etree.of(TPlain(body: EBody.turned(id, x, y, s, r)), kids)
340
+
341
+ fun tstage() -> EStage[TBody] = EStage.of(TPlain(body: EBody.group(0, 0.0, 0.0)))
342
+
343
+ fun tids(s: EStage[TBody]) -> Str = s.root.fold("", |a, b| if a == "" then "{b.key()}" else "{a},{b.key()}")
344
+
345
+ fun tx(s: EStage[TBody], id: Int) -> Float = s.find(id).unwrap().base().x
346
+
347
+ fun tnear(a: Float, b: Float) -> Bool = {a - b}.abs() < 0.0001
348
+
349
+ fun tsameM(a: Affine, b: Affine) -> Bool =
350
+ tnear(a.a, b.a) && tnear(a.b, b.b) && tnear(a.c, b.c) && tnear(a.d, b.d) && tnear(a.e, b.e) && tnear(a.f, b.f)
351
+
352
+ fun tseen(s: EStage[TBody], id: Int) -> Affine = match s.find(id).unwrap()
353
+ TProbe(_, seen, _) => seen
354
+ _ => Affine.Identity
355
+
356
+ fun tseenA(s: EStage[TBody], id: Int) -> Float = match s.find(id).unwrap()
357
+ TProbe(_, _, a) => a
358
+ _ => 0.0
359
+
360
+ test "step returns a new stage and leaves a kept one as it was"
361
+ s0 := tstage().add(0, tdrifter(1, 0.0, 10.0, -1)).add(0, tdrifter(2, 5.0, -10.0, -1))
362
+ ctx := ECtx[TBody]()
363
+ s1 := s0.step(ctx, 0.5)
364
+ s2 := s1.step(ctx, 0.5)
365
+ assert tx(s0, 1) == 0.0
366
+ assert tx(s1, 1) == 5.0
367
+ assert tx(s2, 1) == 10.0
368
+ assert tx(s2, 2) == -5.0
369
+ assert tids(s0) == "0,1,2"
370
+ assert tids(s2) == "0,1,2"
371
+
372
+ test "a step that changes nothing keeps every body"
373
+ s0 := tstage().add(0, trect(1, 0.0, 0.0, 5.0)).add(0, tgroup(2, 0.0, 0.0, 1.0, 0.0, [trect(3, 0.0, 0.0, 5.0)]))
374
+ s1 := s0.step(ECtx[TBody](), 1.0)
375
+ assert tids(s1) == "0,1,2,3"
376
+ assert s1.find(3).unwrap() == s0.find(3).unwrap()
377
+
378
+ test "a body that returns a dead version is dropped with its subtree in the same step"
379
+ s := tstage().add(0, tdrifter(1, 0.0, 1.0, 1)).add(0, trect(2, 0.0, 0.0, 5.0)).add(1, trect(3, 0.0, 0.0, 5.0))
380
+ assert tids(s) == "0,1,3,2"
381
+ ctx := ECtx[TBody]()
382
+ s1 := s.step(ctx, 1.0)
383
+ assert tids(s1) == "0,1,3,2"
384
+ s2 := s1.step(ctx, 1.0)
385
+ assert tids(s2) == "0,2"
386
+ assert s2.find(3).isNone()
387
+
388
+ test "spawns pushed to ctx.out are added after the step, on top"
389
+ s := tstage().add(0, tspawner(1, 10))
390
+ ctx := ECtx[TBody]()
391
+ s1 := s.step(ctx, 1.0)
392
+ assert tids(s1) == "0,1,10"
393
+ assert ctx.out.length() == 0
394
+ assert tids(s1.step(ctx, 1.0)) == "0,1,10,11"
395
+
396
+ test "apply kills and spawns in one pass, in order"
397
+ s := tstage().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 1.0), trect(3, 0.0, 0.0, 1.0)])).add(0, trect(4, 0.0, 0.0, 1.0))
398
+ cmds := Slice[ECmd[TBody]]()
399
+ cmds.push(EKill(id: 2))
400
+ cmds.push(ESpawn(parent: 1, node: trect(5, 0.0, 0.0, 1.0)))
401
+ cmds.push(ESpawn(parent: 0, node: trect(6, 0.0, 0.0, 1.0)))
402
+ cmds.push(ESpawn(parent: 1, node: trect(7, 0.0, 0.0, 1.0)))
403
+ cmds.push(ESpawn(parent: 99, node: trect(8, 0.0, 0.0, 1.0)))
404
+ s2 := s.apply(cmds)
405
+ assert tids(s2) == "0,1,3,5,7,4,6"
406
+ assert tids(s) == "0,1,2,3,4"
407
+ assert s.kill(1).count() == 2
408
+
409
+ test "update by id changes one body and shares its untouched siblings"
410
+ s := tstage().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 1.0), trect(3, 0.0, 0.0, 1.0)]))
411
+ s1 := s.add(0, tgroup(4, 0.0, 0.0, 1.0, 0.0, [trect(5, 0.0, 0.0, 1.0)]))
412
+ u := s1.update(2, |b| TPlain(body: EBody.rect(b.key(), 9.0, 9.0, 1.0, 1.0, Color.Blue)))
413
+ assert tx(u, 2) == 9.0
414
+ assert tx(s1, 2) == 0.0
415
+ # 2's later sibling (3) and 1's later sibling (the group 4) are the same nodes
416
+ assert u.root.kids().kids().rest() == s1.root.kids().kids().rest()
417
+ assert u.root.kids().rest() == s1.root.kids().rest()
418
+
419
+ test "flatten gives each shown body its stage transform, parents first"
420
+ g := tgroup(1, 100.0, 0.0, 2.0, Float.HalfPi, [trect(2, 10.0, 0.0, 10.0), trect(3, 0.0, 0.0, 30.0)])
421
+ s := tstage().add(0, g).add(0, trect(4, 5.0, 5.0, 1.0))
422
+ d := s.flatten()
423
+ assert d.length() == 5
424
+ ids := Slice[Int]()
425
+ for e := range d
426
+ ids.push(e.body.key())
427
+ assert ids.toStr() == "[0,1,2,3,4]"
428
+ # (0, 0) of rect 2 is (10, 0) in the group, turned a quarter and doubled: (100, 20)
429
+ p := d.at(2).m.apply(Vec2(x: 0.0, y: 0.0))
430
+ assert tnear(p.x, 100.0) && tnear(p.y, 20.0)
431
+ assert tnear(d.at(4).m.e, 5.0)
432
+ hidden := s.update(1, |b| TPlain(body: EBody.group(b.key(), 100.0, 0.0).withVisible(false)))
433
+ assert hidden.flatten().length() == 2
434
+
435
+ test "hit finds the topmost body: later siblings and children first"
436
+ g := tgroup(1, 100.0, 0.0, 2.0, Float.HalfPi, [trect(2, 0.0, 0.0, 30.0), trect(3, 10.0, 0.0, 10.0)])
437
+ s := tstage().add(0, g)
438
+ assert s.hit(90.0, 30.0).unwrap().key() == 3
439
+ assert s.hit(70.0, 10.0).unwrap().key() == 2
440
+ assert s.hit(10.0, 10.0).isNone()
441
+ t := tstage().add(0, trect(5, 0.0, 0.0, 50.0)).add(0, trect(6, 25.0, 0.0, 50.0)).add(6, trect(7, 0.0, 0.0, 10.0))
442
+ assert t.hit(10.0, 10.0).unwrap().key() == 5
443
+ assert t.hit(30.0, 5.0).unwrap().key() == 7
444
+ assert t.hit(40.0, 10.0).unwrap().key() == 6
445
+
446
+ test "a body's world transform is computed when it asks, and matches the eager product"
447
+ gb := EBody.turned(1, 100.0, 30.0, 2.0, 0.7)
448
+ hb := EBody.turned(2, -20.0, 5.0, 1.5, -1.1).pivotAt(3.0, 4.0)
449
+ p := tprobe(3, 7.0, -2.0, 2.5)
450
+ q := tprobe(4, 1.0, 1.0, 0.0)
451
+ s := tstage().add(0, etree.of(TPlain(body: gb), [etree.of(TPlain(body: hb), [etree.leaf(p), etree.leaf(q)])]))
452
+ s1 := s.step(ECtx[TBody](), 1.0)
453
+ assert tsameM(tseen(s1, 3), gb.local().mul(hb.local()).mul(p.local()))
454
+ assert tnear(tseenA(s1, 3), 0.5)
455
+ # the sibling got its own transform from the same context
456
+ assert tsameM(tseen(s1, 4), gb.local().mul(hb.local()).mul(q.local()))
457
+
458
+ test "siblings with children each give their children their own world transform"
459
+ g1 := EBody.turned(1, 100.0, 30.0, 2.0, 0.7)
460
+ g2 := EBody.turned(2, -40.0, 5.0, 0.5, -1.2)
461
+ p1 := tprobe(3, 7.0, -2.0, 2.5)
462
+ p2 := tprobe(4, 1.0, 9.0, 0.3)
463
+ s := tstage().add(0, etree.of(TPlain(body: g1), [etree.leaf(p1)])).add(0, etree.of(TPlain(body: g2), [etree.leaf(p2)]))
464
+ s1 := s.step(ECtx[TBody](), 1.0)
465
+ assert tsameM(tseen(s1, 3), g1.local().mul(p1.local()))
466
+ assert tsameM(tseen(s1, 4), g2.local().mul(p2.local()))
467
+
468
+ test "a kill pushed before the step drops the body in the step's own walk, unstepped"
469
+ s := tstage().add(0, tspawner(1, 10)).add(0, tgroup(2, 0.0, 0.0, 1.0, 0.0, [trect(3, 0.0, 0.0, 1.0)]))
470
+ ctx := ECtx[TBody]()
471
+ ctx.out.push(EKill(id: 1))
472
+ s2 := s.step(ctx, 1.0)
473
+ # the spawner was not stepped, so it spawned nothing
474
+ assert tids(s2) == "0,2,3"
475
+ assert ctx.out.length() == 0
476
+ # ids outside the bitsets' range take the set: the same answers
477
+ ctx.out.push(EKill(id: -7))
478
+ ctx.out.push(EKill(id: 3))
479
+ ctx.out.push(EKill(id: 5000000))
480
+ assert tids(s2.step(ctx, 1.0)) == "0,2"
481
+
482
+ test "spawns pushed before the step go on top of their parents, in order, unstepped"
483
+ s := tstage().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 1.0), trect(3, 0.0, 0.0, 1.0)]))
484
+ s1 := s.add(0, trect(4, 0.0, 0.0, 1.0)).add(0, tgroup(9, 0.0, 0.0, 1.0, 0.0, [trect(10, 0.0, 0.0, 1.0)]))
485
+ ctx := ECtx[TBody]()
486
+ ctx.out.push(ESpawn(parent: 1, node: tdrifter(5, 0.0, 10.0, -1)))
487
+ ctx.out.push(ESpawn(parent: 4, node: trect(6, 0.0, 0.0, 1.0)))
488
+ ctx.out.push(ESpawn(parent: 1, node: trect(7, 0.0, 0.0, 1.0)))
489
+ ctx.out.push(ESpawn(parent: 99, node: trect(8, 0.0, 0.0, 1.0)))
490
+ s2 := s1.step(ctx, 1.0)
491
+ assert tids(s2) == "0,1,2,3,5,7,4,6,9,10"
492
+ # the drifter was added after the step: it hasn't moved yet
493
+ assert tx(s2, 5) == 0.0
494
+ assert tx(s2.step(ctx, 1.0), 5) == 10.0
495
+ # many spawns into one parent keep their order
496
+ for i := range 50
497
+ ctx.out.push(ESpawn(parent: 4, node: trect(100 + i, 0.0, 0.0, 1.0)))
498
+ s3 := s2.step(ctx, 1.0)
499
+ ids := s3.root.kids().rest().kids().fold(Slice[Int](), |acc, b|
500
+ acc.push(b.key())
501
+ acc
502
+ )
503
+ assert ids.length() == 51 && ids.at(0) == 6 && ids.at(1) == 100 && ids.at(50) == 149
504
+
505
+ test "a kill and a spawn of the same id before the step: the old body goes, the new one stays"
506
+ s := tstage().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 1.0), trect(3, 0.0, 0.0, 1.0)]))
507
+ ctx := ECtx[TBody]()
508
+ ctx.out.push(EKill(id: 2))
509
+ ctx.out.push(ESpawn(parent: 1, node: trect(2, 7.0, 0.0, 1.0)))
510
+ s2 := s.step(ctx, 1.0)
511
+ assert tids(s2) == "0,1,3,2"
512
+ assert tx(s2, 2) == 7.0
513
+ # the old stage is as it was
514
+ assert tids(s) == "0,1,2,3"
515
+ assert tx(s, 2) == 0.0
516
+ # a reused id is killed again by the next batch
517
+ ctx.out.push(EKill(id: 2))
518
+ assert tids(s2.step(ctx, 1.0)) == "0,1,3"
519
+
520
+ test "commands pushed during the step apply after those pushed before it"
521
+ s := tstage().add(0, tkiller(1, 5)).add(0, tgroup(2, 0.0, 0.0, 1.0, 0.0, []))
522
+ ctx := ECtx[TBody]()
523
+ # spawned by the batch before the step, then killed by a body during it
524
+ ctx.out.push(ESpawn(parent: 2, node: trect(5, 0.0, 0.0, 1.0)))
525
+ s2 := s.step(ctx, 1.0)
526
+ assert tids(s2) == "0,1,2"
527
+ assert ctx.out.length() == 0
528
+
529
+ test "the bitsets cover ids up to 2^22 - 1, and the set and map take the ids past it"
530
+ big := 4194303
531
+ s := tstage().add(0, tgroup(big, 0.0, 0.0, 1.0, 0.0, [trect(big - 1, 0.0, 0.0, 1.0)]))
532
+ s1 := s.add(0, tgroup(big + 1, 0.0, 0.0, 1.0, 0.0, [trect(63, 0.0, 0.0, 1.0), trect(64, 0.0, 0.0, 1.0)]))
533
+ ctx := ECtx[TBody]()
534
+ # in the bitsets' range: the last bit of the last word, and a word boundary
535
+ ctx.out.push(EKill(id: big - 1))
536
+ ctx.out.push(EKill(id: 64))
537
+ ctx.out.push(ESpawn(parent: big, node: trect(0 - 3, 0.0, 0.0, 1.0)))
538
+ s2 := s1.step(ctx, 1.0)
539
+ assert tids(s2) == "0,{big},-3,{big + 1},63"
540
+ # one id past the range: the whole batch uses the set and the map
541
+ ctx.out.push(ESpawn(parent: big + 1, node: trect(9, 0.0, 0.0, 1.0)))
542
+ ctx.out.push(EKill(id: 0 - 3))
543
+ ctx.out.push(EKill(id: 63))
544
+ s3 := s2.step(ctx, 1.0)
545
+ assert tids(s3) == "0,{big},{big + 1},9"
546
+ # a kill of an id the tree doesn't have, past the bitsets: nothing changes
547
+ ctx.out.push(EKill(id: big + 100))
548
+ assert tids(s3.step(ctx, 1.0)) == "0,{big},{big + 1},9"
549
+
550
+ test "a plain EBody stage: add, step, draw list"
551
+ s := EStage.of(EBody.group(0, 0.0, 0.0)).add(0, etree.leaf(EBody.rect(1, 10.0, 5.0, 40.0, 20.0, Color.Red)))
552
+ s1 := s.step(ECtx[EBody](), 1.0)
553
+ assert s1.count() == 2
554
+ assert s1.flatten().at(1).m.e == 10.0
555
+ assert s1.hit(20.0, 10.0).unwrap().id == 1
std/game_enum_tree/ETree.plum ADDED
@@ -0,0 +1,317 @@
1
+ module std
2
+
3
+ import std/Int
4
+ import std/Bool
5
+ import std/Str
6
+ import std/Option
7
+ import std/List
8
+ import std/Slice
9
+
10
+ # A persistent tree in left-child, right-sibling form: a node holds its value, its first
11
+ # child and its next sibling, so any number of children needs only two links per node.
12
+ # Every operation returns a new tree, and the old one stays valid while something still
13
+ # holds it: keeping last tick's root is a snapshot. When nothing else holds the old tree,
14
+ # the compiler's in-place reuse (FBIP) writes the new nodes into the old ones' cells
15
+ # instead of allocating; `--no-fbip` turns that off.
16
+ #
17
+ # leaf := etree.leaf(3)
18
+ # t := etree.of(1, [etree.leaf(2), leaf]) # 1 with the children 2 and 3
19
+ # t2 := t.addChild(etree.leaf(4)) # 1 with 2, 3 and 4; `t` still has 2 and 3
20
+ #
21
+ # A value of `ETree[T]` is a node together with its later siblings (a chain). A root has
22
+ # none, so a whole tree is a chain of one. The methods below work on the whole chain:
23
+ # `t.fold` folds the node, its subtree and then its later siblings and theirs, in
24
+ # preorder; `t.append(n)` puts `n` at the end of the chain. `addChild` works on the node
25
+ # itself (the first of the chain), and keeps its siblings.
26
+ #
27
+ # This is master's std/game_enum_tree/ETree written without loops, `return` or local
28
+ # reassignment: every walk is a recursion over the chain. Walks that rebuild a chain
29
+ # (`map`, `filter`, `append`) recurse once per sibling, so a chain's length is bounded by
30
+ # the stack (tens of thousands of nodes); `fold`, `each` and `find` are tail calls on the
31
+ # siblings and run in constant stack along a chain.
32
+ #
33
+ # Siblings are kept in draw order: the first child is drawn first and hit last. Appending
34
+ # a child copies the link nodes of its earlier siblings (their values and subtrees are
35
+ # shared), O(children); `appendAll` adds a batch for the cost of one.
36
+ #
37
+ # Nodes are referred to by what is in them (std/game_enum_tree's `EBody` has an `id`), not
38
+ # by the node itself: after an update the old node is a different, older value.
39
+ enum ETree[T] =
40
+ | EEmpty
41
+ | ENode(value: T, firstChild: ETree[T], nextSibling: ETree[T])
42
+
43
+ fun isEmpty(self) -> Bool = match self
44
+ EEmpty => true
45
+ ENode(_, _, _) => false
46
+
47
+ # The first node's value, None for an empty tree.
48
+ fun top(self) -> Option[T] = match self
49
+ EEmpty => None
50
+ ENode(v, _, _) => Some(v)
51
+
52
+ # The first node's children (a chain), empty for an empty tree.
53
+ fun kids(self) -> ETree[T] = match self
54
+ EEmpty => self
55
+ ENode(_, k, _) => k
56
+
57
+ # The siblings after the first node (a chain), empty for an empty tree.
58
+ fun rest(self) -> ETree[T] = match self
59
+ EEmpty => self
60
+ ENode(_, _, n) => n
61
+
62
+ # The nodes of this chain, first to last, each still linked to its later siblings.
63
+ fun chain(self) -> Slice[ETree[T]] =
64
+ out := Slice[ETree[T]]()
65
+ self.chainInto(out)
66
+ out
67
+
68
+ fun chainInto(self, out: Slice[ETree[T]]) =
69
+ if ENode(_, _, n) := self
70
+ out.push(self)
71
+ n.chainInto(out)
72
+
73
+ # The number of nodes in the chain and all their subtrees.
74
+ fun count(self) -> Int = self.fold(0, |a, v| a + 1)
75
+
76
+ # `f` over every value in preorder: a node, then its subtree, then its later siblings.
77
+ fun fold[A](self, acc: A, f: fn(A, T) -> A) -> A = match self
78
+ EEmpty => acc
79
+ ENode(v, k, n) => n.fold(k.fold(f(acc, v), f), f)
80
+
81
+ # Calls `f` on every value in preorder.
82
+ fun each(self, f: fn(T) -> Unit) =
83
+ if ENode(v, k, n) := self
84
+ f(v)
85
+ k.each(f)
86
+ n.each(f)
87
+
88
+ # The values in preorder.
89
+ fun toSlice(self) -> Slice[T] =
90
+ out := Slice[T]()
91
+ self.pushInto(out)
92
+ out
93
+
94
+ fun pushInto(self, out: Slice[T]) =
95
+ if ENode(v, k, n) := self
96
+ out.push(v)
97
+ k.pushInto(out)
98
+ n.pushInto(out)
99
+
100
+ # The same shape with `f` applied to every value, called in preorder.
101
+ fun map[B](self, f: fn(T) -> B) -> ETree[B] = match self
102
+ EEmpty => EEmpty
103
+ ENode(v, k, n) =>
104
+ v2 := f(v)
105
+ k2 := k.map(f)
106
+ ENode(value: v2, firstChild: k2, nextSibling: n.map(f))
107
+
108
+ # The tree without the nodes whose value fails `keep`; a dropped node takes its subtree
109
+ # with it. A chain in which nothing was dropped, at any depth, is returned as it was (the
110
+ # same value), so untouched subtrees are shared.
111
+ fun filter(self, keep: fn(T) -> Bool) -> ETree[T] = match self
112
+ EEmpty => self
113
+ ENode(v, k, n) =>
114
+ if keep(v)
115
+ k2 := k.filter(keep)
116
+ n2 := n.filter(keep)
117
+ if k2 == k && n2 == n then self else ENode(value: v, firstChild: k2, nextSibling: n2)
118
+ else
119
+ n.filter(keep)
120
+
121
+ # The chain with the node `n` (and its subtree, not its siblings) added at the end.
122
+ fun append(self, n: ETree[T]) -> ETree[T] = self.concat(n.alone())
123
+
124
+ # The chain with the nodes of `ns` (each with its subtree, not its siblings) added at the
125
+ # end, in order. The chain's own link nodes are copied once; values and subtrees are
126
+ # shared.
127
+ fun appendAll(self, ns: List[ETree[T]]) -> ETree[T] = self.concat(etreeChainOf(ns))
128
+
129
+ # This chain followed by the chain `tail`: the link nodes of this one are copied, `tail`
130
+ # is shared.
131
+ fun concat(self, tail: ETree[T]) -> ETree[T] = match self
132
+ EEmpty => tail
133
+ ENode(v, k, n) => ENode(value: v, firstChild: k, nextSibling: n.concat(tail))
134
+
135
+ # The first node without its later siblings (empty for an empty tree).
136
+ fun alone(self) -> ETree[T] = match self
137
+ EEmpty => self
138
+ ENode(v, k, n) => if n.isEmpty() then self else ENode(value: v, firstChild: k, nextSibling: EEmpty)
139
+
140
+ # The first node with `c` added as its last child (drawn on top of its siblings). Its
141
+ # later siblings are kept. An empty tree stays empty.
142
+ fun addChild(self, c: ETree[T]) -> ETree[T] = match self
143
+ EEmpty => self
144
+ ENode(v, k, n) => ENode(value: v, firstChild: k.append(c), nextSibling: n)
145
+
146
+ # The first node with the nodes of `cs` added as its last children, in order.
147
+ fun addChildren(self, cs: List[ETree[T]]) -> ETree[T] = match self
148
+ EEmpty => self
149
+ ENode(v, k, n) => ENode(value: v, firstChild: k.appendAll(cs), nextSibling: n)
150
+
151
+ # The first node with its value replaced by `v`; children and siblings are kept.
152
+ fun withValue(self, v: T) -> ETree[T] = match self
153
+ EEmpty => self
154
+ ENode(_, k, n) => ENode(value: v, firstChild: k, nextSibling: n)
155
+
156
+ # The tree with the first node, in preorder, whose value passes `pick` replaced by
157
+ # `f(node)`, where `node` is that node with its children and without its siblings; the
158
+ # result's own siblings are ignored and the original ones kept. Everything off the path
159
+ # to that node is shared: the node's later siblings, the subtrees of its earlier ones
160
+ # (only their link nodes are copied) and of its ancestors' siblings alike. With no
161
+ # match, the tree itself is returned.
162
+ fun replace(self, pick: fn(T) -> Bool, f: fn(ETree[T]) -> ETree[T]) -> ETree[T] = match self
163
+ EEmpty => self
164
+ ENode(v, k, n) =>
165
+ if pick(v)
166
+ match f(self.alone())
167
+ EEmpty => n
168
+ ENode(v2, k2, _) => ENode(value: v2, firstChild: k2, nextSibling: n)
169
+ else
170
+ k2 := k.replace(pick, f)
171
+ if k2 != k
172
+ ENode(value: v, firstChild: k2, nextSibling: n)
173
+ else
174
+ n2 := n.replace(pick, f)
175
+ if n2 == n then self else ENode(value: v, firstChild: k, nextSibling: n2)
176
+
177
+ # The tree with the value of the first node, in preorder, that passes `pick` replaced by
178
+ # `f(value)`. As `replace`, it shares everything off the path.
179
+ fun update(self, pick: fn(T) -> Bool, f: fn(T) -> T) -> ETree[T] =
180
+ self.replace(pick, |x| x.withValue(f(x.top().unwrap())))
181
+
182
+ # The first value in preorder that passes `pick`.
183
+ fun find(self, pick: fn(T) -> Bool) -> Option[T] = match self
184
+ EEmpty => None
185
+ ENode(v, k, n) =>
186
+ if pick(v)
187
+ Some(v)
188
+ else
189
+ match k.find(pick)
190
+ Some(x) => Some(x)
191
+ None => n.find(pick)
192
+
193
+ # A node with no children.
194
+ fun leaf[T](v: T) -> ETree[T] =
195
+ empty: ETree[T] := EEmpty
196
+ ENode(value: v, firstChild: empty, nextSibling: empty)
197
+
198
+ # A node with the children `kids` (each with its subtree, not its siblings), in order.
199
+ fun of[T](v: T, kids: List[ETree[T]]) -> ETree[T] =
200
+ empty: ETree[T] := EEmpty
201
+ ENode(value: v, firstChild: etreeChainOf(kids), nextSibling: empty)
202
+
203
+ # The nodes of `ns` (each with its subtree, not its siblings) linked into one chain, in
204
+ # order.
205
+ fun etreeChainOf[T](ns: List[ETree[T]]) -> ETree[T] = match ns
206
+ Nil => EEmpty
207
+ Cons(h, t) => match h
208
+ EEmpty => etreeChainOf(t)
209
+ ENode(v, k, _) => ENode(value: v, firstChild: k, nextSibling: etreeChainOf(t))
210
+
211
+ # The nodes of `ns` from index `i` on, linked into one chain, in order.
212
+ fun etreeChainFrom[T](ns: Slice[ETree[T]], i: Int) -> ETree[T] =
213
+ if i >= ns.length()
214
+ EEmpty
215
+ else
216
+ match ns.at(i)
217
+ EEmpty => etreeChainFrom(ns, i + 1)
218
+ ENode(v, k, _) => ENode(value: v, firstChild: k, nextSibling: etreeChainFrom(ns, i + 1))
219
+
220
+ # --- tests ---
221
+
222
+ fun etreeSample() -> ETree[Int] =
223
+ # 1
224
+ # 2 5
225
+ # 3 4 6
226
+ of(1, [of(2, [leaf(3), leaf(4)]), of(5, [leaf(6)])])
227
+
228
+ fun etreeShow(t: ETree[Int]) -> Str = match t
229
+ EEmpty => ""
230
+ ENode(v, k, n) =>
231
+ me := if k.isEmpty() then "{v}" else "{v}({etreeShow(k)})"
232
+ if n.isEmpty() then me else "{me} {etreeShow(n)}"
233
+
234
+ test "fold and toSlice visit a node, its subtree, then its later siblings"
235
+ t := etreeSample()
236
+ assert t.fold("", |a, v| "{a}{v}") == "123456"
237
+ assert t.toSlice().toStr() == "[1,2,3,4,5,6]"
238
+ assert t.count() == 6
239
+ assert etreeShow(t) == "1(2(3 4) 5(6))"
240
+ e: ETree[Int] := EEmpty
241
+ assert e.count() == 0
242
+ assert e.top().isNone()
243
+ assert t.kids().chain().length() == 2
244
+
245
+ test "map keeps the shape and calls f in preorder"
246
+ t := etreeSample().map(|v| v * 10)
247
+ assert etreeShow(t) == "10(20(30 40) 50(60))"
248
+ s := etreeSample().map(|v| "<{v}>")
249
+ assert s.fold("", |a, v| "{a}{v}") == "<1><2><3><4><5><6>"
250
+
251
+ test "filter drops a node with its subtree and shares what it didn't touch"
252
+ t := etreeSample()
253
+ f := t.filter(|v| v != 2)
254
+ assert etreeShow(f) == "1(5(6))"
255
+ assert etreeShow(t) == "1(2(3 4) 5(6))"
256
+ assert etreeShow(t.filter(|v| v != 4)) == "1(2(3) 5(6))"
257
+ assert t.filter(|v| true) == t
258
+ g := t.filter(|v| v != 3)
259
+ assert g.kids().rest() == t.kids().rest()
260
+
261
+ test "append and addChild keep draw order, and the old tree is unchanged"
262
+ t := of(1, [leaf(2)])
263
+ t2 := t.addChild(leaf(3))
264
+ t3 := t2.addChild(of(4, [leaf(5)]))
265
+ assert etreeShow(t) == "1(2)"
266
+ assert etreeShow(t2) == "1(2 3)"
267
+ assert etreeShow(t3) == "1(2 3 4(5))"
268
+ assert etreeShow(leaf(1).append(leaf(2)).append(leaf(3))) == "1 2 3"
269
+ e: ETree[Int] := EEmpty
270
+ assert etreeShow(e.append(leaf(7))) == "7"
271
+ assert etreeShow(leaf(1).addChildren([leaf(2), leaf(3), leaf(4)])) == "1(2 3 4)"
272
+ # a node's own siblings don't come along
273
+ assert etreeShow(leaf(1).addChild(leaf(8).append(leaf(9)))) == "1(8)"
274
+
275
+ test "update changes one node and shares the untouched siblings and subtrees"
276
+ t := etreeSample()
277
+ u := t.update(|v| v == 3, |v| v + 100)
278
+ assert etreeShow(u) == "1(2(103 4) 5(6))"
279
+ assert etreeShow(t) == "1(2(3 4) 5(6))"
280
+ # the later sibling of 3 and the later sibling of 2 are the same values, not copies
281
+ assert u.kids().kids().rest() == t.kids().kids().rest()
282
+ assert u.kids().rest() == t.kids().rest()
283
+ # an earlier sibling's link is new, but its subtree is shared
284
+ w := t.update(|v| v == 5, |v| 50)
285
+ assert etreeShow(w) == "1(2(3 4) 50(6))"
286
+ assert w.kids() != t.kids()
287
+ assert w.kids().kids() == t.kids().kids()
288
+ assert w.kids().rest().kids() == t.kids().rest().kids()
289
+ # no match: the tree itself
290
+ assert t.update(|v| v == 99, |v| 0) == t
291
+
292
+ test "replace swaps a whole node and keeps its siblings"
293
+ t := etreeSample()
294
+ r := t.replace(|v| v == 2, |n| n.addChild(leaf(7)))
295
+ assert etreeShow(r) == "1(2(3 4 7) 5(6))"
296
+ assert r.kids().rest() == t.kids().rest()
297
+ assert etreeShow(t.replace(|v| v == 2, |n| leaf(9))) == "1(9 5(6))"
298
+ e: ETree[Int] := EEmpty
299
+ assert etreeShow(t.replace(|v| v == 5, |n| e)) == "1(2(3 4))"
300
+
301
+ test "find returns the first value in preorder"
302
+ t := etreeSample()
303
+ assert t.find(|v| v > 2).unwrap() == 3
304
+ assert t.find(|v| v > 4).unwrap() == 5
305
+ assert t.find(|v| v > 6).isNone()
306
+
307
+ test "a sibling chain of 10,000 nodes"
308
+ kids := Slice[ETree[Int]]()
309
+ for i := range 10000
310
+ kids.push(leaf(i))
311
+ empty: ETree[Int] := EEmpty
312
+ t := ENode(value: -1, firstChild: etreeChainFrom(kids, 0), nextSibling: empty)
313
+ assert t.count() == 10001
314
+ assert t.fold(0, |a, v| a + v) == 49995000 - 1
315
+ u := t.update(|v| v == 9999, |v| 0)
316
+ assert u.fold(0, |a, v| a + v) == 49995000 - 1 - 9999
317
+ assert t.filter(|v| v < 0 || v % 2 == 0).count() == 5001