plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
2dc2a4a
— Peter John
2026-11-16T20:20:54+05:30
U4a: one struct per closure, called with no cast; a constructor is a function value
- benchmarks/closures/calls.plum +53 -0
- benchmarks/master_vs_simpler/run.py +17 -20
- benchmarks/screen_views/clockwork.plum +70 -0
- compiler/checker/tests/checker/review_tests.rs +8 -6
- compiler/core/src/ctor_values.rs +104 -0
- compiler/core/src/lib.rs +1 -0
- compiler/core/src/lower.rs +2 -0
- compiler/wasm-codegen/src/closurecalls.rs +40 -53
- compiler/wasm-codegen/src/closures.rs +1 -1
- compiler/wasm-codegen/src/context.rs +22 -17
- compiler/wasm-codegen/src/driver.rs +45 -52
- compiler/wasm-codegen/src/expr.rs +2 -5
- compiler/wasm-codegen/src/gctypes.rs +19 -7
- compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs +74 -9
- docs/backlog.md +2 -2
- docs/game.md +4 -4
- docs/language.md +2 -0
- examples/games/balloonpop/screens/PlaygroundScreen.plum +1 -1
- examples/games/clicks.plum +1 -1
- examples/games/clockwork/screens/OrreryScreen.plum +1 -1
- examples/games/menu/screens/MenuScreen.plum +1 -1
- examples/games/menu/screens/TurnScreen.plum +1 -1
- examples/games/orbitrunner/screens/PlayingScreen.plum +1 -1
- std/game/ScreenSlice.plum +3 -2
- tests/syntax/constructor_values.plum +51 -0
- tests/wasm_codegen/e2e_types/typed_closures.plum +103 -0
benchmarks/closures/calls.plum
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# Closures that no specialisation removes: 2000 closures that capture a value each, built
|
|
2
|
+
# into a list (a closure in an enum payload), then each called 1000 times through the list,
|
|
3
|
+
# and a chain of 100 composed closures (a closure returning a closure) called 10,000
|
|
4
|
+
# times; 10 rounds.
|
|
5
|
+
#
|
|
6
|
+
# plum build benchmarks/closures/calls.plum -o calls
|
|
7
|
+
# ./calls
|
|
8
|
+
#
|
|
9
|
+
# It prints `ms <total> checksum <c>`.
|
|
10
|
+
module closure_calls_bench
|
|
11
|
+
|
|
12
|
+
import std/Int
|
|
13
|
+
import std/Float
|
|
14
|
+
import std/Str
|
|
15
|
+
import std/Io
|
|
16
|
+
import std/App
|
|
17
|
+
|
|
18
|
+
primitive ClosureCalls[App] =
|
|
19
|
+
fun adders(n: Int, acc: Fns) -> Fns =
|
|
20
|
+
if n == 0 then acc else adders(n - 1, More(f: |x| {x * 31 + n} % 1000003, rest: acc))
|
|
21
|
+
|
|
22
|
+
fun applyAll(fs: Fns, x: Int) -> Int = match fs
|
|
23
|
+
Done => x
|
|
24
|
+
More(f, rest) => applyAll(rest, f(x))
|
|
25
|
+
|
|
26
|
+
fun repeat(fs: Fns, k: Int, x: Int) -> Int =
|
|
27
|
+
if k == 0 then x else repeat(fs, k - 1, applyAll(fs, x))
|
|
28
|
+
|
|
29
|
+
fun compose(f: fn(Int) -> Int, g: fn(Int) -> Int) -> fn(Int) -> Int = |x| g(f(x))
|
|
30
|
+
|
|
31
|
+
fun chain(n: Int, f: fn(Int) -> Int) -> fn(Int) -> Int =
|
|
32
|
+
if n == 0 then f else chain(n - 1, compose(f, |x| {x + n} % 1000003))
|
|
33
|
+
|
|
34
|
+
fun drive(f: fn(Int) -> Int, k: Int, x: Int) -> Int = if k == 0 then x else drive(f, k - 1, f(x))
|
|
35
|
+
|
|
36
|
+
fun round(r: Int) -> Int =
|
|
37
|
+
fs := adders(2000, Done)
|
|
38
|
+
a := repeat(fs, 1000, r)
|
|
39
|
+
c := chain(100, |x| x)
|
|
40
|
+
{a + drive(c, 10000, r)} % 1000000007
|
|
41
|
+
|
|
42
|
+
fun rounds(k: Int, acc: Int) -> Int = if k == 0 then acc else rounds(k - 1, {acc * 31 + round(k)} % 1000000007)
|
|
43
|
+
|
|
44
|
+
fun main(io: Io) =
|
|
45
|
+
t0 := io.nowMicros()
|
|
46
|
+
r := ClosureCalls.rounds(10, 0)
|
|
47
|
+
t1 := io.nowMicros()
|
|
48
|
+
el := {t1 - t0} / 1000.0
|
|
49
|
+
io.printLn("ms {el} checksum {r}")
|
|
50
|
+
|
|
51
|
+
enum Fns =
|
|
52
|
+
| More(f: fn(Int) -> Int, rest: Fns)
|
|
53
|
+
| Done
|
benchmarks/master_vs_simpler/run.py
CHANGED
|
@@ -152,37 +152,36 @@ primitive OrbRun[App] =
|
|
|
152
152
|
|
|
153
153
|
fun steerY(seed: Int, t: Int) -> Float = Float({{seed * 13 + t / 13} * 40503 % 1000033} % 3 - 1)
|
|
154
154
|
|
|
155
|
-
fun heldAt(seed: Int, t: Int) ->
|
|
155
|
+
fun heldAt(seed: Int, t: Int) -> List<Int> = [
|
|
156
|
-
keys := Slice<Int>()
|
|
157
|
-
if steerX(seed, t) < 0.0
|
|
156
|
+
if steerX(seed, t) < 0.0 then Key.Left
|
|
158
|
-
keys.push(Key.Left)
|
|
159
|
-
if steerX(seed, t) > 0.0
|
|
157
|
+
if steerX(seed, t) > 0.0 then Key.Right
|
|
160
|
-
keys.push(Key.Right)
|
|
161
|
-
if steerY(seed, t) < 0.0
|
|
158
|
+
if steerY(seed, t) < 0.0 then Key.Up
|
|
162
|
-
keys.push(Key.Up)
|
|
163
|
-
if steerY(seed, t) > 0.0
|
|
159
|
+
if steerY(seed, t) > 0.0 then Key.Down
|
|
160
|
+
]
|
|
161
|
+
|
|
162
|
+
fun listOf(xs: Slice<InputEvent>) -> List<InputEvent> =
|
|
164
|
-
|
|
163
|
+
none: List<InputEvent> := Nil
|
|
165
|
-
|
|
164
|
+
xs.fold(none, |acc, e| Cons(e, acc)).reverse()
|
|
166
165
|
|
|
167
166
|
fun inputAt(seed: Int, t: Int, over: Bool) -> Input =
|
|
168
167
|
now := heldAt(seed, t)
|
|
169
|
-
before := if t == 0 then
|
|
168
|
+
before := if t == 0 then Nil else heldAt(seed, t - 1)
|
|
170
169
|
events := Slice<InputEvent>()
|
|
171
170
|
px := Float({t * 37} % 800)
|
|
172
171
|
py := Float({t * 53} % 600)
|
|
173
172
|
events.push(PointerMove(x: px, y: py))
|
|
174
173
|
for k := range [Key.Left, Key.Right, Key.Up, Key.Down]
|
|
175
|
-
if now.
|
|
174
|
+
if now.any(|x| x == k) && !before.any(|x| x == k)
|
|
176
175
|
events.push(KeyDown(key: k))
|
|
177
|
-
if !now.
|
|
176
|
+
if !now.any(|x| x == k) && before.any(|x| x == k)
|
|
178
177
|
events.push(KeyUp(key: k))
|
|
179
178
|
if over && t % 150 == 0
|
|
180
179
|
events.push(KeyDown(key: Key.Enter))
|
|
181
|
-
Input(held: Held(keys: now), events:
|
|
180
|
+
Input(held: Held(keys: now), events: listOf(events))
|
|
182
181
|
|
|
183
182
|
fun playing(g: Game) -> PlayingScreen = match g.screen()
|
|
184
183
|
PlayingScreen as p => p
|
|
185
|
-
_ => PlayingScreen.start(
|
|
184
|
+
_ => PlayingScreen.start(0, Assets.none())
|
|
186
185
|
|
|
187
186
|
fun run(io: Io, seed: Int, g: Game, t: Int, was: Bool, acc: Tally) -> Tally =
|
|
188
187
|
if t >= TICKS
|
|
@@ -197,7 +196,7 @@ primitive OrbRun[App] =
|
|
|
197
196
|
fun main(io: Io) =
|
|
198
197
|
t0 := io.nowMicros()
|
|
199
198
|
tally := SEEDS.fold(Tally(check: 0, overs: 0, scores: 0, mines: 0), |acc, seed|
|
|
200
|
-
only: Screen := PlayingScreen.start(
|
|
199
|
+
only: Screen := PlayingScreen.start(seed, Assets.none())
|
|
201
200
|
OrbRun.run(io, seed, Game(screens: [only]), 0, false, acc))
|
|
202
201
|
t1 := io.nowMicros()
|
|
203
202
|
el := {t1 - t0} / 1000.0
|
|
@@ -249,9 +248,7 @@ primitive BalloonRun[App] =
|
|
|
249
248
|
if t >= TICKS
|
|
250
249
|
Tally(..acc, pops: acc.pops + field(g).pops)
|
|
251
250
|
else
|
|
252
|
-
events := Slice<InputEvent>()
|
|
253
|
-
|
|
251
|
+
inp := Input(held: Held(), events: [PointerDown(x: Float({t * 97} % 800), y: Float({t * 61} % 600))])
|
|
254
|
-
inp := Input(held: Held(), events: events, pos: Vec2(x: 0.0, y: 0.0), wheel: 0.0)
|
|
255
252
|
n := g.step(io, inp, 1.0 / 60.0, Vec2(x: 800.0, y: 600.0))
|
|
256
253
|
run(io, n, t + 1, Tally(..acc, check: {acc.check * 31 + field(n).pops} % 1000000007))
|
|
257
254
|
|
benchmarks/screen_views/clockwork.plum
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
# Clockwork, timed per tick: 3600 ticks of the orrery (60 walkers re-sorted each tick, four
|
|
2
|
+
# planets with their moons), seeds 1, 7, 42 and 1234 picking when Space pauses and resumes.
|
|
3
|
+
#
|
|
4
|
+
# update each tick through the game (`Game.update`)
|
|
5
|
+
# paint each tick, then the frame (`Game.draw`). Run with PLUM_NULL_GFX=1: there is no
|
|
6
|
+
# host, and the draw calls reach nothing.
|
|
7
|
+
#
|
|
8
|
+
# It prints `us <total> ticks <n> checksum <c>`: the microseconds of every tick (and frame),
|
|
9
|
+
# the ticks, and a checksum of every walker's place at the end of each seed.
|
|
10
|
+
#
|
|
11
|
+
# plum build benchmarks/screen_views/clockwork.plum -o clockwork
|
|
12
|
+
# PLUM_NULL_GFX=1 ./clockwork update
|
|
13
|
+
# PLUM_NULL_GFX=1 ./clockwork paint
|
|
14
|
+
module clockwork_bench
|
|
15
|
+
|
|
16
|
+
import std/Int
|
|
17
|
+
import std/Float
|
|
18
|
+
import std/Bool
|
|
19
|
+
import std/Str
|
|
20
|
+
import std/Io
|
|
21
|
+
import std/collections/List
|
|
22
|
+
import std/math/Vec2
|
|
23
|
+
import std/game/Input
|
|
24
|
+
import std/game/Screen
|
|
25
|
+
import std/game/Game
|
|
26
|
+
import std/App
|
|
27
|
+
import benchmarks/screen_views/timing
|
|
28
|
+
import examples/games/clockwork/Clockwork
|
|
29
|
+
import examples/games/clockwork/screens/OrreryScreen
|
|
30
|
+
|
|
31
|
+
primitive ClockworkBench[App] =
|
|
32
|
+
fun make() -> OrreryScreen = OrreryScreen.start(Assets.none())
|
|
33
|
+
|
|
34
|
+
fun gameOf() -> Game =
|
|
35
|
+
only: Screen := make()
|
|
36
|
+
Game(screens: [only])
|
|
37
|
+
|
|
38
|
+
fun orreryOf(g: Game) -> OrreryScreen = match g.screen()
|
|
39
|
+
OrreryScreen as o => o
|
|
40
|
+
_ => make()
|
|
41
|
+
|
|
42
|
+
fun state(o: OrreryScreen) -> Int =
|
|
43
|
+
none: List<Int> := Nil
|
|
44
|
+
places := o.walkers.fold(none, |acc, w| Cons(w.place().y.toBits(), Cons(w.place().x.toBits(), acc)))
|
|
45
|
+
Timing.hash(Cons(Timing.flag(o.paused), places))
|
|
46
|
+
|
|
47
|
+
fun inputAt(seed: Int, t: Int) -> Input =
|
|
48
|
+
Input(events: [if {t + seed} % 700 == 699 then KeyDown(key: Key.Space)])
|
|
49
|
+
|
|
50
|
+
fun tickOnce(io: Io, g: Game, inp: Input, paint: Bool) -> Game =
|
|
51
|
+
next := g.update(io, inp, Ticker.Tick)
|
|
52
|
+
if paint
|
|
53
|
+
next.draw(io)
|
|
54
|
+
next
|
|
55
|
+
|
|
56
|
+
fun play(io: Io, seed: Int, paint: Bool, ticks: Int) -> Int =
|
|
57
|
+
g := Range.until(0, ticks).fold(gameOf(), |cur, t| tickOnce(io, cur, inputAt(seed, t), paint))
|
|
58
|
+
state(orreryOf(g))
|
|
59
|
+
|
|
60
|
+
fun main(io: Io) =
|
|
61
|
+
args := io.args()
|
|
62
|
+
paint := args.length() > 0 && args.at(0) == "paint"
|
|
63
|
+
seeds := [1, 7, 42, 1234]
|
|
64
|
+
timed := seeds.fold(Timed(us: 0.0, sums: Nil), |acc, seed|
|
|
65
|
+
t0 := io.nowMicros()
|
|
66
|
+
sum := ClockworkBench.play(io, seed, paint, 3600)
|
|
67
|
+
Timed(us: acc.us + {io.nowMicros() - t0}, sums: acc.sums.append([sum])))
|
|
68
|
+
io.printLn("us {Int(timed.us)} ticks {3600 * seeds.length()} checksum {Timing.hash(timed.sums)}")
|
|
69
|
+
|
|
70
|
+
struct Timed(us: Float, sums: List<Int>)
|
compiler/checker/tests/checker/review_tests.rs
CHANGED
|
@@ -23,15 +23,17 @@ fn ok(body: &str) {
|
|
|
23
23
|
}
|
|
24
24
|
|
|
25
25
|
#[test]
|
|
26
|
-
fn
|
|
26
|
+
fn a_bare_struct_name_is_its_constructor() {
|
|
27
|
+
// A constructor named as a value is the function that builds one (`ctor_values`).
|
|
27
|
-
let e = errorWith("struct Boxed(x: Int)\n\nprimitive Main =\n fun k(x: Boxed) -> Boxed = Boxed", "
|
|
28
|
+
let e = errorWith("struct Boxed(x: Int)\n\nprimitive Main =\n fun k(x: Boxed) -> Boxed = Boxed", "found (Int) -> Boxed");
|
|
28
|
-
assert!(e.message.contains("`Boxed(x: ..)`"), "{e:?}");
|
|
29
|
-
assert_eq!(
|
|
29
|
+
assert_eq!(e.line, 4, "{e:?}");
|
|
30
|
+
ok("struct Boxed(x: Int)\n\nprimitive Main =\n fun k() -> fn(Int) -> Boxed = Boxed");
|
|
30
31
|
}
|
|
31
32
|
|
|
32
33
|
#[test]
|
|
33
|
-
fn
|
|
34
|
+
fn a_bare_payload_variant_is_its_constructor() {
|
|
34
|
-
errorWith("enum Sh =\n | Circ(r: Int)\n | Sq(s: Int)\n\nprimitive Main =\n fun k() -> Sh = Circ", "
|
|
35
|
+
errorWith("enum Sh =\n | Circ(r: Int)\n | Sq(s: Int)\n\nprimitive Main =\n fun k() -> Sh = Circ", "found (Int) -> Sh");
|
|
36
|
+
ok("enum Sh =\n | Circ(r: Int)\n | Sq(s: Int)\n\nprimitive Main =\n fun k() -> fn(Int) -> Sh = Circ");
|
|
35
37
|
}
|
|
36
38
|
|
|
37
39
|
#[test]
|
compiler/core/src/ctor_values.rs
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
//! A struct or variant constructor named as a value is the function that constructs it:
|
|
2
|
+
//! `OnFrame(Tick)` is `OnFrame(|dt| Tick(dt: dt))` for `Tick(dt: Float)`, and
|
|
3
|
+
//! `xs.map(Some)` is `xs.map(|value| Some(value: value))`. The constructor takes every
|
|
4
|
+
//! field, in declaration order (a field with a default too). A constructor with no
|
|
5
|
+
//! fields is already a value (`Nil`), and a struct with a `fun init(self)` is built
|
|
6
|
+
//! through its init, so neither is lowered. `Type.name` (a static, a constant) is a
|
|
7
|
+
//! type used as a receiver, not a value, and stays as it is, as does a type given to a
|
|
8
|
+
//! compile-time built-in (`@sameRef(x, Str)`, which reports it).
|
|
9
|
+
use std::collections::{HashMap, HashSet};
|
|
10
|
+
|
|
11
|
+
use crate::ast::*;
|
|
12
|
+
use crate::forms::mapExprs;
|
|
13
|
+
|
|
14
|
+
/// How a constructor is called: its field names (empty for a positional variant,
|
|
15
|
+
/// `Next(T)`), and its number of fields.
|
|
16
|
+
struct Ctor {
|
|
17
|
+
names: Vec<String>,
|
|
18
|
+
arity: usize,
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/// Rewrites every constructor named as a value into a closure literal (see the module doc).
|
|
22
|
+
pub fn lowerCtorValues(source: &mut Source) {
|
|
23
|
+
let mut ctors: HashMap<String, Ctor> = HashMap::new();
|
|
24
|
+
for item in &source.items {
|
|
25
|
+
let Item::Enum(e) = item else { continue };
|
|
26
|
+
for v in &e.variants {
|
|
27
|
+
if !v.fields.is_empty() {
|
|
28
|
+
let names = if v.field_names.len() == v.fields.len() { v.field_names.clone() } else { Vec::new() };
|
|
29
|
+
ctors.insert(v.name.clone(), Ctor { names, arity: v.fields.len() });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
for item in &source.items {
|
|
34
|
+
if let Item::Fn(f) = item {
|
|
35
|
+
if f.name == "init" && f.has_self {
|
|
36
|
+
if let Some(t) = &f.type_param {
|
|
37
|
+
ctors.remove(t);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if ctors.is_empty() {
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
for item in &mut source.items {
|
|
46
|
+
let Item::Fn(f) = item else { continue };
|
|
47
|
+
// The receivers of `Type.name` are types, not values, and so are the type arguments
|
|
48
|
+
// a compile-time built-in is given by mistake (`@sameRef(x, Str)`, its own error).
|
|
49
|
+
let mut receivers: HashSet<*const Expr> = HashSet::new();
|
|
50
|
+
mapExprs(&mut f.body, &mut |e| match &e.kind {
|
|
51
|
+
ExprKind::Attribute(a) => {
|
|
52
|
+
receivers.insert(&a.object as *const Expr);
|
|
53
|
+
}
|
|
54
|
+
ExprKind::FnCall(c) if c.name.starts_with('@') => {
|
|
55
|
+
for a in &c.args {
|
|
56
|
+
if let Arg::Positional(v) | Arg::Keyword { value: v, .. } = a {
|
|
57
|
+
receivers.insert(v as *const Expr);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
_ => {}
|
|
62
|
+
});
|
|
63
|
+
mapExprs(&mut f.body, &mut |e| {
|
|
64
|
+
let ExprKind::TypeName(n) = &e.kind else { return };
|
|
65
|
+
let Some(c) = ctors.get(n.as_str()) else { return };
|
|
66
|
+
if receivers.contains(&(e as *const Expr)) {
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
let params: Vec<String> = (0..c.arity).map(|i| format!("__ctor{i}")).collect();
|
|
70
|
+
let call = if c.names.is_empty() {
|
|
71
|
+
Expr::FnCall(FnCall {
|
|
72
|
+
name: n.clone(),
|
|
73
|
+
args: params.iter().map(|p| Arg::Positional(Expr::Var(p.clone()))).collect(),
|
|
74
|
+
line: 0,
|
|
75
|
+
column: 0,
|
|
76
|
+
tail: TailKind::NotTail,
|
|
77
|
+
recv: None,
|
|
78
|
+
type_args: Vec::new(),
|
|
79
|
+
})
|
|
80
|
+
} else {
|
|
81
|
+
Expr::ClassCall(ClassCall {
|
|
82
|
+
type_name: n.clone(),
|
|
83
|
+
fields: c
|
|
84
|
+
.names
|
|
85
|
+
.iter()
|
|
86
|
+
.zip(¶ms)
|
|
87
|
+
.map(|(name, p)| FieldArg { name: name.clone(), value: Expr::Var(p.clone()) })
|
|
88
|
+
.collect(),
|
|
89
|
+
generics: Vec::new(),
|
|
90
|
+
spread: None,
|
|
91
|
+
unique: false,
|
|
92
|
+
reuse: None,
|
|
93
|
+
reboxed: Vec::new(),
|
|
94
|
+
})
|
|
95
|
+
};
|
|
96
|
+
let closure = Closure {
|
|
97
|
+
param_types: vec![None; params.len()],
|
|
98
|
+
params,
|
|
99
|
+
body: Block { stmts: vec![Stmt::new(StmtKind::Expr(call, 0, 0))] },
|
|
100
|
+
};
|
|
101
|
+
*e = Expr::Closure(Box::new(closure)).at(e);
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
}
|
compiler/core/src/lib.rs
CHANGED
|
@@ -11,6 +11,7 @@ pub mod closure_escape;
|
|
|
11
11
|
pub mod closure_spec;
|
|
12
12
|
pub mod compile_builtins;
|
|
13
13
|
pub mod ctors;
|
|
14
|
+
pub mod ctor_values;
|
|
14
15
|
pub mod diag;
|
|
15
16
|
pub mod drive;
|
|
16
17
|
pub mod enum_checks;
|
compiler/core/src/lower.rs
CHANGED
|
@@ -60,6 +60,8 @@ pub fn frontEndDiag(source: &mut Source) -> Result<(), Vec<Diagnostic>> {
|
|
|
60
60
|
if !questionErrors.is_empty() {
|
|
61
61
|
return Err(questionErrors);
|
|
62
62
|
}
|
|
63
|
+
// Before `lowerCtors`: a struct's constructor named as a value is a call to it.
|
|
64
|
+
crate::ctor_values::lowerCtorValues(source);
|
|
63
65
|
let ctorErrors = crate::ctors::lowerCtors(source);
|
|
64
66
|
if !ctorErrors.is_empty() {
|
|
65
67
|
return Err(diags(DiagKind::Type, ctorErrors));
|
compiler/wasm-codegen/src/closurecalls.rs
CHANGED
|
@@ -2,10 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
use crate::*;
|
|
4
4
|
|
|
5
|
-
/// Compiles a closure *literal* at its construction site.
|
|
5
|
+
/// Compiles a closure *literal* at its construction site: one `struct.new` of its own
|
|
6
|
-
/// free variable's CURRENT value into a fresh env struct (`struct.new`), then wraps
|
|
7
|
-
///
|
|
6
|
+
/// closure struct, the function's table index and each captured free variable's CURRENT
|
|
8
|
-
///
|
|
7
|
+
/// value. A literal that captures nothing is the one value its global holds.
|
|
9
8
|
pub(crate) fn compileClosureLiteral(
|
|
10
9
|
expr: &ast::Expr,
|
|
11
10
|
body: &mut Vec<u8>,
|
|
@@ -18,9 +17,10 @@ pub(crate) fn compileClosureLiteral(
|
|
|
18
17
|
.to_string()
|
|
19
18
|
})?;
|
|
20
19
|
|
|
21
|
-
|
|
20
|
+
if let Some(g) = info.global {
|
|
22
|
-
// env struct (snapshotting each captured free variable's current value from the
|
|
23
|
-
|
|
21
|
+
Instruction::GlobalGet(g).encode(body);
|
|
22
|
+
return Ok(());
|
|
23
|
+
}
|
|
24
24
|
Instruction::I32Const(info.table_idx as i32).encode(body);
|
|
25
25
|
for (name, fty) in &info.free_vars {
|
|
26
26
|
let local_idx = *ctx.locals.get(name).ok_or_else(|| {
|
|
@@ -33,13 +33,13 @@ pub(crate) fn compileClosureLiteral(
|
|
|
33
33
|
boxIfValue(fty, body);
|
|
34
34
|
}
|
|
35
35
|
Instruction::StructNew(info.env_type_idx).encode(body);
|
|
36
|
-
Instruction::StructNew(ctx.gc_types.closure_type_idx).encode(body);
|
|
37
36
|
Ok(())
|
|
38
37
|
}
|
|
39
38
|
|
|
40
|
-
/// Compiles a call to a closure-typed local
|
|
39
|
+
/// Compiles a call to a closure-typed local with the typed closure ABI: push the
|
|
41
|
-
/// closure
|
|
40
|
+
/// closure itself (the env), each argument in its own representation, then the
|
|
42
|
-
/// table index
|
|
41
|
+
/// table index its struct holds, and `call_indirect` at the signature's type. A local
|
|
42
|
+
/// of a `fn(..)` type is a `ref null $Closure`: the read needs no cast.
|
|
43
43
|
pub(crate) fn compileClosureCall(
|
|
44
44
|
call: &ast::FnCall,
|
|
45
45
|
_call_expr: &ast::Expr,
|
|
@@ -65,7 +65,6 @@ pub(crate) fn compileClosureCallArgs(
|
|
|
65
65
|
.locals
|
|
66
66
|
.get(name)
|
|
67
67
|
.ok_or_else(|| format!("codegen: closure '{}' is not a local", name))?;
|
|
68
|
-
let closure_type_idx = ctx.gc_types.closure_type_idx;
|
|
69
68
|
let Some(PlumType::TFun(ps, r)) = ctx.local_decl_types.get(name) else {
|
|
70
69
|
return Err(format!("codegen: '{}' is not a function-typed local", name));
|
|
71
70
|
};
|
|
@@ -76,14 +75,9 @@ pub(crate) fn compileClosureCallArgs(
|
|
|
76
75
|
name, key
|
|
77
76
|
)
|
|
78
77
|
})?;
|
|
78
|
+
let closure_idx = ctx.gc_types.closure_type_idx;
|
|
79
79
|
|
|
80
80
|
Instruction::LocalGet(closure_local).encode(body);
|
|
81
|
-
Instruction::RefCastNonNull(HeapType::Concrete(closure_type_idx)).encode(body);
|
|
82
|
-
Instruction::StructGet {
|
|
83
|
-
struct_type_index: closure_type_idx,
|
|
84
|
-
field_index: 1,
|
|
85
|
-
}
|
|
86
|
-
.encode(body);
|
|
87
81
|
for (i, arg) in args.iter().enumerate() {
|
|
88
82
|
match ps.get(i) {
|
|
89
83
|
Some(p) => compileExprInto(argExprOf(arg), p, body, ctx, state)?,
|
|
@@ -91,45 +85,29 @@ pub(crate) fn compileClosureCallArgs(
|
|
|
91
85
|
}
|
|
92
86
|
}
|
|
93
87
|
Instruction::LocalGet(closure_local).encode(body);
|
|
94
|
-
Instruction::
|
|
88
|
+
Instruction::StructGet { struct_type_index: closure_idx, field_index: 0 }.encode(body);
|
|
95
|
-
Instruction::StructGet {
|
|
96
|
-
struct_type_index: closure_type_idx,
|
|
97
|
-
field_index: 0,
|
|
98
|
-
}
|
|
99
|
-
.encode(body);
|
|
100
89
|
let ret_vts = key.1.clone();
|
|
101
90
|
if tailMode(tail, None, &ret_vts, r, ctx) == TailMode::Plain {
|
|
102
|
-
Instruction::CallIndirect {
|
|
91
|
+
Instruction::CallIndirect { type_index, table_index: 0 }.encode(body);
|
|
103
|
-
type_index,
|
|
104
|
-
table_index: 0,
|
|
105
|
-
}
|
|
106
|
-
.encode(body);
|
|
107
92
|
} else {
|
|
108
|
-
Instruction::ReturnCallIndirect {
|
|
93
|
+
Instruction::ReturnCallIndirect { type_index, table_index: 0 }.encode(body);
|
|
109
|
-
type_index,
|
|
110
|
-
table_index: 0,
|
|
111
|
-
}
|
|
112
|
-
.encode(body);
|
|
113
94
|
}
|
|
114
95
|
Ok(())
|
|
115
96
|
}
|
|
116
97
|
|
|
117
|
-
/// A closure calling itself by name: the running
|
|
98
|
+
/// A closure calling itself by name: the running closure (wasm local 0, its env) is
|
|
118
|
-
/// straight through
|
|
99
|
+
/// passed straight through to a direct call of its own function.
|
|
119
100
|
pub(crate) fn compileSelfClosureCall(
|
|
120
101
|
call: &ast::FnCall,
|
|
121
102
|
body: &mut Vec<u8>,
|
|
122
103
|
ctx: &LocalCtx,
|
|
123
104
|
state: &mut ModuleState,
|
|
124
105
|
) -> Result<(), String> {
|
|
125
|
-
let (_,
|
|
106
|
+
let (_, func_idx) = ctx.self_closure.as_ref().expect("self closure call");
|
|
126
107
|
let Some(PlumType::TFun(ps, r)) = ctx.local_decl_types.get(&call.name) else {
|
|
127
108
|
return Err(format!("codegen: '{}' is not a function-typed local", call.name));
|
|
128
109
|
};
|
|
129
110
|
let key = closureSigKey(ps, r, ctx.gc_types);
|
|
130
|
-
let type_index = *ctx.closure_call_types.get(&key).ok_or_else(|| {
|
|
131
|
-
format!("internal codegen error: no call_indirect type for closure '{}'", call.name)
|
|
132
|
-
})?;
|
|
133
111
|
Instruction::LocalGet(0).encode(body);
|
|
134
112
|
for (i, arg) in call.args.iter().enumerate() {
|
|
135
113
|
match ps.get(i) {
|
|
@@ -137,11 +115,10 @@ pub(crate) fn compileSelfClosureCall(
|
|
|
137
115
|
None => compileExpr(argExprOf(arg), body, ctx, state)?,
|
|
138
116
|
}
|
|
139
117
|
}
|
|
140
|
-
Instruction::I32Const(*table_idx as i32).encode(body);
|
|
141
118
|
if tailMode(call.tail, None, &key.1, r, ctx) == TailMode::Plain {
|
|
142
|
-
Instruction::
|
|
119
|
+
Instruction::Call(*func_idx).encode(body);
|
|
143
120
|
} else {
|
|
144
|
-
Instruction::
|
|
121
|
+
Instruction::ReturnCall(*func_idx).encode(body);
|
|
145
122
|
}
|
|
146
123
|
Ok(())
|
|
147
124
|
}
|
|
@@ -158,10 +135,11 @@ pub(crate) fn closureCallReturnsUnit(name: &str, ctx: &LocalCtx) -> bool {
|
|
|
158
135
|
}
|
|
159
136
|
|
|
160
137
|
/// Compiles a closure literal's own body into a standalone wasm function with the
|
|
161
|
-
/// typed closure ABI `(env:
|
|
138
|
+
/// typed closure ABI `(env: ref null $Closure, p1: T1, ..., pn: Tn) -> R` (see
|
|
162
|
-
/// Local 0 is the env; locals `1..=n` are the params
|
|
139
|
+
/// `ClosureSigKey`). Local 0 is the closure itself (its env); locals `1..=n` are the params
|
|
163
|
-
/// captured free variables (restored from the
|
|
140
|
+
/// in their own representation; captured free variables (restored from the closure's
|
|
141
|
+
/// struct, cast once to its own final type), the body's own named locals and scratch
|
|
164
|
-
///
|
|
142
|
+
/// slots follow.
|
|
165
143
|
pub(crate) fn compileClosureBody(
|
|
166
144
|
cl: &ast::Closure,
|
|
167
145
|
info: &ClosureInfo,
|
|
@@ -242,7 +220,11 @@ pub(crate) fn compileClosureBody(
|
|
|
242
220
|
idx += 1;
|
|
243
221
|
}
|
|
244
222
|
|
|
223
|
+
// The env cast to this literal's own struct once, for reading its captures.
|
|
224
|
+
let env_local = (!info.free_vars.is_empty()).then(|| {
|
|
225
|
+
groups.push(gcRef(info.env_type_idx));
|
|
245
|
-
|
|
226
|
+
idx
|
|
227
|
+
});
|
|
246
228
|
|
|
247
229
|
if groups.is_empty() {
|
|
248
230
|
body.push(0);
|
|
@@ -254,14 +236,19 @@ pub(crate) fn compileClosureBody(
|
|
|
254
236
|
}
|
|
255
237
|
}
|
|
256
238
|
|
|
257
|
-
// Restore each captured free variable from the
|
|
239
|
+
// Restore each captured free variable from the closure struct at entry (field 0 is
|
|
240
|
+
// the function).
|
|
258
|
-
|
|
241
|
+
if let Some(env_local) = env_local {
|
|
259
|
-
let local_idx = *locals.get(name).expect("free var local was assigned above");
|
|
260
242
|
Instruction::LocalGet(0).encode(&mut body);
|
|
261
243
|
Instruction::RefCastNonNull(HeapType::Concrete(info.env_type_idx)).encode(&mut body);
|
|
244
|
+
Instruction::LocalSet(env_local).encode(&mut body);
|
|
245
|
+
}
|
|
246
|
+
for (i, (name, _)) in info.free_vars.iter().enumerate() {
|
|
247
|
+
let local_idx = *locals.get(name).expect("free var local was assigned above");
|
|
248
|
+
Instruction::LocalGet(env_local.expect("a closure with captures has its env local")).encode(&mut body);
|
|
262
249
|
Instruction::StructGet {
|
|
263
250
|
struct_type_index: info.env_type_idx,
|
|
264
|
-
field_index: i as u32,
|
|
251
|
+
field_index: i as u32 + 1,
|
|
265
252
|
}
|
|
266
253
|
.encode(&mut body);
|
|
267
254
|
let fv_ty = &info.free_vars[i].1;
|
|
@@ -308,7 +295,7 @@ pub(crate) fn compileClosureBody(
|
|
|
308
295
|
}),
|
|
309
296
|
tail_depth: Cell::new(0),
|
|
310
297
|
import_count: ctx.import_count,
|
|
311
|
-
self_closure: info.self_name.clone().map(|n| (n, info.
|
|
298
|
+
self_closure: info.self_name.clone().map(|n| (n, info.func_idx)),
|
|
312
299
|
};
|
|
313
300
|
|
|
314
301
|
if matches!(info.ret_ptype, PlumType::TUnit) {
|
compiler/wasm-codegen/src/closures.rs
CHANGED
|
@@ -22,7 +22,7 @@ pub(crate) fn getClosureCallType(
|
|
|
22
22
|
if let Some(&t) = m.get(key) {
|
|
23
23
|
return t;
|
|
24
24
|
}
|
|
25
|
-
let mut params = vec![
|
|
25
|
+
let mut params = vec![gcRef(gcTypes().closure_type_idx)];
|
|
26
26
|
params.extend(key.0.iter().copied());
|
|
27
27
|
let results: Vec<ValType> = key.1.clone();
|
|
28
28
|
let t = module.addType(¶ms, &results);
|
compiler/wasm-codegen/src/context.rs
CHANGED
|
@@ -26,26 +26,29 @@ pub struct FuncSig {
|
|
|
26
26
|
|
|
27
27
|
/// Everything codegen needs to know about one closure *literal* found in the program.
|
|
28
28
|
/// wasm has no native closures: each literal `|v| body` becomes its own real wasm
|
|
29
|
-
/// function (registered in the funcref table), and a closure *value* is a `
|
|
29
|
+
/// function (registered in the funcref table), and a closure *value* is a `$Closure`
|
|
30
|
-
///
|
|
30
|
+
/// (`GcTypeRegistry::closure_type_idx`) whose first field is that function's table index.
|
|
31
|
-
///
|
|
31
|
+
/// A literal that captures values is an instance of its own final subtype of `$Closure`
|
|
32
|
-
/// (`env_type_idx`)
|
|
32
|
+
/// (`env_type_idx`) with one more field per captured (free) variable, in `free_vars`
|
|
33
|
+
/// order: one allocation per closure. The closure is its own env: the function gets it
|
|
34
|
+
/// as its first parameter.
|
|
33
35
|
pub struct ClosureInfo {
|
|
34
36
|
/// Reserved wasm function index for this closure's compiled body.
|
|
35
37
|
pub func_idx: u32,
|
|
36
|
-
/// Index of `func_idx` in the funcref table (the
|
|
38
|
+
/// Index of `func_idx` in the funcref table (the closure struct's first field).
|
|
37
|
-
/// struct's `table_idx` field).
|
|
38
39
|
pub table_idx: u32,
|
|
39
|
-
///
|
|
40
|
+
/// The struct type the literal builds: its own subtype of `$Closure` when it captures
|
|
40
|
-
/// order) — assigned once all closures are discovered, alongside every other
|
|
41
|
-
///
|
|
41
|
+
/// values (field 0 the table index, then `free_vars`), else `$Closure` itself.
|
|
42
42
|
pub env_type_idx: u32,
|
|
43
|
+
/// A literal that captures nothing is one value for the whole run: the global the
|
|
44
|
+
/// start function builds it into.
|
|
45
|
+
pub global: Option<u32>,
|
|
43
46
|
/// Closure param plum types (for the closure body's own type env).
|
|
44
47
|
pub param_ptypes: Vec<PlumType>,
|
|
45
48
|
/// Closure return plum type.
|
|
46
49
|
pub ret_ptype: PlumType,
|
|
47
50
|
/// Free variables captured by value, in a stable (first-appearance) order; the
|
|
48
|
-
/// index
|
|
51
|
+
/// variable at index `i` is field `i + 1` of the closure's struct (after the table index).
|
|
49
52
|
pub free_vars: Vec<(String, PlumType)>,
|
|
50
53
|
/// The local this literal is bound to (`name := |..| ..`): inside the body that
|
|
51
54
|
/// name refers to the closure itself.
|
|
@@ -53,9 +56,10 @@ pub struct ClosureInfo {
|
|
|
53
56
|
}
|
|
54
57
|
|
|
55
58
|
/// Closure ABI: every closure compiles to the wasm function type
|
|
56
|
-
/// `(env:
|
|
59
|
+
/// `(env: ref null $Closure, params...) -> result` for its own Plum signature, with every
|
|
57
|
-
/// value in its natural representation (no boxing);
|
|
60
|
+
/// value in its natural representation (no boxing); `env` is the closure value itself
|
|
61
|
+
/// (a `ref null $Closure`). A closure value is called with `call_indirect` of that type
|
|
58
|
-
///
|
|
62
|
+
/// on the table index its struct holds.
|
|
59
63
|
pub(crate) type ClosureSigKey = (Vec<ValType>, Vec<ValType>);
|
|
60
64
|
|
|
61
65
|
/// Global, read-only lookup tables shared by every function body being compiled.
|
|
@@ -84,10 +88,10 @@ pub struct CompileCtx<'a> {
|
|
|
84
88
|
/// The AST of each discovered closure literal, keyed the same way, so its body can
|
|
85
89
|
/// be compiled in a second pass after all closures are registered.
|
|
86
90
|
pub closure_asts: HashMap<(usize, usize), &'a ast::Closure>,
|
|
87
|
-
/// Closure signature -> its `call_indirect`
|
|
91
|
+
/// Closure signature -> its function type (`call_indirect`'s type index).
|
|
88
92
|
pub closure_call_types: HashMap<ClosureSigKey, u32>,
|
|
89
93
|
/// Top-level function name -> global index holding its zero-capture "trampoline"
|
|
90
|
-
/// closure struct `
|
|
94
|
+
/// closure struct (`$Closure` holding the trampoline's table index), for using a plain named function
|
|
91
95
|
/// wherever a `fn(...)`-typed value is expected (e.g. `each(double)`). Since the
|
|
92
96
|
/// struct has no captures it never changes, so it's built once by the shared
|
|
93
97
|
/// `start` function instead of being reconstructed per reference.
|
|
@@ -180,8 +184,9 @@ pub(crate) struct LocalCtx<'a> {
|
|
|
180
184
|
pub(crate) tail_depth: Cell<u32>,
|
|
181
185
|
/// Imported function count: calls to imports are never tail calls.
|
|
182
186
|
pub(crate) import_count: u32,
|
|
183
|
-
/// In a closure body bound as `name := |..| ..`: `name` and the closure's
|
|
187
|
+
/// In a closure body bound as `name := |..| ..`: `name` and the closure's wasm
|
|
184
|
-
///
|
|
188
|
+
/// function. The name resolves to the closure itself (the env, wasm local 0), and a
|
|
189
|
+
/// call of it calls that function directly.
|
|
185
190
|
pub(crate) self_closure: Option<(String, u32)>,
|
|
186
191
|
}
|
|
187
192
|
|
compiler/wasm-codegen/src/driver.rs
CHANGED
|
@@ -55,6 +55,18 @@ pub(crate) fn unitTypesOf<'t>(inst_types: &'t [UnitTypes], base_types: &'t UnitT
|
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
+
/// A global holding the closure `$Closure{table_idx}` (one that captures nothing), built
|
|
59
|
+
/// by the start function.
|
|
60
|
+
fn closureGlobal(module: &mut WasmModule, start_body: &mut Vec<u8>, closure_idx: u32, table_idx: u32) -> u32 {
|
|
61
|
+
let mut init = Vec::new();
|
|
62
|
+
Instruction::RefNull(HeapType::Concrete(closure_idx)).encode(&mut init);
|
|
63
|
+
let global_idx = module.addGlobal(gcRef(closure_idx), true, &init);
|
|
64
|
+
Instruction::I32Const(table_idx as i32).encode(start_body);
|
|
65
|
+
Instruction::StructNew(closure_idx).encode(start_body);
|
|
66
|
+
Instruction::GlobalSet(global_idx).encode(start_body);
|
|
67
|
+
global_idx
|
|
68
|
+
}
|
|
69
|
+
|
|
58
70
|
/// A fresh state for this compile: nothing carries over from a previous one.
|
|
59
71
|
pub(crate) fn resetGenState(source: &ast::Source) {
|
|
60
72
|
|
|
@@ -709,12 +721,12 @@ impl<'a> Setup<'a> {
|
|
|
709
721
|
withGen(|s| s.gc_types = Some(std::rc::Rc::new(gc_types.clone())));
|
|
710
722
|
}
|
|
711
723
|
|
|
712
|
-
/// Closure ABI: one
|
|
724
|
+
/// Closure ABI: one function type per Plum function signature.
|
|
713
725
|
pub(crate) fn registerClosureCallTypes(&mut self) {
|
|
714
726
|
let Setup { module, gc_types, type_funs, closure_call_types, .. } = self;
|
|
715
727
|
let gc_types = gc_types.as_mut().unwrap();
|
|
716
|
-
// Closure ABI: one
|
|
728
|
+
// Closure ABI: one function type per Plum function signature,
|
|
717
|
-
// `(env:
|
|
729
|
+
// `(env: ref null $Closure, params...) -> result`, with every value in its own representation.
|
|
718
730
|
for t in type_funs.iter() {
|
|
719
731
|
if let PlumType::TFun(ps, r) = t {
|
|
720
732
|
getClosureCallType(
|
|
@@ -795,58 +807,44 @@ impl<'a> Setup<'a> {
|
|
|
795
807
|
}
|
|
796
808
|
}
|
|
797
809
|
|
|
798
|
-
/// One
|
|
810
|
+
/// One final subtype of `$Closure` per closure literal that captures values: the
|
|
811
|
+
/// table index, then the captured values (see `GcTypeRegistry::closure_type_idx`).
|
|
799
812
|
pub(crate) fn registerClosureTypes(&mut self) {
|
|
800
813
|
let Setup { module, gc_types, raw_closures, closure_type_indices, .. } = self;
|
|
801
814
|
let gc_types = gc_types.as_mut().unwrap();
|
|
815
|
+
let base = module.next_type_idx;
|
|
802
|
-
let mut
|
|
816
|
+
let mut subtypes: Vec<SubType> = Vec::new();
|
|
803
|
-
is_final: true,
|
|
804
|
-
supertype_idx: None,
|
|
805
|
-
|
|
817
|
+
closure_type_indices.clear();
|
|
806
|
-
inner: CompositeInnerType::Struct(StructType {
|
|
807
|
-
fields: vec![
|
|
808
|
-
FieldType {
|
|
809
|
-
element_type: StorageType::Val(ValType::I32),
|
|
810
|
-
mutable: false,
|
|
811
|
-
},
|
|
812
|
-
FieldType {
|
|
813
|
-
element_type: StorageType::Val(ValType::Ref(RefType::ANYREF)),
|
|
814
|
-
mutable: false,
|
|
815
|
-
},
|
|
816
|
-
]
|
|
817
|
-
.into(),
|
|
818
|
-
}),
|
|
819
|
-
shared: false,
|
|
820
|
-
},
|
|
821
|
-
}];
|
|
822
818
|
for (_, rc) in raw_closures.iter() {
|
|
819
|
+
if rc.free_vars.is_empty() {
|
|
823
|
-
|
|
820
|
+
closure_type_indices.push(gc_types.closure_type_idx);
|
|
824
|
-
.free_vars
|
|
825
|
-
|
|
821
|
+
continue;
|
|
822
|
+
}
|
|
823
|
+
let mut fields = vec![FieldType { element_type: StorageType::Val(ValType::I32), mutable: false }];
|
|
826
|
-
|
|
824
|
+
fields.extend(rc.free_vars.iter().map(|(_, ty)| FieldType {
|
|
827
|
-
|
|
825
|
+
element_type: StorageType::Val(plumTypeToValtype(ty)),
|
|
828
|
-
|
|
826
|
+
mutable: false,
|
|
829
|
-
|
|
827
|
+
}));
|
|
830
|
-
|
|
828
|
+
closure_type_indices.push(base + subtypes.len() as u32);
|
|
831
|
-
|
|
829
|
+
subtypes.push(SubType {
|
|
832
830
|
is_final: true,
|
|
833
|
-
supertype_idx:
|
|
831
|
+
supertype_idx: Some(gc_types.closure_type_idx),
|
|
834
832
|
composite_type: CompositeType {
|
|
835
|
-
inner: CompositeInnerType::Struct(StructType {
|
|
833
|
+
inner: CompositeInnerType::Struct(StructType { fields: fields.into() }),
|
|
836
|
-
fields: field_types.into(),
|
|
837
|
-
}),
|
|
838
834
|
shared: false,
|
|
839
835
|
},
|
|
840
836
|
});
|
|
841
837
|
}
|
|
838
|
+
if !subtypes.is_empty() {
|
|
842
|
-
|
|
839
|
+
let got = module.addGcTypes(subtypes);
|
|
843
|
-
|
|
840
|
+
debug_assert_eq!(got.first().copied(), Some(base));
|
|
844
|
-
|
|
841
|
+
}
|
|
845
842
|
}
|
|
846
843
|
|
|
847
|
-
/// One reserved function
|
|
844
|
+
/// One reserved function and table slot per closure literal; a literal that captures
|
|
845
|
+
/// nothing is built once, into a global, by the start function.
|
|
848
846
|
pub(crate) fn registerClosureFns(&mut self) {
|
|
849
|
-
let Setup { module, gc_types, units, raw_closures, closure_type_indices, closure_call_types, closures, closure_asts, .. } = self;
|
|
847
|
+
let Setup { module, gc_types, units, raw_closures, closure_type_indices, closure_call_types, closures, closure_asts, start_body, .. } = self;
|
|
850
848
|
let gc_types = gc_types.as_mut().unwrap();
|
|
851
849
|
// A unit's closures are named `f.closure`, `f.closure2`, ... in source order, so a
|
|
852
850
|
// backtrace tells them apart.
|
|
@@ -860,12 +858,15 @@ impl<'a> Setup<'a> {
|
|
|
860
858
|
let suffix = if *nth == 1 { String::new() } else { nth.to_string() };
|
|
861
859
|
module.nameFunction(func_idx, &format!("{}.closure{suffix}", units[*ui].name));
|
|
862
860
|
let table_idx = module.addTableElement(func_idx);
|
|
861
|
+
let env_type_idx = closure_type_indices[i];
|
|
862
|
+
let global = rc.free_vars.is_empty().then(|| closureGlobal(module, start_body, env_type_idx, table_idx));
|
|
863
863
|
closures.insert(
|
|
864
864
|
(*ui, rc.ptr),
|
|
865
865
|
ClosureInfo {
|
|
866
866
|
func_idx,
|
|
867
867
|
table_idx,
|
|
868
|
-
env_type_idx
|
|
868
|
+
env_type_idx,
|
|
869
|
+
global,
|
|
869
870
|
param_ptypes: rc.param_ptypes.clone(),
|
|
870
871
|
ret_ptype: rc.ret_ptype.clone(),
|
|
871
872
|
free_vars: rc.free_vars.clone(),
|
|
@@ -902,16 +903,8 @@ impl<'a> Setup<'a> {
|
|
|
902
903
|
let func_idx = module.addFunction(type_idx, &tbody);
|
|
903
904
|
module.nameFunction(func_idx, &format!("{}.trampoline", name));
|
|
904
905
|
let table_idx = module.addTableElement(func_idx);
|
|
905
|
-
|
|
906
|
-
let mut init = Vec::new();
|
|
907
|
-
Instruction::RefNull(HeapType::Concrete(gc_types.closure_type_idx)).encode(&mut init);
|
|
908
|
-
let global_idx =
|
|
906
|
+
let global_idx = closureGlobal(module, start_body, gc_types.closure_type_idx, table_idx);
|
|
909
907
|
named_fn_values.insert((name.clone(), fty.clone()), global_idx);
|
|
910
|
-
|
|
911
|
-
Instruction::I32Const(table_idx as i32).encode(start_body);
|
|
912
|
-
Instruction::RefNull(HeapType::ANY).encode(start_body);
|
|
913
|
-
Instruction::StructNew(gc_types.closure_type_idx).encode(start_body);
|
|
914
|
-
Instruction::GlobalSet(global_idx).encode(start_body);
|
|
915
908
|
}
|
|
916
909
|
}
|
|
917
910
|
|
compiler/wasm-codegen/src/expr.rs
CHANGED
|
@@ -154,12 +154,9 @@ fn compileExprNode(
|
|
|
154
154
|
// value (e.g. `each(double)`) — push its zero-capture trampoline
|
|
155
155
|
// closure's (pre-built by the `start` function) global.
|
|
156
156
|
None if ctx.self_closure.as_ref().is_some_and(|(n, _)| n == name) => {
|
|
157
|
-
// The closure's own name used as a value:
|
|
157
|
+
// The closure's own name used as a value: the running closure,
|
|
158
|
-
//
|
|
158
|
+
// which is its own env (wasm local 0).
|
|
159
|
-
let (_, table_idx) = ctx.self_closure.as_ref().expect("just checked");
|
|
160
|
-
Instruction::I32Const(*table_idx as i32).encode(body);
|
|
161
159
|
Instruction::LocalGet(0).encode(body);
|
|
162
|
-
Instruction::StructNew(ctx.gc_types.closure_type_idx).encode(body);
|
|
163
160
|
}
|
|
164
161
|
None => {
|
|
165
162
|
let fty = namedRefType(name, expr, ctx.types, ctx.func_sigs);
|
compiler/wasm-codegen/src/gctypes.rs
CHANGED
|
@@ -87,10 +87,13 @@ pub struct GcTypeRegistry {
|
|
|
87
87
|
/// storage of `Str` (`Str(data, start, len)`, see `std/Str.plum`) and
|
|
88
88
|
/// `Buffer`.
|
|
89
89
|
pub byte_array_type_idx: u32,
|
|
90
|
+
/// `$Closure`, `(sub (struct (field i32)))`: the type of every closure value (a
|
|
91
|
+
/// `fn(..)` is a `ref null $Closure`), its one field the table index of the function a
|
|
92
|
+
/// call runs (`call_indirect` at the signature's type). A closure literal that captures
|
|
93
|
+
/// values is an instance of its own final subtype with one more field per captured
|
|
94
|
+
/// value (`ClosureInfo::env_type_idx`), so building it is one allocation, and calling
|
|
95
|
+
/// it needs no cast. Not a typed funcref field: wasmtime reads and writes a funcref in
|
|
90
|
-
///
|
|
96
|
+
/// a GC object through a host call, where a table index is a plain load.
|
|
91
|
-
/// anyref}` — every closure (and zero-capture "trampoline") uses regardless of
|
|
92
|
-
/// its own captures; only assigned once closures are discovered (see
|
|
93
|
-
/// `compileSource`), so `0` until then (nothing reads it earlier).
|
|
94
97
|
pub closure_type_idx: u32,
|
|
95
98
|
/// The single shared `array<anyref>` type index every `Array<T>`
|
|
96
99
|
/// uses regardless of its own `T`. `0` (the `Str` slot,
|
|
@@ -287,7 +290,7 @@ pub(crate) fn plumTypeToGcValtype(t: &PlumType, registry: &GcTypeRegistry) -> Va
|
|
|
287
290
|
Some(idx) => gcRef(*idx),
|
|
288
291
|
None => ValType::Ref(RefType::ANYREF),
|
|
289
292
|
},
|
|
290
|
-
PlumType::TFun(_, _) =>
|
|
293
|
+
PlumType::TFun(_, _) => gcRef(registry.closure_type_idx),
|
|
291
294
|
PlumType::TParam(_) => ValType::Ref(RefType::ANYREF),
|
|
292
295
|
PlumType::TVar(_) | PlumType::TUnit => ValType::I64,
|
|
293
296
|
}
|
|
@@ -325,13 +328,14 @@ pub(crate) fn buildGcTypeRegistry(
|
|
|
325
328
|
) -> GcTypeRegistry {
|
|
326
329
|
enum Slot {
|
|
327
330
|
Str,
|
|
331
|
+
Closure,
|
|
328
332
|
Obj,
|
|
329
333
|
EnumSuper(PlumType),
|
|
330
334
|
Variant(PlumType, String),
|
|
331
335
|
ArrayRef(ValType),
|
|
332
336
|
ArraySoa(Vec<ValType>),
|
|
333
337
|
}
|
|
334
|
-
let mut slots: Vec<Slot> = vec![Slot::Str];
|
|
338
|
+
let mut slots: Vec<Slot> = vec![Slot::Str, Slot::Closure];
|
|
335
339
|
let mut reg = GcTypeRegistry {
|
|
336
340
|
class_type_idx: HashMap::new(),
|
|
337
341
|
enum_super_type_idx: HashMap::new(),
|
|
@@ -342,7 +346,7 @@ pub(crate) fn buildGcTypeRegistry(
|
|
|
342
346
|
instances: Vec::new(),
|
|
343
347
|
known_enums: HashSet::new(),
|
|
344
348
|
byte_array_type_idx: 0,
|
|
345
|
-
closure_type_idx:
|
|
349
|
+
closure_type_idx: 1,
|
|
346
350
|
array_type_idx: 0,
|
|
347
351
|
leaf_array_idx: HashMap::new(),
|
|
348
352
|
mk_str_fn: None,
|
|
@@ -545,6 +549,14 @@ pub(crate) fn buildGcTypeRegistry(
|
|
|
545
549
|
shared: false,
|
|
546
550
|
},
|
|
547
551
|
},
|
|
552
|
+
Slot::Closure => SubType {
|
|
553
|
+
is_final: false,
|
|
554
|
+
supertype_idx: None,
|
|
555
|
+
composite_type: CompositeType {
|
|
556
|
+
inner: CompositeInnerType::Struct(StructType { fields: vec![tagField()].into() }),
|
|
557
|
+
shared: false,
|
|
558
|
+
},
|
|
559
|
+
},
|
|
548
560
|
Slot::Obj => SubType {
|
|
549
561
|
is_final: false,
|
|
550
562
|
supertype_idx: None,
|
compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs
CHANGED
|
@@ -1310,11 +1310,8 @@ fun main() -> Int =\n Main.apply(|n| n + 1, 41)\n",
|
|
|
1310
1310
|
for g in s {
|
|
1311
1311
|
for t in g.unwrap().types() {
|
|
1312
1312
|
if let wasmparser::CompositeInnerType::Func(f) = &t.composite_type.inner {
|
|
1313
|
-
|
|
1313
|
+
// `(env: ref null $Closure, i64) -> i64`: the closure is its own env.
|
|
1314
|
-
== [
|
|
1315
|
-
|
|
1314
|
+
if matches!(f.params(), [wasmparser::ValType::Ref(r), wasmparser::ValType::I64] if r.is_nullable() && r.type_index().is_some())
|
|
1316
|
-
wasmparser::ValType::I64,
|
|
1317
|
-
]
|
|
1318
1315
|
&& f.results() == [wasmparser::ValType::I64]
|
|
1319
1316
|
{
|
|
1320
1317
|
found = true;
|
|
@@ -1324,7 +1321,7 @@ fun main() -> Int =\n Main.apply(|n| n + 1, 41)\n",
|
|
|
1324
1321
|
}
|
|
1325
1322
|
}
|
|
1326
1323
|
}
|
|
1327
|
-
assert!(found, "no (
|
|
1324
|
+
assert!(found, "no (ref null $Closure, i64) -> i64 closure type");
|
|
1328
1325
|
}
|
|
1329
1326
|
|
|
1330
1327
|
// ---- built-in Bool (i32; no `import std/Bool`) ----
|
|
@@ -1732,6 +1729,74 @@ fn value_nested_pattern_mixed() {
|
|
|
1732
1729
|
assert_eq!(runMerged::<i64>("value_nested_pattern_mixed", &src), 1);
|
|
1733
1730
|
}
|
|
1734
1731
|
|
|
1732
|
+
// ---------------------------------------------------------------------------
|
|
1733
|
+
// Closure values: one struct each, called with no cast
|
|
1734
|
+
// ---------------------------------------------------------------------------
|
|
1735
|
+
|
|
1736
|
+
#[test]
|
|
1737
|
+
fn closureIsOneStructAndItsCallNeedsNoCast() {
|
|
1738
|
+
let src = format!(
|
|
1739
|
+
"{STD_HEAD}\
|
|
1740
|
+
enum Fns =
|
|
1741
|
+
| More(f: fn(Int) -> Int, rest: Fns)
|
|
1742
|
+
| Done
|
|
1743
|
+
|
|
1744
|
+
primitive Main[App] =
|
|
1745
|
+
fun build(n: Int, k: Int, acc: Fns) -> Fns = if n == 0 then acc else build(n - 1, k, More(f: |x| x * k + n, rest: acc))
|
|
1746
|
+
|
|
1747
|
+
fun run(fs: Fns, x: Int) -> Int = match fs
|
|
1748
|
+
Done => x
|
|
1749
|
+
More(f, rest) => run(rest, f(x))
|
|
1750
|
+
|
|
1751
|
+
fun main() -> Int = run(build(3, 2, Done), 1)
|
|
1752
|
+
"
|
|
1753
|
+
);
|
|
1754
|
+
let (bytes, _) = compiledKeys("closure_one_struct", &src);
|
|
1755
|
+
// The closure (its table index and both captures) and the `More` cell: one `struct.new`
|
|
1756
|
+
// each, in `build` (or the loop fusion made of `run(build(..))`).
|
|
1757
|
+
let builds: Vec<Vec<String>> = namedBodies(&bytes)
|
|
1758
|
+
.into_iter()
|
|
1759
|
+
.filter(|(n, _)| n.contains("build") && !n.contains("closure"))
|
|
1760
|
+
.map(|(_, ops)| ops)
|
|
1761
|
+
.collect();
|
|
1762
|
+
assert!(!builds.is_empty());
|
|
1763
|
+
for build in &builds {
|
|
1764
|
+
assert_eq!(countOps(build, "StructNew"), 2, "{build:?}");
|
|
1765
|
+
}
|
|
1766
|
+
// The call reads the table index straight from the `fn(Int) -> Int` value.
|
|
1767
|
+
let run = opsOf(&bytes, "Main.run");
|
|
1768
|
+
let at: Vec<usize> = run.iter().enumerate().filter(|(_, o)| o.starts_with("CallIndirect")).map(|(i, _)| i).collect();
|
|
1769
|
+
assert_eq!(at.len(), 1, "{run:?}");
|
|
1770
|
+
assert!(run[at[0] - 1].starts_with("StructGet") && run[at[0] - 2].starts_with("LocalGet"), "{run:?}");
|
|
1771
|
+
// The body casts its env once, to its own final struct, and reads both captures.
|
|
1772
|
+
let body = opsOf(&bytes, "Main.build.closure");
|
|
1773
|
+
assert_eq!(countOps(&body, "RefCast"), 1, "{body:?}");
|
|
1774
|
+
assert_eq!(countOps(&body, "StructGet"), 2, "{body:?}");
|
|
1775
|
+
// f1, f2, f3 on 1: 1 * 2 + 1, then * 2 + 2, then * 2 + 3.
|
|
1776
|
+
assert_eq!(runMerged::<i64>("closure_one_struct_run", &src), 19);
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
#[test]
|
|
1780
|
+
fn closureThatCapturesNothingIsBuiltOnce() {
|
|
1781
|
+
let src = format!(
|
|
1782
|
+
"{STD_HEAD}\
|
|
1783
|
+
primitive Main[App] =
|
|
1784
|
+
fun twice(f: fn(Int) -> Int, x: Int) -> Int = f(f(x))
|
|
1785
|
+
|
|
1786
|
+
fun pick(b: Bool) -> fn(Int) -> Int = if b then |x| x + 1 else |x| x * 3
|
|
1787
|
+
|
|
1788
|
+
fun main() -> Int = twice(pick(true), 1) * 100 + twice(pick(false), 1)
|
|
1789
|
+
"
|
|
1790
|
+
);
|
|
1791
|
+
let (bytes, _) = compiledKeys("closure_no_capture", &src);
|
|
1792
|
+
// `pick` (inlined into `main` or not) takes them from their globals.
|
|
1793
|
+
for (n, ops) in namedBodies(&bytes).into_iter().filter(|(n, _)| n == "main" || n == "Main.pick") {
|
|
1794
|
+
assert_eq!(countOps(&ops, "StructNew"), 0, "{n}: {ops:?}");
|
|
1795
|
+
assert!(countOps(&ops, "GlobalGet") >= 1, "{n}: {ops:?}");
|
|
1796
|
+
}
|
|
1797
|
+
assert_eq!(runMerged::<i64>("closure_no_capture_run", &src), 309);
|
|
1798
|
+
}
|
|
1799
|
+
|
|
1735
1800
|
// ---------------------------------------------------------------------------
|
|
1736
1801
|
// `for x := range v`: lowered inline, so no closures
|
|
1737
1802
|
// ---------------------------------------------------------------------------
|
|
@@ -1772,7 +1837,7 @@ primitive Main[App] =
|
|
|
1772
1837
|
let looped = namedBodies(&bytes).into_iter().find(|(n, _)| n.contains("@loop")).expect("the loop function compiled").1;
|
|
1773
1838
|
assert_eq!(countOps(&looped, "RefFunc") + countOps(&looped, "CallIndirect") + countOps(&looped, "CallRef"), 0, "{looped:?}");
|
|
1774
1839
|
assert_eq!(runMerged::<i64>("formfilter_run", &form), 2);
|
|
1775
|
-
// the closure-method version
|
|
1840
|
+
// the closure-method version calls through the table
|
|
1776
1841
|
let closure = format!(
|
|
1777
1842
|
"{STD_HEAD}\
|
|
1778
1843
|
primitive Main[App] =
|
|
@@ -1785,8 +1850,8 @@ primitive Main[App] =
|
|
|
1785
1850
|
);
|
|
1786
1851
|
let (cbytes, _) = compiledKeys("closurefilter", &closure);
|
|
1787
1852
|
let cops = opsOf(&cbytes, "main");
|
|
1788
|
-
//
|
|
1853
|
+
// `keep` captures nothing: one closure value, built by the start function into a global.
|
|
1789
|
-
assert!(countOps(&cops, "
|
|
1854
|
+
assert!(countOps(&cops, "GlobalGet") >= 1, "closure main reads the closure's global: {cops:?}");
|
|
1790
1855
|
// the call through the closure is in `retainList`'s loop function
|
|
1791
1856
|
let calls: usize = namedBodies(&cbytes)
|
|
1792
1857
|
.into_iter()
|
docs/backlog.md
CHANGED
|
@@ -25,11 +25,11 @@ The retained scene tree was replaced by master's screen view in functional form:
|
|
|
25
25
|
- **Compile time is worse than on 2026-11-10 morning**: 1.32x CPU for Orb Run (538 to 708 ms), 1.40x Balloon Pop, 2.0x for a small program, even after a 30% speed-up of the passes. Causes measured or likely: programs reach more std (+17% items for Orb Run), the in-place pass is now its own pass with its own re-check, the loader's threads add CPU. The program is still checked about 7 times per compile. Re-checking only changed functions was tried and dropped: type info is keyed by node id and instantiation numbering depends on whole-program order, so the output would change. Needs stable ids first. Pruning std before the first check fails because loop and `?` lowering add calls the raw program does not name.
|
|
26
26
|
- **Only the parse is cached per file** (`parse_cache`, 2026-11-16). Checking a module once and reusing it in every program that imports it, as Roc does, needs a checker that works module by module. Today's is whole-program. The loader merges every file into one program before anything after the parse. `resolveModules` renames functions that several files of the program define. `shadowStdTypes` rewrites and re-parses std's text when the importer declares a std type's name. Generic bodies are checked once per instantiation, starting from call sites anywhere in the program (with the importer's types). Trait-object calls reach the importer's implementers. Type info is keyed by node ids numbered over the merged program. Measured with a debug build on Map's tests: load 90 ms (parse 30 to 40 of it), first check 130 ms, then 5 re-checks of about 48 ms each and the passes. The front end is about 15% of a `plum test` file; a `plum check` file is about half parse and half check.
|
|
27
27
|
- **`Map` reuse stops as soon as any map in the program is shared.** A uniquely owned map is now updated in its own cells (the `map` workload went from 479 to 281 ms; the old hash table took about 200), and `Int`, `Byte` and `Float.compare` are native and inlined. But field uniqueness is decided per type over the whole program, so one kept old version of a `Map` anywhere turns deep reuse off for every `Map`: Orb Run gets none. Reuse alongside sharing needs a per-value deep-uniqueness analysis. Also open: `Map.get` allocates an `Option` on a hit (fusion treats `Map.get` as an impure producer).
|
|
28
|
-
- **Closure calls
|
|
28
|
+
- **Closure calls go through the table** (since U4a, 2026-11-16). A `fn(..)` value is a `ref null $Closure` (`struct {i32 table index}`), and a closure that captures values is its own final subtype with the captures as fields: one allocation (none for a closure that captures nothing: a global built at start), no cast at the call (`struct.get` then `call_indirect`), one cast to a final type in the body. Not `call_ref` on a typed funcref field: wasmtime 47 reads and writes a funcref inside a GC object through a host call (`get_interned_func_ref`), which made Orbit Runner's update 2-3x slower when tried, and a cast to a non-final type that the value only subtypes is a host call too (`is_subtype`), so a `fn` read out of a `Slice` (an `anyref` array) still pays one. Release, interleaved, min of 9 (the machine was loaded): orbit update 13.4 to 12.2 ms, Orb Run 40.7 to 38.2, `benchmarks/closures/calls` 179 to 165; orbit paint, Clockwork, Balloon Pop, `cons`, `cons_rec` within noise (their closures are inlined by closure specialisation or not hot). Left: the table bounds and signature check of `call_indirect`, and the env cast in each capturing body.
|
|
29
29
|
- **A value struct inside an enum payload is boxed twice** (`Some(Pos)` allocates two objects). No measurement yet.
|
|
30
30
|
- **In-place updates still miss** 36 of Orb Run's 56 spreads. Reasons, by count: a value rebound by a pattern (8), the receiver read again after a method call (5), a shared value (4), a field passed on without being written back (4), an argument passed from inside a closure (4).
|
|
31
31
|
- **Static functions are slower than free functions** (0.78 s against 0.57 s on `benchmarks/static_calls`).
|
|
32
|
-
- **Which closures are inlined depends on the whole program**: closure specialisation copies a callee for at most 8 closures program-wide (`closure_spec::MAX_COPIES`), in the order it meets them, so a closure-taking walk added anywhere (std's `List.filter`, `any`) can turn another call of the same walk back into a closure call (`
|
|
32
|
+
- **Which closures are inlined depends on the whole program**: closure specialisation copies a callee for at most 8 closures program-wide (`closure_spec::MAX_COPIES`), in the order it meets them, so a closure-taking walk added anywhere (std's `List.filter`, `any`) can turn another call of the same walk back into a closure call (`call_indirect`, slower). In-place updates no longer depend on it (U1). A cap per caller, or copies ranked by how hot the caller is, would make it stable.
|
|
33
33
|
- **Smaller codegen items**: match arms test then cast (`br_on_cast` would do one check); the inliner skips leaves that use their locals (`unbox.*`); every struct has its own empty supertype; purity treats every closure-taking function as impure, so pipelines fuse only after closure specialisation.
|
|
34
34
|
- No evidence either way, so not planned: unchecked reads in `for` over a `Slice` (checked `at` showed no cost).
|
|
35
35
|
|
docs/game.md
CHANGED
|
@@ -62,7 +62,7 @@ struct TapScreen[ScreenSlice<TapAction>](taps: Int, ball: Ball) =
|
|
|
62
62
|
fun subscriptions(self) -> List<Sub<TapAction>> = [
|
|
63
63
|
OnKeyDown(key: Key.Escape, act: Quit)
|
|
64
64
|
OnHeld(|h| Push(dx: if h.isKeyDown(Key.Right) then 100.0 else 0.0))
|
|
65
|
-
OnFrame(
|
|
65
|
+
OnFrame(Tick)
|
|
66
66
|
]
|
|
67
67
|
|
|
68
68
|
fun update(self, a: TapAction) -> Next<TapScreen, TapAction> = match a
|
|
@@ -158,7 +158,7 @@ Its motion is a `Body` (below), which `Steps` steps for it: its own `step` is it
|
|
|
158
158
|
|
|
159
159
|
**Timers are moments.** Nothing counts down: a ship hit is hurt until a moment on its own clock, `hurtFor(t)` is `Ship(..self, hurtUntil: self.clock + t)` and `hurt()` is `self.clock < self.hurtUntil`, as a balloon keeps `poppedAt` and Balloon Pop's party `partyAt`.
|
|
160
160
|
|
|
161
|
-
**Stepping.** There is no stepping phase: the frame reaches a slice screen as an action (`OnFrame(
|
|
161
|
+
**Stepping.** There is no stepping phase: the frame reaches a slice screen as an action (`OnFrame(Tick)`), and its `update` steps its actors there with `stepped(dt)`, then runs its rules on what has moved. On master the game walks the view and the hud and steps each `Actor` it finds in place; here a screen is a value, and an actor found in a view can't be put back into the field that holds it, so the screen's own fields are stepped. Every screen has its `stepped` derived by the compiler (it lists nothing for it): each field that is an `Actor`, a value whose type has its own `step(self, dt: Float) -> Self` (a `Body`), a `List` of either (of one type, or of a trait type that is an `Actor`), an `Option` of one or a `List<View>` is stepped, and the other fields are as they are. Orbit Runner's:
|
|
162
162
|
|
|
163
163
|
```plum
|
|
164
164
|
struct PlayingScreen[ScreenSlice<PlayAction>](
|
|
@@ -372,7 +372,7 @@ A screen with no actions writes neither: the defaults keep it as it is. Orbit Ru
|
|
|
372
372
|
|
|
373
373
|
```plum
|
|
374
374
|
fun subscriptions(self) -> List<Sub<PlayAction>> = [
|
|
375
|
-
OnFrame(
|
|
375
|
+
OnFrame(Tick)
|
|
376
376
|
if !self.over then OnHeld(|h| PlayingScreen.steering(h))
|
|
377
377
|
if self.over then OnKeyDown(key: Key.Enter, act: StartOver)
|
|
378
378
|
if self.over then OnKeyDown(key: Key.KeyR, act: StartOver)
|
|
@@ -381,7 +381,7 @@ fun subscriptions(self) -> List<Sub<PlayAction>> = [
|
|
|
381
381
|
|
|
382
382
|
| `Sub<A>` | The action |
|
|
383
383
|
|---|---|
|
|
384
|
-
| `OnFrame(act)` | `act(dt)` each tick, last: the frame, which steps the actors and runs the rules |
|
|
384
|
+
| `OnFrame(act)` | `act(dt)` each tick, last: the frame, which steps the actors and runs the rules. `OnFrame(Tick)` for an action `Tick(dt: Float)`: a constructor is the function that builds it |
|
|
385
385
|
| `OnKeyDown(key, act)`, `OnKeyUp(key, act)` | `act` when that key goes down, or up |
|
|
386
386
|
| `OnHeld(act)` | `act(h)` each tick, with what is held after the tick's events (`Held`): the steering keys. It also wakes an `OnDemand` screen while something is held |
|
|
387
387
|
| `OnWheel(act)` | `act(dy, at)` for a turn of the wheel, `at` where the pointer is, in the world |
|
docs/language.md
CHANGED
|
@@ -595,6 +595,8 @@ Add a type when the compiler can't work one out: `|b: Box| b.get()`. Passing a c
|
|
|
595
595
|
|
|
596
596
|
A static is a value too (`Closures.apply(Numbers.sign, 5)`), unless it is generic, `extern` or a static of a generic type (`Holder<T>`'s): wrap those in a closure, `|x| Ids.id(x)`.
|
|
597
597
|
|
|
598
|
+
A constructor is a value too: a struct or a variant with fields, named without arguments, is the function that builds it from all its fields, in order (defaulted ones too). For `Tick(dt: Float)`, `OnFrame(Tick)` is `OnFrame(|dt| Tick(dt: dt))`; `[1, 2].map(Some)` is a `List<Option<Int>>`, and `mk := Point` is a `fn(Int, Int) -> Point`. A variant with no fields is already a value (`Nil`), and a struct with a `fun init(self)` isn't one: wrap it, `|x, tex| Ship(x, tex)`.
|
|
599
|
+
|
|
598
600
|
## Generics
|
|
599
601
|
|
|
600
602
|
Declare type parameters in `< >` after the name. The name can be anything.
|
examples/games/balloonpop/screens/PlaygroundScreen.plum
CHANGED
|
@@ -69,7 +69,7 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
|
|
|
69
69
|
]
|
|
70
70
|
|
|
71
71
|
fun subscriptions(self) -> List<Sub<PopAction>> = [
|
|
72
|
-
OnFrame(
|
|
72
|
+
OnFrame(Tick)
|
|
73
73
|
OnKeyDown(key: Key.KeyZ, act: TakeBack)
|
|
74
74
|
OnKeyDown(key: Key.Backspace, act: TakeBack)
|
|
75
75
|
]
|
examples/games/clicks.plum
CHANGED
|
@@ -46,7 +46,7 @@ struct TapScreen[ScreenSlice<TapAction>](taps: Int, ball: Ball) =
|
|
|
46
46
|
fun subscriptions(self) -> List<Sub<TapAction>> = [
|
|
47
47
|
OnKeyDown(key: Key.Escape, act: Quit)
|
|
48
48
|
OnHeld(|h| Push(dx: if h.isKeyDown(Key.Right) then 100.0 else 0.0))
|
|
49
|
-
OnFrame(
|
|
49
|
+
OnFrame(Tick)
|
|
50
50
|
]
|
|
51
51
|
|
|
52
52
|
fun update(self, a: TapAction) -> Next<TapScreen, TapAction> = match a
|
examples/games/clockwork/screens/OrreryScreen.plum
CHANGED
|
@@ -82,7 +82,7 @@ struct OrreryScreen[ScreenSlice<SkyAction>](
|
|
|
82
82
|
fun subscriptions(self) -> List<Sub<SkyAction>> = [
|
|
83
83
|
OnKeyDown(key: Key.Space, act: TogglePause)
|
|
84
84
|
OnPointerDown(|at| Pick(body: -1))
|
|
85
|
-
OnFrame(
|
|
85
|
+
OnFrame(Tick)
|
|
86
86
|
]
|
|
87
87
|
|
|
88
88
|
fun update(self, a: SkyAction) -> Next<OrreryScreen, SkyAction> = match a
|
examples/games/menu/screens/MenuScreen.plum
CHANGED
|
@@ -61,7 +61,7 @@ struct MenuScreen[ScreenSlice<MenuAction>](selected: Int, highlight: Tween) =
|
|
|
61
61
|
OnKeyDown(key: Key.Down, act: MoveBy(step: 1))
|
|
62
62
|
OnKeyDown(key: Key.Enter, act: Choose)
|
|
63
63
|
OnKeyDown(key: Key.Space, act: Choose)
|
|
64
|
-
OnFrame(
|
|
64
|
+
OnFrame(Tick)
|
|
65
65
|
]
|
|
66
66
|
|
|
67
67
|
fun update(self, a: MenuAction) -> Next<MenuScreen, MenuAction> = match a
|
examples/games/menu/screens/TurnScreen.plum
CHANGED
|
@@ -32,7 +32,7 @@ struct TurnScreen[ScreenSlice<TurnAction>](turner: Turner) =
|
|
|
32
32
|
|
|
33
33
|
fun subscriptions(self) -> List<Sub<TurnAction>> = [
|
|
34
34
|
OnKeyDown(key: Key.Escape, act: Back)
|
|
35
|
-
OnFrame(
|
|
35
|
+
OnFrame(Tick)
|
|
36
36
|
]
|
|
37
37
|
|
|
38
38
|
fun update(self, a: TurnAction) -> Next<TurnScreen, TurnAction> = match a
|
examples/games/orbitrunner/screens/PlayingScreen.plum
CHANGED
|
@@ -75,7 +75,7 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
|
|
|
75
75
|
]
|
|
76
76
|
|
|
77
77
|
fun subscriptions(self) -> List<Sub<PlayAction>> = [
|
|
78
|
-
OnFrame(
|
|
78
|
+
OnFrame(Tick)
|
|
79
79
|
if !self.over then OnHeld(|h| PlayingScreen.steering(h))
|
|
80
80
|
if self.over then OnKeyDown(key: Key.Enter, act: StartOver)
|
|
81
81
|
if self.over then OnKeyDown(key: Key.KeyR, act: StartOver)
|
std/game/ScreenSlice.plum
CHANGED
|
@@ -24,7 +24,7 @@ import std/game/Screen
|
|
|
24
24
|
#
|
|
25
25
|
# struct CountScreen[ScreenSlice<Act>](count: Int, ball: Ball) =
|
|
26
26
|
# fun subscriptions(self) -> List<Sub<Act>> = [
|
|
27
|
-
# OnFrame(
|
|
27
|
+
# OnFrame(Tick)
|
|
28
28
|
# OnKeyDown(key: Key.Space, act: Bump)
|
|
29
29
|
# ]
|
|
30
30
|
#
|
|
@@ -92,7 +92,8 @@ trait ScreenSlice<A>[Screen] =
|
|
|
92
92
|
|
|
93
93
|
# What a slice listens to (its `subscriptions`), each giving it an action of type `A`:
|
|
94
94
|
#
|
|
95
|
-
# OnFrame(act) `act(dt)` each tick, last: the frame
|
|
95
|
+
# OnFrame(act) `act(dt)` each tick, last: the frame (`OnFrame(Tick)` for an
|
|
96
|
+
# action `Tick(dt: Float)`: a constructor is a function)
|
|
96
97
|
# OnKeyDown(key, act) `act` when `key` goes down (a `Key`, std/game/Input)
|
|
97
98
|
# OnKeyUp(key, act) `act` when `key` goes up
|
|
98
99
|
# OnHeld(act) `act(h)` each tick, with what is held after the tick's events
|
tests/syntax/constructor_values.plum
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import std/Str
|
|
2
|
+
import std/Int
|
|
3
|
+
import std/Float
|
|
4
|
+
import std/Option
|
|
5
|
+
import std/collections/List
|
|
6
|
+
import std/Test
|
|
7
|
+
|
|
8
|
+
enum Act =
|
|
9
|
+
| Tick(dt: Float)
|
|
10
|
+
| Moved(dx: Int, dy: Int)
|
|
11
|
+
| Stop
|
|
12
|
+
|
|
13
|
+
enum Sub =
|
|
14
|
+
| OnFrame(act: fn(Float) -> Act)
|
|
15
|
+
| OnKey(act: Act)
|
|
16
|
+
|
|
17
|
+
struct Pt(x: Int, y: Int = 7) =
|
|
18
|
+
fun origin() -> Pt = Pt(x: 0, y: 0)
|
|
19
|
+
|
|
20
|
+
fun sum(self) -> Int = self.x + self.y
|
|
21
|
+
|
|
22
|
+
# A struct or a variant with fields, named without arguments, is the function that builds
|
|
23
|
+
# it from all its fields.
|
|
24
|
+
primitive ConstructorValues =
|
|
25
|
+
fun frame(subs: List<Sub>, dt: Float) -> Float = subs.fold(0.0, |acc, s| match s
|
|
26
|
+
OnFrame(act) => match act(dt)
|
|
27
|
+
Tick(d) => acc + d
|
|
28
|
+
_ => acc
|
|
29
|
+
OnKey(_) => acc)
|
|
30
|
+
|
|
31
|
+
fun moved(f: fn(Int, Int) -> Act) -> Int = match f(2, 3)
|
|
32
|
+
Moved(dx, dy) => dx * 10 + dy
|
|
33
|
+
_ => 0
|
|
34
|
+
|
|
35
|
+
primitive ConstructorValuesTest[UnitTest] =
|
|
36
|
+
fun aVariantAsTheActionOfASubscription() =
|
|
37
|
+
assert ConstructorValues.frame([OnFrame(Tick), OnKey(act: Stop), OnFrame(|dt| Tick(dt: dt * 2.0))], 0.5) == 1.5
|
|
38
|
+
|
|
39
|
+
fun aVariantOfTwoFields() =
|
|
40
|
+
assert ConstructorValues.moved(Moved) == 23
|
|
41
|
+
|
|
42
|
+
fun aGenericVariant() =
|
|
43
|
+
xs := [1, 2, 3].map(Some)
|
|
44
|
+
assert xs.fold(0, |acc, o| acc + o.unwrapOr(0)) == 6
|
|
45
|
+
|
|
46
|
+
fun aStructTakesEveryFieldDefaultedOrNot() =
|
|
47
|
+
mk := Pt
|
|
48
|
+
assert mk(3, 4).sum() == 7
|
|
49
|
+
|
|
50
|
+
fun aStaticOfTheTypeIsStillAStatic() =
|
|
51
|
+
assert Pt.origin().sum() == 0
|
tests/wasm_codegen/e2e_types/typed_closures.plum
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import std/Str
|
|
2
|
+
import std/Int
|
|
3
|
+
import std/Float
|
|
4
|
+
import std/Bool
|
|
5
|
+
import std/Option
|
|
6
|
+
import std/Slice
|
|
7
|
+
import std/collections/List
|
|
8
|
+
import std/Test
|
|
9
|
+
|
|
10
|
+
struct Pt(x: Float, y: Float)
|
|
11
|
+
|
|
12
|
+
struct Named(name: Str)
|
|
13
|
+
|
|
14
|
+
struct Rec(step: fn(Rec, Int) -> Int)
|
|
15
|
+
|
|
16
|
+
struct Holder<T>(f: fn(T) -> T)
|
|
17
|
+
|
|
18
|
+
enum Fns =
|
|
19
|
+
| More(f: fn(Int) -> Int, rest: Fns)
|
|
20
|
+
| Done
|
|
21
|
+
|
|
22
|
+
# Closures of each kind, as values the closure specialisation doesn't remove: stored in
|
|
23
|
+
# structs and enum payloads, returned, and called through them.
|
|
24
|
+
primitive TypedClosures =
|
|
25
|
+
fun captures() -> Str =
|
|
26
|
+
n := 3
|
|
27
|
+
k := 0.5
|
|
28
|
+
s := "ab"
|
|
29
|
+
on := true
|
|
30
|
+
p := Pt(x: 1.0, y: 2.0)
|
|
31
|
+
who := Named(name: "cd")
|
|
32
|
+
inner := |x| x * 10
|
|
33
|
+
f := |x| if on then "{inner(x + n)} {k * p.y + p.x} {s}{who.name}" else ""
|
|
34
|
+
TypedClosures.call(f, 1)
|
|
35
|
+
|
|
36
|
+
fun call(f: fn(Int) -> Str, x: Int) -> Str = f(x)
|
|
37
|
+
|
|
38
|
+
fun throughField(n: Int) -> Int =
|
|
39
|
+
r := Rec(step: |self, m| if m <= 0 then 0 else m + self.step(self, m - 1))
|
|
40
|
+
r.step(r, n)
|
|
41
|
+
|
|
42
|
+
fun selfNamed(n: Int) -> Int =
|
|
43
|
+
fact := |m| if m <= 1 then 1 else m * fact(m - 1)
|
|
44
|
+
fact(n)
|
|
45
|
+
|
|
46
|
+
fun twice<T>(h: Holder<T>, x: T) -> T = h.f(h.f(x))
|
|
47
|
+
|
|
48
|
+
fun generic() -> Str =
|
|
49
|
+
i := TypedClosures.twice(Holder(f: |x| x * 3), 2)
|
|
50
|
+
s := TypedClosures.twice(Holder(f: |x| "<{x}>"), "a")
|
|
51
|
+
"{i} {s}"
|
|
52
|
+
|
|
53
|
+
fun build(n: Int, acc: Fns) -> Fns = if n == 0 then acc else TypedClosures.build(n - 1, More(f: |x| x * 2 + n, rest: acc))
|
|
54
|
+
|
|
55
|
+
fun runAll(fs: Fns, x: Int) -> Int = match fs
|
|
56
|
+
Done => x
|
|
57
|
+
More(f, rest) => TypedClosures.runAll(rest, f(x))
|
|
58
|
+
|
|
59
|
+
fun returning() -> Int =
|
|
60
|
+
mk := |a| |b| a - b
|
|
61
|
+
g := mk(10)
|
|
62
|
+
h := mk(100)
|
|
63
|
+
g(3) + h(1)
|
|
64
|
+
|
|
65
|
+
fun adder(n: Int) -> fn(Int) -> Int = |x| x + n
|
|
66
|
+
|
|
67
|
+
fun inCollections(n: Int) -> Int =
|
|
68
|
+
fs := [|x| x + n, |x| x * 2, TypedClosures.adder(100)]
|
|
69
|
+
viaList := fs.fold(1, |acc, f| f(acc))
|
|
70
|
+
viaSlice := fs.toSlice().fold(1, |acc, f| f(acc))
|
|
71
|
+
viaOption := match fs.find(|f| f(0) == 100)
|
|
72
|
+
Some(f) => f(1)
|
|
73
|
+
None => 0
|
|
74
|
+
viaList + viaSlice + viaOption
|
|
75
|
+
|
|
76
|
+
fun pick(b: Bool) -> fn(Int) -> Int = if b then TypedClosures.adder(1) else |x| x * 3
|
|
77
|
+
|
|
78
|
+
primitive TypedClosuresTest[UnitTest] =
|
|
79
|
+
fun capturedValuesOfEachKind() =
|
|
80
|
+
assert TypedClosures.captures() == "40 2.0 abcd"
|
|
81
|
+
|
|
82
|
+
fun recursionThroughAField() =
|
|
83
|
+
assert TypedClosures.throughField(4) == 10
|
|
84
|
+
|
|
85
|
+
fun recursionByItsOwnName() =
|
|
86
|
+
assert TypedClosures.selfNamed(5) == 120
|
|
87
|
+
|
|
88
|
+
fun oneGenericClosureTypeAtTwoTypes() =
|
|
89
|
+
assert TypedClosures.generic() == "18 <<a>>"
|
|
90
|
+
|
|
91
|
+
fun closuresInAnEnumPayload() =
|
|
92
|
+
assert TypedClosures.runAll(TypedClosures.build(3, Done), 1) == 19
|
|
93
|
+
|
|
94
|
+
fun aClosureReturningAClosure() =
|
|
95
|
+
assert TypedClosures.returning() == 106
|
|
96
|
+
|
|
97
|
+
fun closuresAsTheElementsOfGenericCollections() =
|
|
98
|
+
assert TypedClosures.inCollections(2) == 106 + 106 + 101
|
|
99
|
+
|
|
100
|
+
fun aCapturingAndANonCapturingClosureOfOneType() =
|
|
101
|
+
up := TypedClosures.pick(true)
|
|
102
|
+
tri := TypedClosures.pick(false)
|
|
103
|
+
assert up(4) + tri(4) == 17
|