plum

#treesitter#compiler#wasm

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

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


5b6c68a — Peter John 2026-11-16T22:39:49+05:30
U4g: view lists painted with none made

Generated files not shown: Cargo.lock

compiler/core/src/lib.rs CHANGED
@@ -46,6 +46,7 @@ pub mod tests_lower;
46
46
  pub mod timing;
47
47
  pub mod trmc;
48
48
  pub mod uniqueness;
49
+ pub mod view_walk;
49
50
  pub mod visit;
50
51
  pub mod whistle;
51
52
 
compiler/core/src/view_walk.rs ADDED
@@ -0,0 +1,553 @@
1
+ //! A view's list streamed into the paint walk: no list is built to be walked once.
2
+ //!
3
+ //! A frame draws each item of a screen's `view()` list, and under each item its own `view()`,
4
+ //! with `Views.paintIn` (std/game/View): the list is built, walked once and dropped. Where the
5
+ //! walk's list is `self.view()` (a kind's `paintAt` and `paintCulledAt`, a screen's `paintView`
6
+ //! and `paintCulledView`, each `@final`, so each type has its own copy) and the type's `view`
7
+ //! writes its list as a literal, the call becomes one of a method made here from the literal,
8
+ //! `view$paint` (or `view$paintCulled`), that paints each item where the literal would have put
9
+ //! it in the list:
10
+ //!
11
+ //! ```text
12
+ //! fun view(self) -> List<View> = [Box(..), ..self.mines, if !self.over then self.ship, Label(..)]
13
+ //!
14
+ //! fun view$paint(self, io, m, alpha, mode) =
15
+ //! Box(..).paintAt(io, m, alpha, mode)
16
+ //! self.mines.each(|x| x.paintAt(io, m, alpha, mode))
17
+ //! if !self.over
18
+ //! self.ship.paintAt(io, m, alpha, mode)
19
+ //! Label(..).paintAt(io, m, alpha, mode)
20
+ //! ```
21
+ //!
22
+ //! so a value is painted with no list cell made for it, a spread of a `List<Mine>` is walked
23
+ //! as it is (no `List<View>` copy of it, `__upcastOnto`), and a spread of
24
+ //! `xs.map(|i| Star(..))` over a `List`, a `Range` or an `Option` paints each `Star` as `map`
25
+ //! would have made it (`xs.each(|i| Star(..).paintAt(..))`). An item painted is a value of its
26
+ //! own kind, so its `paintAt` is that kind's copy, called directly. What is not a literal (a
27
+ //! `Group`'s `self.children`, a call returning a list) is walked as it is, with `each`.
28
+ //!
29
+ //! Each item's value is made just before it is painted, not all of them before the first is:
30
+ //! the same draws in the same order (a `view` computes values; it draws nothing). `view()`
31
+ //! itself stays, for the hit tests, the draw list of std/game/TestRig, a game's own calls.
32
+ //!
33
+ //! The literal is read back from what `list_items` lowers it to (`Cons`, `spreadOnto`, the
34
+ //! checker's `__upcastOnto`/`__upcast` helpers, the `__li` temporaries of a conditional item,
35
+ //! `if`/`match` blocks around them). It runs at the start of closure specialisation
36
+ //! (`plum_driver`), which inlines the painting closures into copies of `each`, and is checked
37
+ //! again with it: a type whose walk fails the check keeps its list. A kind whose `view` is
38
+ //! empty (`Nil`, std's default) paints nothing under itself, so its walk statement is dropped.
39
+ //! The culling walk is made only when some type's `culls()` is not `false`.
40
+ use crate::ast::*;
41
+ use crate::closure_spec::Hints;
42
+ use std::collections::{HashMap, HashSet};
43
+
44
+ /// The method a painting walk calls on each item, and the made method's name.
45
+ #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
46
+ enum Walk {
47
+ Paint,
48
+ Culled,
49
+ }
50
+
51
+ impl Walk {
52
+ fn callee(self) -> &'static str {
53
+ match self {
54
+ Walk::Paint => "paintIn",
55
+ Walk::Culled => "paintCulledIn",
56
+ }
57
+ }
58
+ fn itemMethod(self) -> &'static str {
59
+ match self {
60
+ Walk::Paint => "paintAt",
61
+ Walk::Culled => "paintCulledAt",
62
+ }
63
+ }
64
+ pub fn made(self) -> &'static str {
65
+ match self {
66
+ Walk::Paint => "view$paint",
67
+ Walk::Culled => "view$paintCulled",
68
+ }
69
+ }
70
+ /// The made method's parameters after `self`, in the order the item's method takes them.
71
+ fn params(self) -> Vec<(&'static str, &'static str)> {
72
+ let mut ps = vec![(IO, "Io"), (M, "Affine"), (ALPHA, "Float")];
73
+ if self == Walk::Culled {
74
+ ps.push((AREA, "Aabb"));
75
+ }
76
+ ps.push((MODE, "Int"));
77
+ ps
78
+ }
79
+ }
80
+
81
+ const IO: &str = "__vw_io";
82
+ const M: &str = "__vw_m";
83
+ const ALPHA: &str = "__vw_alpha";
84
+ const AREA: &str = "__vw_area";
85
+ const MODE: &str = "__vw_mode";
86
+ /// The receivers whose `map(f)` spread is painted as `each` with `f`'s value painted.
87
+ const MAPPED: [&str; 3] = ["List", "Range", "Option"];
88
+
89
+ /// Rewrites every `Views.paintIn(io, self.view(), ..)` and `Views.paintCulledIn(..)` of a
90
+ /// type whose `view` is a list literal into a call of the walk made from it. Whether anything
91
+ /// changed. `made` gets the receiver types of the `each` calls made, where the walk knows them
92
+ /// (a spread's list, a mapped `Range`), for closure specialisation, which runs next on the
93
+ /// same program and inlines the painting closure into a copy of `each`.
94
+ pub fn walkViews(src: &mut Source, hints: &Hints, made: &mut Hints) -> bool {
95
+ let mut views: HashMap<String, Fn> = HashMap::new();
96
+ let mut empty: HashSet<String> = HashSet::new();
97
+ for i in &src.items {
98
+ let Item::Fn(f) = i else { continue };
99
+ let (Some(owner), Some(body)) = (&f.type_param, bodyExpr(f)) else { continue };
100
+ if f.name != "view" || !f.has_self || !f.params.is_empty() {
101
+ continue;
102
+ }
103
+ if matches!(&body.kind, ExprKind::TypeName(n) if n == "Nil") {
104
+ empty.insert(owner.clone());
105
+ } else if literal(&body) {
106
+ views.insert(owner.clone(), f.clone());
107
+ }
108
+ }
109
+ if views.is_empty() && empty.is_empty() {
110
+ return false;
111
+ }
112
+ let mut changed = false;
113
+ // A kind whose view is empty (a `Box`, a `Sprite`) paints nothing under itself: its walk
114
+ // of `self.view()`, a statement, goes.
115
+ for item in &mut src.items {
116
+ let Item::Fn(f) = item else { continue };
117
+ if f.type_param.as_ref().is_some_and(|o| empty.contains(o)) {
118
+ if let FnBody::Block(b) = &mut f.body {
119
+ changed |= dropEmptyWalks(b);
120
+ }
121
+ }
122
+ }
123
+ // The culling walk only where something can cull: a screen whose `culls()` is not `false`
124
+ // (std's default), or a program calling `paintCulled` itself (its kinds keep the list).
125
+ let culls = src.items.iter().any(|i| match i {
126
+ Item::Fn(f) if f.name == "culls" && f.type_param.is_some() => {
127
+ !matches!(bodyExpr(f).map(|e| e.kind), Some(ExprKind::BoolLit(false)))
128
+ }
129
+ _ => false,
130
+ });
131
+ let mut wanted: HashSet<(String, Walk)> = HashSet::new();
132
+ for item in &mut src.items {
133
+ let Item::Fn(f) = item else { continue };
134
+ let Some(owner) = f.type_param.clone() else { continue };
135
+ if !views.contains_key(&owner) || f.name == Walk::Paint.made() || f.name == Walk::Culled.made() {
136
+ continue;
137
+ }
138
+ let mut cb = |e: &mut Expr| {
139
+ if let Some((walk, args)) = paintOfSelfView(e).filter(|(w, _)| culls || *w == Walk::Paint) {
140
+ wanted.insert((owner.clone(), walk));
141
+ let call = FnCall {
142
+ name: walk.made().to_string(),
143
+ args: args.into_iter().map(Arg::Positional).collect(),
144
+ line: 0,
145
+ column: 0,
146
+ tail: TailKind::NotTail,
147
+ recv: None,
148
+ type_args: Vec::new(),
149
+ };
150
+ *e = Expr::Attribute(Box::new(AttributeExpr { object: Expr::new(ExprKind::Self_), attr: AttrKind::Method(call) }));
151
+ }
152
+ };
153
+ match &mut f.body {
154
+ FnBody::Expr(e) => crate::visit::visitExpr(e, &mut cb),
155
+ FnBody::Block(b) => crate::visit::visitBlock(b, &mut cb),
156
+ FnBody::Extern => {}
157
+ }
158
+ }
159
+ if wanted.is_empty() {
160
+ return changed;
161
+ }
162
+ let mut wanted: Vec<(String, Walk)> = wanted.into_iter().collect();
163
+ wanted.sort_by(|a, b| (&a.0, a.1 as u8).cmp(&(&b.0, b.1 as u8)));
164
+ let mut fresh = 0;
165
+ for (owner, walk) in wanted {
166
+ let view = &views[&owner];
167
+ let mut w = Walker { walk, hints, made: &mut *made, file: view.file.clone(), line: view.line, fresh: &mut fresh };
168
+ let mut stmts = Vec::new();
169
+ w.list(&bodyExpr(view).unwrap(), &HashSet::new(), &mut stmts);
170
+ let params = walk
171
+ .params()
172
+ .into_iter()
173
+ .map(|(n, t)| Param { name: n.to_string(), ty: ParamType::Type(Type { name: t.to_string(), generics: vec![] }), default: None })
174
+ .collect();
175
+ let mut made = Fn {
176
+ name: walk.made().to_string(),
177
+ file: view.file.clone(),
178
+ line: view.line,
179
+ column: view.column,
180
+ type_param: Some(owner),
181
+ generics: view.generics.clone(),
182
+ bounds: view.bounds.clone(),
183
+ is_extern: false,
184
+ is_export: false,
185
+ is_test: false,
186
+ is_fip: false,
187
+ has_self: true,
188
+ params,
189
+ returns: None,
190
+ body: FnBody::Block(Block { stmts }),
191
+ };
192
+ // the view's code, copied: its nodes get ids of their own
193
+ refreshFnIds(&mut made);
194
+ src.items.push(Item::Fn(made));
195
+ }
196
+ true
197
+ }
198
+
199
+ /// Drops each `Views.paintIn(io, self.view(), ..)` statement of `b` and the blocks in it that
200
+ /// is not a block's value. Whether one went.
201
+ fn dropEmptyWalks(b: &mut Block) -> bool {
202
+ let n = b.stmts.len();
203
+ let mut i = 0;
204
+ let before = b.stmts.len();
205
+ b.stmts.retain(|s| {
206
+ i += 1;
207
+ !(i < n && matches!(&s.kind, StmtKind::Expr(e, ..) if paintOfSelfView(e).is_some()))
208
+ });
209
+ let mut changed = b.stmts.len() != before;
210
+ for s in &mut b.stmts {
211
+ for inner in crate::visit::stmtBlocks(s) {
212
+ changed |= dropEmptyWalks(inner);
213
+ }
214
+ for e in crate::visit::stmtExprs(s) {
215
+ crate::visit::innerBlocks(e, &mut |inner| changed |= dropEmptyWalks(inner));
216
+ }
217
+ }
218
+ changed
219
+ }
220
+
221
+ /// A fn's body as one expression (a block body is a block value).
222
+ fn bodyExpr(f: &Fn) -> Option<Expr> {
223
+ match &f.body {
224
+ FnBody::Expr(e) => Some(e.clone()),
225
+ FnBody::Block(b) => Some(Expr::Block(Box::new(b.clone()))),
226
+ FnBody::Extern => None,
227
+ }
228
+ }
229
+
230
+ /// Whether `e` builds a list the walk can take apart: a `Cons`, a spread, a block or an `if`
231
+ /// around one. A list that is only read (`self.children`) or `Nil` is walked as it is.
232
+ fn literal(e: &Expr) -> bool {
233
+ match &e.kind {
234
+ ExprKind::ClassCall(c) => c.type_name == "Cons",
235
+ ExprKind::Attribute(a) => matches!(&a.attr, AttrKind::Method(c) if c.name == crate::list_items::SPREAD_ONTO),
236
+ ExprKind::FnCall(c) => c.name.starts_with("__upcastOnto"),
237
+ ExprKind::InlineIf(i) => literal(&i.then) || literal(&i.else_),
238
+ ExprKind::Block(b) => match b.stmts.last().map(|s| &s.kind) {
239
+ Some(StmtKind::Expr(t, ..)) => literal(t),
240
+ Some(StmtKind::If(_) | StmtKind::Match(_)) => true,
241
+ _ => false,
242
+ },
243
+ _ => false,
244
+ }
245
+ }
246
+
247
+ /// `Views.paintIn(io, self.view(), m, alpha, mode)` (or `paintCulledIn(.., area, mode)`): the
248
+ /// walk and its arguments without the list.
249
+ fn paintOfSelfView(e: &Expr) -> Option<(Walk, Vec<Expr>)> {
250
+ let ExprKind::Attribute(a) = &e.kind else { return None };
251
+ if !matches!(&a.object.kind, ExprKind::TypeName(n) if n == "Views") {
252
+ return None;
253
+ }
254
+ let AttrKind::Method(c) = &a.attr else { return None };
255
+ let walk = [Walk::Paint, Walk::Culled].into_iter().find(|w| w.callee() == c.name)?;
256
+ if c.args.len() != walk.params().len() + 1 {
257
+ return None;
258
+ }
259
+ let args: Vec<&Expr> = c
260
+ .args
261
+ .iter()
262
+ .map(|a| match a {
263
+ Arg::Positional(e) => Some(e),
264
+ Arg::Keyword { .. } => None,
265
+ })
266
+ .collect::<Option<_>>()?;
267
+ let ExprKind::Attribute(v) = &args[1].kind else { return None };
268
+ let isSelfView = matches!(&v.object.kind, ExprKind::Self_)
269
+ && matches!(&v.attr, AttrKind::Method(m) if m.name == "view" && m.args.is_empty());
270
+ if !isSelfView {
271
+ return None;
272
+ }
273
+ let mut rest: Vec<Expr> = vec![args[0].clone()];
274
+ rest.extend(args[2..].iter().map(|e| (*e).clone()));
275
+ Some((walk, rest))
276
+ }
277
+
278
+ struct Walker<'a> {
279
+ walk: Walk,
280
+ hints: &'a Hints,
281
+ made: &'a mut Hints,
282
+ /// The `view`'s file: the key of its calls' receiver hints.
283
+ file: String,
284
+ /// The `view`'s line: the line of the calls made.
285
+ line: usize,
286
+ /// Calls made so far in the file (see `MADE_COLUMN`), and closure parameters.
287
+ fresh: &'a mut usize,
288
+ }
289
+
290
+ fn var(n: &str) -> Expr {
291
+ Expr::Var(n.to_string())
292
+ }
293
+
294
+ /// The first column of the calls made here: past any column written, so each call made has a
295
+ /// position of its own (`at`), and the checker's receiver type of it reaches the passes after
296
+ /// this one (`closure_spec::Hints` are keyed by position), which inline the closure handed to
297
+ /// an `each` and call the item's own `paintAt`.
298
+ const MADE_COLUMN: usize = 1_000_000;
299
+
300
+ fn method(object: Expr, name: &str, args: Vec<Expr>, at: (usize, usize)) -> Expr {
301
+ Expr::Attribute(Box::new(AttributeExpr {
302
+ object,
303
+ attr: AttrKind::Method(FnCall {
304
+ name: name.to_string(),
305
+ args: args.into_iter().map(Arg::Positional).collect(),
306
+ line: at.0,
307
+ column: at.1,
308
+ tail: TailKind::NotTail,
309
+ recv: None,
310
+ type_args: Vec::new(),
311
+ }),
312
+ }))
313
+ }
314
+
315
+ fn stmt(e: Expr) -> Stmt {
316
+ Stmt::Expr(e, 0, 0)
317
+ }
318
+
319
+ fn ifStmt(condition: Expr, body: Vec<Stmt>, else_: Vec<Stmt>) -> Stmt {
320
+ Stmt::If(If {
321
+ condition,
322
+ body: Block { stmts: body },
323
+ else_ifs: Vec::new(),
324
+ else_: if else_.is_empty() { None } else { Some(Block { stmts: else_ }) },
325
+ })
326
+ }
327
+
328
+ fn positional(c: &FnCall) -> Option<Vec<&Expr>> {
329
+ c.args
330
+ .iter()
331
+ .map(|a| match a {
332
+ Arg::Positional(e) => Some(e),
333
+ Arg::Keyword { .. } => None,
334
+ })
335
+ .collect()
336
+ }
337
+
338
+ fn field<'e>(c: &'e ClassCall, name: &str) -> Option<&'e Expr> {
339
+ c.fields.iter().find(|f| f.name == name).map(|f| &f.value)
340
+ }
341
+
342
+ impl Walker<'_> {
343
+ /// A position of its own for a call made.
344
+ fn at(&mut self) -> (usize, usize) {
345
+ *self.fresh += 1;
346
+ (self.line, MADE_COLUMN + *self.fresh)
347
+ }
348
+
349
+ /// The statement painting the value `x`, one item.
350
+ fn item(&mut self, x: Expr) -> Stmt {
351
+ let args = self.walk.params().into_iter().map(|(n, _)| var(n)).collect();
352
+ let at = self.at();
353
+ stmt(method(x, self.walk.itemMethod(), args, at))
354
+ }
355
+
356
+ /// `xs.each(|x| <paint x>)`: every element of `xs` (a `List`, an `Option`) painted. `recv`:
357
+ /// the type of `xs`, when known.
358
+ fn each(&mut self, xs: Expr, recv: Option<String>) -> Stmt {
359
+ let (_, n) = self.at();
360
+ let x = format!("__vw_x{}", n - MADE_COLUMN);
361
+ let body = Block { stmts: vec![self.item(var(&x))] };
362
+ let f = Expr::Closure(Box::new(Closure { params: vec![x], param_types: vec![None], body }));
363
+ let at = self.at();
364
+ self.know(at, recv);
365
+ stmt(method(xs, "each", vec![f], at))
366
+ }
367
+
368
+ /// Records the receiver type of the `each` made at `at`.
369
+ fn know(&mut self, at: (usize, usize), recv: Option<String>) {
370
+ if let Some(t) = recv {
371
+ self.made.insert((self.file.clone(), at.0, at.1, "each".to_string()), t);
372
+ }
373
+ }
374
+
375
+ /// `each` over a list (what is in a list's place in the literal).
376
+ fn eachOfList(&mut self, xs: Expr) -> Stmt {
377
+ self.each(xs, Some("List".to_string()))
378
+ }
379
+
380
+ /// Paints the list `e` would build, in order, onto `out`. A `Var` in `stopped` is the rest
381
+ /// of the list, painted after the expression that names it: nothing here.
382
+ fn list(&mut self, e: &Expr, stopped: &HashSet<String>, out: &mut Vec<Stmt>) {
383
+ match &e.kind {
384
+ ExprKind::TypeName(n) if n == "Nil" => {}
385
+ ExprKind::Var(v) if stopped.contains(v) => {}
386
+ ExprKind::ClassCall(c) if c.type_name == "Cons" && c.spread.is_none() => match (field(c, "head"), field(c, "tail")) {
387
+ (Some(h), Some(t)) => {
388
+ out.push(self.item(h.clone()));
389
+ self.list(t, stopped, out);
390
+ }
391
+ _ => out.push(self.eachOfList(e.clone())),
392
+ },
393
+ ExprKind::Attribute(a) => match &a.attr {
394
+ AttrKind::Method(c) if c.name == crate::list_items::SPREAD_ONTO && c.args.len() == 1 => {
395
+ let Some(args) = positional(c) else { return out.push(self.eachOfList(e.clone())) };
396
+ let known = self.hints.get(&(self.file.clone(), c.line, c.column, c.name.clone())).cloned();
397
+ self.spread(&a.object, known, out);
398
+ self.list(args[0], stopped, out);
399
+ }
400
+ _ => out.push(self.eachOfList(e.clone())),
401
+ },
402
+ ExprKind::FnCall(c) if c.name.starts_with("__upcastOnto") && c.args.len() == 2 => {
403
+ let Some(args) = positional(c) else { return out.push(self.eachOfList(e.clone())) };
404
+ self.spread(args[0], Some("List".to_string()), out);
405
+ self.list(args[1], stopped, out);
406
+ }
407
+ ExprKind::FnCall(c) if c.name.starts_with("__upcast") && c.args.len() == 1 => {
408
+ let Some(args) = positional(c) else { return out.push(self.eachOfList(e.clone())) };
409
+ self.list(args[0], stopped, out);
410
+ }
411
+ ExprKind::InlineIf(i) => {
412
+ let mut then = Vec::new();
413
+ self.list(&i.then, stopped, &mut then);
414
+ let mut else_ = Vec::new();
415
+ self.list(&i.else_, stopped, &mut else_);
416
+ if then.is_empty() && else_.is_empty() {
417
+ // the condition still runs, for its traps
418
+ out.push(stmt(i.condition.clone()));
419
+ } else if then.is_empty() {
420
+ out.push(ifStmt(Expr::Not(Box::new(i.condition.clone())), else_, Vec::new()));
421
+ } else {
422
+ out.push(ifStmt(i.condition.clone(), then, else_));
423
+ }
424
+ }
425
+ ExprKind::Block(b) => self.block(b, stopped, out),
426
+ _ => out.push(self.eachOfList(e.clone())),
427
+ }
428
+ }
429
+
430
+ /// A block value building a list: its statements as they are, then its value painted.
431
+ /// The lowering of a conditional item, `{ __li := rest; if c then x :: __li else __li }`,
432
+ /// paints `x` when `c` holds and then `rest`, with no `rest` built.
433
+ fn block(&mut self, b: &Block, stopped: &HashSet<String>, out: &mut Vec<Stmt>) {
434
+ let Some((last, init)) = b.stmts.split_last() else { return };
435
+ let mut stmts: Vec<Stmt> = init.to_vec();
436
+ let mut deferred: Option<(String, Expr)> = None;
437
+ if let StmtKind::Expr(tail, ..) = &last.kind {
438
+ if let ExprKind::InlineIf(i) = &tail.kind {
439
+ if let ExprKind::Var(t) = &i.else_.kind {
440
+ if let Some(StmtKind::Assign(a)) = stmts.last().map(|s| &s.kind) {
441
+ if a.declare && a.values.len() == 1 && matches!(a.targets.as_slice(), [AssignTarget::Var(n)] if n == t) {
442
+ deferred = Some((t.clone(), a.values[0].clone()));
443
+ stmts.pop();
444
+ }
445
+ }
446
+ }
447
+ }
448
+ }
449
+ out.extend(stmts);
450
+ match (&last.kind, deferred) {
451
+ (StmtKind::Expr(tail, ..), Some((t, rest))) => {
452
+ let ExprKind::InlineIf(i) = &tail.kind else { unreachable!() };
453
+ let mut inner = stopped.clone();
454
+ inner.insert(t);
455
+ let mut then = Vec::new();
456
+ self.list(&i.then, &inner, &mut then);
457
+ if !then.is_empty() {
458
+ out.push(ifStmt(i.condition.clone(), then, Vec::new()));
459
+ } else {
460
+ out.push(stmt(i.condition.clone()));
461
+ }
462
+ self.list(&rest, stopped, out);
463
+ }
464
+ (StmtKind::Expr(tail, ..), None) => self.list(tail, stopped, out),
465
+ (StmtKind::If(i), None) => {
466
+ let mut s = i.clone();
467
+ self.tailOf(&mut s.body, stopped);
468
+ for ei in &mut s.else_ifs {
469
+ self.tailOf(&mut ei.body, stopped);
470
+ }
471
+ if let Some(e) = &mut s.else_ {
472
+ self.tailOf(e, stopped);
473
+ }
474
+ out.push(Stmt::If(s));
475
+ }
476
+ (StmtKind::Match(m), None) => {
477
+ let mut s = m.clone();
478
+ for c in &mut s.cases {
479
+ self.tailOf(&mut c.body, stopped);
480
+ }
481
+ out.push(Stmt::Match(s));
482
+ }
483
+ _ => out.push(self.eachOfList(Expr::Block(Box::new(b.clone())))),
484
+ }
485
+ }
486
+
487
+ /// An arm of a block `if` or `match` whose value is a list: painted in place.
488
+ fn tailOf(&mut self, arm: &mut Block, stopped: &HashSet<String>) {
489
+ let b = std::mem::replace(arm, Block { stmts: Vec::new() });
490
+ let mut out = Vec::new();
491
+ self.block(&b, stopped, &mut out);
492
+ arm.stmts = out;
493
+ }
494
+
495
+ /// Paints what the spread of `x` puts in the list: the elements of a `List`, the value of
496
+ /// a `Some`.
497
+ /// `known`: the type of `x`, when known (`List` for an `__upcastOnto`'s, the checker's for a
498
+ /// `spreadOnto`'s receiver).
499
+ fn spread(&mut self, x: &Expr, known: Option<String>, out: &mut Vec<Stmt>) {
500
+ match &x.kind {
501
+ ExprKind::FnCall(c) if c.name.starts_with("__upcast") && !c.name.starts_with("__upcastOnto") && c.args.len() == 1 => {
502
+ match positional(c) {
503
+ Some(args) => self.spread(args[0], known.clone(), out),
504
+ None => out.push(self.each(x.clone(), known.clone())),
505
+ }
506
+ }
507
+ ExprKind::TypeName(n) if n == "None" || n == "Nil" => {}
508
+ ExprKind::ClassCall(c) if c.type_name == "Some" && c.spread.is_none() && c.fields.len() == 1 => {
509
+ out.push(self.item(c.fields[0].value.clone()));
510
+ }
511
+ ExprKind::InlineIf(i) => {
512
+ let mut then = Vec::new();
513
+ self.spread(&i.then, known.clone(), &mut then);
514
+ let mut else_ = Vec::new();
515
+ self.spread(&i.else_, known.clone(), &mut else_);
516
+ if then.is_empty() && else_.is_empty() {
517
+ out.push(stmt(i.condition.clone()));
518
+ } else if then.is_empty() {
519
+ out.push(ifStmt(Expr::Not(Box::new(i.condition.clone())), else_, Vec::new()));
520
+ } else {
521
+ out.push(ifStmt(i.condition.clone(), then, else_));
522
+ }
523
+ }
524
+ ExprKind::Attribute(a) => match &a.attr {
525
+ AttrKind::Method(c) if c.name == "map" && c.args.len() == 1 && self.mapped(c) => {
526
+ let Some(args) = positional(c) else { return out.push(self.each(x.clone(), known.clone())) };
527
+ let ExprKind::Closure(f) = &args[0].kind else { return out.push(self.each(x.clone(), known.clone())) };
528
+ let Some((last, init)) = f.body.stmts.split_last() else { return out.push(self.each(x.clone(), known.clone())) };
529
+ let StmtKind::Expr(value, ..) = &last.kind else { return out.push(self.each(x.clone(), known.clone())) };
530
+ let mut stmts = init.to_vec();
531
+ stmts.push(self.item(value.clone()));
532
+ let g = Closure { params: f.params.clone(), param_types: f.param_types.clone(), body: Block { stmts } };
533
+ let at = self.at();
534
+ let recv = self.hints.get(&(self.file.clone(), c.line, c.column, "map".to_string())).cloned();
535
+ self.know(at, recv);
536
+ out.push(stmt(method(a.object.clone(), "each", vec![Expr::Closure(Box::new(g))], at)));
537
+ }
538
+ _ => out.push(self.each(x.clone(), known.clone())),
539
+ },
540
+ _ => out.push(self.each(x.clone(), known.clone())),
541
+ }
542
+ }
543
+
544
+ /// Whether the `map` call `c` (as the `view` wrote it) is std's, on a `List`, a `Range` or
545
+ /// an `Option`, as the checker saw its receiver.
546
+ fn mapped(&self, c: &FnCall) -> bool {
547
+ c.line != 0
548
+ && self
549
+ .hints
550
+ .get(&(self.file.clone(), c.line, c.column, "map".to_string()))
551
+ .is_some_and(|t| MAPPED.contains(&t.as_str()))
552
+ }
553
+ }
compiler/driver/src/lib.rs CHANGED
@@ -43,6 +43,9 @@ pub enum Target {
43
43
  /// What a rewrite may read besides the program.
44
44
  pub struct Env<'a> {
45
45
  pub explain: bool,
46
+ /// Whether fusion runs (`PassOptions.fusion`): closure specialisation then also streams a
47
+ /// view's list into its paint walk (`plum_core::view_walk`).
48
+ pub fusion: bool,
46
49
  /// Whether in-place updates may be marked (`PassOptions.fbip`).
47
50
  pub fbip: bool,
48
51
  /// Receiver types of method calls, read off the checked program (see `closureHints`).
@@ -69,7 +72,12 @@ pub struct Pass {
69
72
  }
70
73
 
71
74
  fn closureSpec(copy: &mut Source, env: &Env) -> bool {
75
+ // First the view walks (`plum_core::view_walk`), whose painting closures are inlined here
76
+ // with the rest: one re-check for both.
77
+ let mut hints = env.hints.clone();
78
+ let walked = env.fusion && plum_core::view_walk::walkViews(copy, env.hints, &mut hints);
72
- !plum_core::closure_spec::specialiseWith(copy, env.hints).is_empty()
79
+ let specialised = !plum_core::closure_spec::specialiseWith(copy, &hints).is_empty();
80
+ walked || specialised
73
81
  }
74
82
 
75
83
  /// Purity -> simplify -> drive: the `fusion` pass; returns its notes.
@@ -265,7 +273,7 @@ fn runPass(pass: &Pass, original: &Source, opts: &PassOptions, st: &mut State) {
265
273
  Hints::new()
266
274
  });
267
275
  let errors = RefCell::new(Vec::new());
268
- let env = Env { explain: opts.explain, fbip: opts.fbip, hints: &hints, errors: &errors, origins: &st.origins };
276
+ let env = Env { explain: opts.explain, fusion: opts.fusion, fbip: opts.fbip, hints: &hints, errors: &errors, origins: &st.origins };
269
277
  let mut copy = match pass.target {
270
278
  Target::Pre => (*st.pre).clone(),
271
279
  Target::Lowered => match st.info.lowered.as_ref() {
compiler/game/Cargo.toml CHANGED
@@ -13,3 +13,4 @@ image = { version = "0.24", default-features = false, features = ["png", "jpeg",
13
13
  [dev-dependencies]
14
14
  plum-core = { path = "../core" }
15
15
  plum-wasm-codegen = { path = "../wasm-codegen" }
16
+ plum-driver = { path = "../driver" }
compiler/game/tests/fixtures/view_walk_fixture.plum ADDED
@@ -0,0 +1,106 @@
1
+ module view_walk_fixture
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Str
6
+ import std/Bool
7
+ import std/Slice
8
+ import std/Option
9
+ import std/collections/List
10
+ import std/math/Vec2
11
+ import std/math/Affine
12
+ import std/math/Aabb
13
+ import std/Io
14
+ import std/game/Color
15
+ import std/game/Gfx
16
+ import std/game/Input
17
+ import std/game/Place
18
+ import std/game/View
19
+ import std/game/Sized
20
+ import std/game/Touch
21
+ import std/game/Box
22
+ import std/game/Circle
23
+ import std/game/Label
24
+ import std/game/Line
25
+ import std/game/Sprite
26
+ import std/game/Group
27
+ import std/game/Blend
28
+ import std/game/Overlay
29
+ import std/game/Screen
30
+ import std/game/ScreenSlice
31
+ import std/game/Game
32
+ import std/App
33
+
34
+ # A screen whose view is a list literal of every kind of item, drawn by std's frame:
35
+ # compiled with fusion its list is painted as it would be built (plum_core::view_walk),
36
+ # without it the list is built and walked; host_test compares the two draws. Every
37
+ # second tick it toggles `shown` and every third `culls`; actors move off the screen
38
+ # (culled when it culls) and back.
39
+ enum Act = Tick(dt: Float)
40
+
41
+ struct Dot[Actor](x: Float, y: Float, clock: Float, tex: Texture) =
42
+ fun place(self) -> Place = Place.at(self.x, self.y)
43
+
44
+ fun step(self, dt: Float) -> Dot = Dot(..self, x: self.x + 700.0 * dt, clock: self.clock + dt)
45
+
46
+ fun view(self) -> List<View> = [Sprite(tex: self.tex, w: 8.0, h: 8.0, srcX: 0.0, srcY: 0.0, srcW: 8.0, srcH: 8.0, frame: Sprite.frameAt(self.clock, 10.0, 2))]
47
+
48
+ struct Badge[View, Sized](x: Float, y: Float, n: Int, lit: Bool, ring: Option<Circle>) =
49
+ fun place(self) -> Place = Place.at(self.x, self.y).fade(0.5)
50
+
51
+ fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, 20.0, 20.0)
52
+
53
+ fun view(self) -> List<View> =
54
+ w := 20.0
55
+ [
56
+ Box(w: w, h: w, color: Color.Red)
57
+ if self.lit then Circle(x: 10.0, y: 10.0, r: 4.0, color: Color.Yellow)
58
+ ..self.ring
59
+ ..Range.until(0, self.n).map(|i| Label(x: Float(i) * 5.0, text: "{i}", size: 8.0))
60
+ ]
61
+
62
+ struct Walks[ScreenSlice<Act>](
63
+ dots: List<Dot>, badges: List<Badge>, none: List<View>,
64
+ shown: Bool, cull: Bool, ticks: Int
65
+ ) =
66
+ fun size(self) -> Vec2 = Vec2(x: 800.0, y: 600.0)
67
+
68
+ fun culls(self) -> Bool = self.cull
69
+
70
+ fun subscriptions(self) -> List<Sub<Act>> = [OnFrame(Tick)]
71
+
72
+ fun update(self, a: Act) -> Next<Walks, Act> = match a
73
+ Tick(dt) =>
74
+ t := self.ticks + 1
75
+ Next(state: Walks(..self.stepped(dt), ticks: t, shown: t % 2 == 0, cull: t % 3 != 0))
76
+
77
+ fun view(self) -> List<View> = [
78
+ Box(w: 800.0, h: 600.0, color: Color.Black)
79
+ ..self.dots
80
+ ..self.none
81
+ if self.shown then ..self.badges
82
+ if !self.shown then Label(x: 400.0, text: "hidden")
83
+ Group(x: 10.0, y: 10.0) {
84
+ Box(w: 5.0, h: 5.0, color: Color.Green)
85
+ Blend(mode: Blend.Add) {
86
+ Circle(r: 3.0, color: Color.White)
87
+ Line(from: Vec2(x: 0.0, y: 0.0), to: Vec2(x: 9.0, y: 9.0))
88
+ }
89
+ }
90
+ Overlay(x: 700.0, y: 500.0, w: 300.0, h: 50.0) {
91
+ Label(x: 5.0, y: 5.0, text: "ticks {self.ticks}")
92
+ Group(x: 1000.0) { Box(w: 5.0, h: 5.0, color: Color.Blue) }
93
+ }
94
+ ]
95
+
96
+ primitive ViewWalkFixture[App] =
97
+ fun main(io: Io) -> Game =
98
+ tex := Texture.load(io, "sprites.png")
99
+ dots := Range.until(0, 6).map(|i| Dot(x: Float(i) * 150.0, y: 300.0, clock: 0.0, tex: tex))
100
+ badges := [
101
+ Badge(x: 100.0, y: 100.0, n: 3, lit: true, ring: Some(Circle(r: 12.0, color: Color.Blue)))
102
+ Badge(x: 900.0, y: 100.0, n: 0, lit: false, ring: None)
103
+ Badge(x: 300.0, y: -100.0, n: 1, lit: true, ring: None)
104
+ ]
105
+ s: Screen := Walks(dots: dots, badges: badges, none: Nil, shown: true, cull: true, ticks: 0)
106
+ Game(screens: [s])
compiler/game/tests/host_test.rs CHANGED
@@ -969,3 +969,34 @@ fn aSilentSoundsCommandsCallNoHost() {
969
969
  let sounds: Vec<&String> = g.backend().calls.iter().filter(|c| c.starts_with("sound")).collect();
970
970
  assert_eq!(sounds, ["soundPlay(3,0.5)", "soundStop(3)"]);
971
971
  }
972
+
973
+ /// The draw calls of `frames` frames of view_walk_fixture.plum (a tick, then a frame), compiled
974
+ /// with `passes`, and whether its screen's view was painted with no list made
975
+ /// (`plum_core::view_walk`: a `view$paint` method in the module's names).
976
+ fn viewWalkFrames(passes: plum_driver::PassOptions, frames: usize) -> (Vec<String>, bool) {
977
+ let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/view_walk_fixture.plum");
978
+ let source = plum_core::loadAndMergeDiag(&path, &root()).expect("load");
979
+ let opts = plum_wasm_codegen::CompileOptions { passes, ..plum_wasm_codegen::CompileOptions::default() };
980
+ let wasm = plum_wasm_codegen::compile(&source, &opts).expect("compile").wasm;
981
+ let walked = wasm.windows(b"Walks.view$paint".len()).any(|w| w == b"Walks.view$paint");
982
+ let mut g = PlumGame::load(&wasm, Recorder::with_assets(examples_assets())).expect("load game");
983
+ g.init().expect("init");
984
+ for _ in 0..frames {
985
+ g.update(1.0 / 60.0).expect("update");
986
+ g.draw().expect("draw");
987
+ }
988
+ (g.backend().calls.clone(), walked)
989
+ }
990
+
991
+ #[test]
992
+ fn aViewPaintedWithNoListDrawsWhatItsListDraws() {
993
+ let (fused, walked) = viewWalkFrames(plum_driver::PassOptions::default(), 12);
994
+ let off = plum_driver::PassOptions { fusion: false, ..plum_driver::PassOptions::default() };
995
+ let (built, notWalked) = viewWalkFrames(off, 12);
996
+ assert!(walked && !notWalked, "the fused build walks the view, the other builds it");
997
+ assert_eq!(fused, built);
998
+ // spreads, conditional items, a mapped range, children in a blend, culling all drew
999
+ for want in ["drawTextureEx(0,", "drawText(\"hidden\"", "drawText(\"2\"", "drawCircle(", "drawLine(", "blendMode(1)", "drawText(\"ticks "] {
1000
+ assert!(fused.iter().any(|c| c.starts_with(want)), "{want}: {fused:?}");
1001
+ }
1002
+ }
docs/backlog.md CHANGED
@@ -9,7 +9,7 @@ The retained scene tree was replaced by master's screen view in functional form:
9
9
  - **Pass re-check failures met on the way** (fixed in std, not in the compiler): fusion devirtualising `s.frames().onDemand()` on a `Screen` with one implementer mistypes the fused call (std matches on `frames()` instead); dead-code removal is reverted when it removes every type a downcast to a trait could match (it met `Container as c`, which master has since folded into `view` too).
10
10
  - **What std's delivery fold still copies** (the screen is in place since 2026-11-16, `@copy` in `Delivery.deliverTo`; since the Elm-style screens, Orbit Runner's `PlayingScreen.update` 5 (steer, the frame's spread after `stepped`, scored, hit and start over, whose `best` is read before the spread now), `rules`, `deal`, `grown`, `at` and the derived `stepped`: 29 spreads in place, 27 before; a call on a receiver of a bounded type parameter, `s.update(a)` with `S: ScreenSlice<A>`, is stamped with the bound in the analysis' copy of the body and resolves among its implementers, where it resolved to every `update` of the program, `Game.update` and `Viewport.update` among them): an update that reads `self` again after a spread of it copies (Orbit Runner reads its sounds first, `sounds := self.assets`); a screen fold whose result `passes` can't follow (`Range.fold` over the screen; Orbit Runner's `deal` folds a `Rolled<List<Orb>>` instead); Balloon Pop's `update`, one spread in place, the others copies, as its `view` keeps `self` (`s.view()` in `eventInto` then shares the copy) and its frame action spreads inside a fold's closure; an orb's and a mine's `step` (R3: one spread of `self`, the head of the list it is stepped in, `List.head`, which std's read-only walks `List.all`, `filter` and `next` hand to closures and results, and `Ticker.input` binds out of a field read; the screen's `mines` and `orbs` are also handed to the view's upcasts). The proof the fold needed: read-only parameters through calls (`readOnlyParams`: a screen's `view` hands `self` to the fused copies of its closures), a field taken out of a fresh value (rechecked by `analyse` when the field turns out shared), a value stored beside reads of itself (`Next(state: self, then: [if self.over ..])`), a local used once standing for its value in `passes`. Since U1 (2026-11-16) a parameter read only inside a closure handed to a fn that never lets the closure escape is only read (`readOnlyParams` through `An.keepsNoFn`), whether or not closure specialisation made a copy of the callee for that closure. It made at most 8 per callee, program-wide, in the order it met them, so a `filter` or `any` added to std's `Looping` took the last copy of `List.any` from `PlayingScreen.rules`, whose closure reads `self`, and cost `PlayingScreen.update` four of its five in-place spreads (since U4c a small callee, every walk of std, gets a copy for every closure). The cost: the in-place pass takes about 2.5 times as long (debug, Orbit Runner 183 to 480 ms): 9 version rounds where there were 5, each about 30% dearer.
11
11
  - **A program with no `Sized` or `Touch` view drops the dead code pass**: std's `Views.touchOf`, `sizedHit` and `missesArea` match `Touch as t` and `Sized as s` on a `View`, and once the pass has dropped every type that is one, the re-check calls each match impossible ("no type is both a View and a Touch"). Every game has such a view, so only a minimal test program meets it. A trait default's copy is told apart since 2026-11-16 (`defaultPositions` reads the trait's declarations), but these are statics.
12
- - **The view's cost**: each frame makes the view's list and items. `benchmarks/screen_views` (`orbit.plum`, `scale.plum`, master's drivers) times it; not yet run against master. Master's stepping walk makes the view once more a tick and each actor's view; this branch's `stepped` makes neither, so the two `update` timings are not the same work (`scale.plum`'s header says so).
12
+ - **The view's cost**: each frame makes the view's items (not its list since U4g, below). `benchmarks/screen_views` (`orbit.plum`, `scale.plum`, master's drivers) times it; not yet run against master. Master's stepping walk makes the view once more a tick and each actor's view; this branch's `stepped` makes neither, so the two `update` timings are not the same work (`scale.plum`'s header says so).
13
13
  - **Stepping without the screen naming its actors**: done at compile time on 2026-11-16: every screen, and an actor that lists `Steps` (std/game/View), has its fields holding actors stepped by a derived `stepped` (or after its own `step`); since the Elm-style screens a screen calls it in its frame action (no stepping phase, no `steps()`), and one that pauses doesn't call it (`docs/game.md`, "Stepping"; the `@stepsWhen(cond)` field attribute was removed on 2026-11-16). A `List<View>` field is stepped by `Views.stepIn` since R3 (each item's type tested as it is stepped).
14
14
 
15
15
  ## Decided, not built
@@ -28,8 +28,9 @@ The retained scene tree was replaced by master's screen view in functional form:
28
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** (recounted 2026-11-16 after U4c, `--explain-fusion`, each "not in place" line by its innermost reason): Orb Run 36 in place, 39 not (10 a value still used after the update, all the time travel's `rewindTo`/`undo`/`redo` from a fold; 8 bound to a shared value; 6 rebound by a pattern, `match self.history / Some(h)` and `Shift.after`; 5 a shared value; 3 taken out of `List.head`; 2 fields out of declaration order; 2 a receiver read again; 1 each other). Orbit Runner 31 in place of 96, Clockwork 26 of 88, Menu 20 of 86, Balloon Pop 23 of 86; the biggest reason in the four games is a receiver kept or read again after a method call (19-22, mostly the time travel and `Looping`). No closure reason is left (Balloon Pop's 5 "an argument is passed from inside a closure" went with U4c: its fold's closures are copies now), but the counts are the same as before U4c: each fix moved a spread's reason one step down. U4c added three proofs, each with a test in `uniqueness_fold_test.rs`: a field moved in one arm of a whole-body `match` (`moveRegions`: `Steer` in `PlayingScreen.update` is now a move of `self.ship`), a variable handed over through an inline `if` (`sized := if c then self.resized(p) else self`), and a field read into a local that is only read (`aliasReads`: `ship := self.ship` then `ship.body.pos`); and a pattern binder handed to a read-only parameter counts as a read. What blocks the hot ones now: `PlayingScreen.ship` is shared because the view holds the ship (`if !self.over then self.ship`), so `Ship.steer`/`step`/`hurtFor` copy; `List.head` is shared because `List.find` returns the head and `List.next` pairs it (a field's uniqueness is one fact for every element type), so the actors' steps copy; `Game.run`'s `sized` needs `Game.resized` to return its `self` in place, which `Game.remake` (shared) blocks. The Elm-style `update` regression (Orbit Runner's update 7-10% slower after the Elm screens) was not found in instructions retired here (`screen_views/orbit.plum update` 283M before U4c, 280M after).
31
- - **Paint** (U4b, 2026-11-16, `sl/paint-direct`): each kind of view has its own copy of the draw's step (`View.paintAt`, `paintCulledAt`, `@final`), so an item costs one trait call in place of four; the walks recurse over the list with no closure (`List.each` with a capturing closure cost about 15% of a paint), skip the walk under an empty view, and an unturned `Place.under`, `Affine.scaleX`/`scaleY`/`rotation`, `Views.through` and a `Left` label skip the matrix product, `hypot`, `atan2` and the text width. `PLUM_NULL_GFX`'s stubs are raw host functions (a typed `Func::new` loaded every argument as a `Val`: a quarter of a timed paint). Instructions retired by the paint (paint run minus update run): Orbit Runner 2,659M to 1,087M, Clockwork (`benchmarks/screen_views/clockwork.plum`, new) 1,394M to 692M, `scale.plum` 7,750M to 2,740M; about a third of each drop is the null host. Open: wasmtime's `compiler_inlining` takes another 20% of instructions off paint and update both, but inlined frames drop out of a crash's `in f (called from g)` (`crash_in_a_loop_names_the_function_not_its_lifted_loop` fails), so it is off; still made each frame: the view's list (spreads upcast and copied) and each item's own list; `List.each`/`map` with a capturing closure is still slow everywhere else (`Views.stepIn`, `drawnIn`).
31
+ - **Paint** (U4b, 2026-11-16, `sl/paint-direct`): each kind of view has its own copy of the draw's step (`View.paintAt`, `paintCulledAt`, `@final`), so an item costs one trait call in place of four; the walks recurse over the list with no closure (`List.each` with a capturing closure cost about 15% of a paint), skip the walk under an empty view, and an unturned `Place.under`, `Affine.scaleX`/`scaleY`/`rotation`, `Views.through` and a `Left` label skip the matrix product, `hypot`, `atan2` and the text width. `PLUM_NULL_GFX`'s stubs are raw host functions (a typed `Func::new` loaded every argument as a `Val`: a quarter of a timed paint). Instructions retired by the paint (paint run minus update run): Orbit Runner 2,659M to 1,087M, Clockwork (`benchmarks/screen_views/clockwork.plum`, new) 1,394M to 692M, `scale.plum` 7,750M to 2,740M; about a third of each drop is the null host. Open: wasmtime's `compiler_inlining` takes another 20% of instructions off paint and update both, but inlined frames drop out of a crash's `in f (called from g)` (`crash_in_a_loop_names_the_function_not_its_lifted_loop` fails), so it is off; the view's list and each item's own list are no longer made to be drawn (U4g, below); `List.each`/`map` with a capturing closure is still slow everywhere else (`Views.stepIn`, `drawnIn`).
32
32
  - **Closures inlined by size** (U4c, 2026-11-16): a callee of at most 64 expression nodes (`closure_spec::SMALL_CALLEE`; std's closure-taking fns are 3-59, `List.map` 3, `fold` 8, `Range.fold` 33, `Slice.mergeRun` 59, the biggest in the repository 68) gets a copy for every closure handed to it; a bigger one keeps a cap of 8 (`MAX_BIG_COPIES`) per callee, in the order its calls are met, so which of its calls are inlined still depends on the rest of the program. Copies made inside copies stop at 4 levels (`MAX_DEPTH`), and 256 copies of one small callee is a safety net. The escape analysis now resolves `x.m(..)` by the checker's receiver type (`FnCall.recv`, stamped before closure specialisation): `List.all` had never been specialised, as `t.all(keep)` resolved to every `all` and `Set.all` captures its closure. Cost: Orbit Runner compiles in 2.7% more instructions (8,722M to 8,957M), its .wasm is 352 bytes bigger (112,515 to 112,867). Run time within 1% in instructions retired on every benchmark (Orb Run 839M to 845M, Orbit Runner update 283M to 280M, Clockwork update 639M to 643M, `closures/calls` 3,084M to 3,083M; whole process, wasmtime's compile included).
33
+ - **View lists painted with none made** (U4g, 2026-11-16, `sl/view-fusion`): where a type's `view` is a list literal, each kind's copy of `paintAt`/`paintCulledAt` and each screen's copy of the new `@final` `Screen.paintView`/`paintCulledView` (what `Game.draw` calls) paint the literal's items in place (`plum_core::view_walk`, run with closure specialisation, so its `each` closures are inlined): a value drawn as it is made (an actor's one-item `[Sprite(..)]` makes no cell), a spread `..self.mines` walked as the `List<Mine>` it is (no `__upcastOnto` copy), an `if` item drawn when its condition holds, a spread `map` over a `List`, `Range` or `Option` drawn as `each`; a kind whose view is empty starts no walk; the culling walks are made only when some screen's `culls()` is not `false`. `view()` is unchanged for hits, `drawList` and games. Instructions retired by the paint (paint run minus update run, min of 5): Orbit Runner 965M to 831M (-14%), Clockwork 606M to 557M (-8%), `scale.plum` `view` 2,524M to 2,134M (-15%), `spread` 2,514M to 2,006M (-20%), `hand` 1,318M to 1,261M (-4%); update and checksums unchanged. Cost: Orbit Runner's .wasm 113,350 to 117,356 bytes and its compile +2% instructions (Clockwork 116,080 to 121,504, +3%). Still made each frame: the items themselves (a `Sprite` under each `ViewDot`, `scale.plum`'s `view` is 1.7x `hand`), a `Group`'s or `Overlay`'s children list (a field), the closure object handed to each specialised `each` (closure specialisation keeps the parameter).
33
34
  - **Smaller codegen items**: the inliner skips leaves that use their locals (`unbox.*`); purity treats every closure-taking function as impure, so pipelines fuse only after closure specialisation.
34
35
  - No evidence either way, so not planned: unchecked reads in `for` over a `Slice` (checked `at` showed no cost).
35
36
 
docs/game.md CHANGED
@@ -101,7 +101,7 @@ fun view(self) -> List<View> = [
101
101
  ]
102
102
  ```
103
103
 
104
- The view is one list literal, one item a line, its items in drawing order (later items draw over earlier ones). A parent's children are its block: `Overlay(w: .., h: ..) {` + one child a line + `}` is the overlay with those `children` (a construction's block is its last field; see [blocks](language.md#lists-slices-and-maps)), so the view reads as the tree it draws. What shows only sometimes is an `if` item (the ship until the run is over, the game over panel once it is), what repeats is a spread of a `map` over a range (forty stars, one icon a life), and a list the screen holds is spread as it is (`..self.mines`). Nothing is annotated: the literal is a `List<View>` because `view` returns one, and each spread `List<Mine>` widens to it (rebuilt as a `List<View>` there; see [Coercion](language.md#coercion) and [list literal items](language.md#lists-slices-and-maps)).
104
+ The view is one list literal, one item a line, its items in drawing order (later items draw over earlier ones). A parent's children are its block: `Overlay(w: .., h: ..) {` + one child a line + `}` is the overlay with those `children` (a construction's block is its last field; see [blocks](language.md#lists-slices-and-maps)), so the view reads as the tree it draws. What shows only sometimes is an `if` item (the ship until the run is over, the game over panel once it is), what repeats is a spread of a `map` over a range (forty stars, one icon a life), and a list the screen holds is spread as it is (`..self.mines`). Nothing is annotated: the literal is a `List<View>` because `view` returns one, and each spread `List<Mine>` widens to it (rebuilt as a `List<View>` there; see [Coercion](language.md#coercion) and [list literal items](language.md#lists-slices-and-maps)). Drawing a frame builds none of it: the draw walks the literal's items in place ("How std draws a view", below).
105
105
 
106
106
  - **Drawn, not live.** The view is made again every time it is walked (to draw, to hit-test a press), and an item made inside it keeps nothing from one walk to the next. So each takes plain values read from the fields (a `Label`'s `text`, a `Sprite`'s `frame`). A `Group` or an `Overlay` in a view has the children it is made with (its block) as its own `view`, and an actor with a view of its own draws that, so views nest. Balloon Pop's clouds are groups: `Group(x: x, y: y) {` + three circles placed around the group's origin + `}`.
107
107
  - **Two kinds of item.** An actor the screen holds in a field and names in its view (the ship, each mine of `self.mines`) is the very object in the field when the frame is drawn: a press on it reaches the screen as that object ([Clicks](#clicks)), and an actor that says what a press on it means (`Presses<A>`) gives that action. The screen steps it in its frame action, through its `stepped`, which returns the screen with the actor's next version. An item made inside `view` (the score label, the stars, the game over panel) is a new object every frame, made from the fields.
@@ -226,7 +226,7 @@ Every kind is at the origin of what it is in unless given an `x` and a `y`: an a
226
226
 
227
227
  ### How std draws a view
228
228
 
229
- The game draws the shown screen once per frame (`Game.draw`): it clears with the screen's `background()` and draws the screen's `view()`, made for the frame, through its camera's transform (the world to the window's pixels) with `Views.paint`: each visible item through its place, its `paintSelf` and then its own view, multiplying the alphas down (after a `Blend`'s view, the blend mode goes back to the one it was drawn in). An item scaled flat (0 on an axis) is drawn as the host draws it, and never hit, nor what is under it. A screen that `culls()` is drawn with `Views.paintCulled`, which skips each `Sized` item whose bounds miss what the camera shows, with what is under it. Each kind of view draws its own items: `View` has two `@final` methods, `paintAt` and `paintCulledAt` (the walks' step for one item), so each kind gets its own copy, in which its `visible`, `place`, `paintSelf` and `view` are direct calls; an item drawn costs one call through `View`, and an item with an empty view starts no walk under it. Then the screen's `hud(window)` is drawn one unit a pixel. During a transition both screens are drawn this way, each on its own background, moved and faded. `Game.drawList()` lists what a frame draws, each item with its transform and alpha (`Drawn`), culled as the frame is, the hud's after the view's; std/game/TestRig reads it.
229
+ The game draws the shown screen once per frame (`Game.draw`): it clears with the screen's `background()` and draws the screen's `view()`, made for the frame, through its camera's transform (the world to the window's pixels) with `Views.paint`: each visible item through its place, its `paintSelf` and then its own view, multiplying the alphas down (after a `Blend`'s view, the blend mode goes back to the one it was drawn in). An item scaled flat (0 on an axis) is drawn as the host draws it, and never hit, nor what is under it. A screen that `culls()` is drawn with `Views.paintCulled`, which skips each `Sized` item whose bounds miss what the camera shows, with what is under it. Each kind of view draws its own items: `View` has two `@final` methods, `paintAt` and `paintCulledAt` (the walks' step for one item), so each kind gets its own copy, in which its `visible`, `place`, `paintSelf` and `view` are direct calls; an item drawn costs one call through `View`, and an item with an empty view starts no walk under it. The list a `view` writes as a literal is not built to be drawn: in each kind's copy of `paintAt` and `paintCulledAt`, and in each screen's copy of `Screen.paintView` and `paintCulledView` (also `@final`, what `Game.draw` calls), the compiler paints each item where the literal would have put it in the list (`plum_core::view_walk`): a value is drawn as it is made, a spread `..self.mines` walks the screen's `List<Mine>` as it is (no `List<View>` copy), an `if` item is drawn when its condition holds, and a spread of a `map` over a `List`, a `Range` or an `Option` draws each item as `map` would have made it. The same items are drawn in the same order, culled alike; each is made just before it is drawn, which a `view` that only computes its items can't tell. `view()` itself is unchanged, and what else reads it (the hit tests, `drawList`, a game's own calls) gets the list. Then the screen's `hud(window)` is drawn one unit a pixel. During a transition both screens are drawn this way, each on its own background, moved and faded. `Game.drawList()` lists what a frame draws, each item with its transform and alpha (`Drawn`), culled as the frame is, the hud's after the view's; std/game/TestRig reads it.
230
230
 
231
231
  Nothing is kept between frames, and there is no tree: the game keeps the screens and their state, the camera's inputs (each screen's `size()`, `viewport()` and `camera`, the window's size) and the transition, and works out the rest when it needs it. One walk goes over a view for everything (draw, cull, list, hit test, find): an item, then its `view()`. The walks are the statics of `Views` in `std/game/View` (`paint`, `paintCulled`, `drawnIn`, `hitIn`, `worldIn`), with `stepAll`, `stepSome` and `stepIn` for a derived stepping.
232
232
 
std/Option.plum CHANGED
@@ -29,6 +29,11 @@ enum Option<T> =
29
29
  None => None
30
30
  Some(v) => Some(f(v))
31
31
 
32
+ # Calls `f` on the value, if there is one.
33
+ fun each(self, f: fn(T) -> Unit) -> Unit =
34
+ if Some(v) := self
35
+ f(v)
36
+
32
37
  fun andThen<B>(self, f: fn(T) -> Option<B>) -> Option<B> = match self
33
38
  None => None
34
39
  Some(v) => f(v)
std/game/Game.plum CHANGED
@@ -344,9 +344,9 @@ struct Game(screens: List<Screen>) =
344
344
  area := Aabb(min: Vec2(x: v.min.x - f.x / c.sx, y: v.min.y - f.y / c.sy), max: Vec2(x: v.max.x - f.x / c.sx, y: v.max.y - f.y / c.sy))
345
345
  m := Affine(a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: f.x, f: f.y).mul(c.transform())
346
346
  if s.culls()
347
- Views.paintCulled(io, s.view(), m, f.alpha, Views.through(area, m))
347
+ s.paintCulledView(io, m, f.alpha, Views.through(area, m))
348
348
  else
349
- Views.paint(io, s.view(), m, f.alpha)
349
+ s.paintView(io, m, f.alpha)
350
350
  hud := s.hud(self.pixels)
351
351
  if !hud.isEmpty()
352
352
  Views.paint(io, hud, Affine(a: 1.0, b: 0.0, c: 0.0, d: 1.0, e: f.x, f: f.y), f.alpha)
std/game/Screen.plum CHANGED
@@ -13,6 +13,7 @@ import std/math/Aabb
13
13
  import std/game/Color
14
14
  import std/game/Input
15
15
  import std/game/View
16
+ import std/game/Blend
16
17
  import std/game/Viewport
17
18
  import std/game/Cmd
18
19
  import std/game/ScreenSlice
@@ -126,6 +127,14 @@ trait Screen =
126
127
 
127
128
  fun wants(self, h: Held) -> Bool = false
128
129
 
130
+ # Draws its view through `m` at `alpha` (`Views.paint`; std/game/Game's frame): `@final`,
131
+ # so each screen has its own copy, in which the compiler walks the list its `view`
132
+ # writes as it is built, with no list made (std/game/View, "Drawing a view").
133
+ @final fun paintView(self, io: Io, m: Affine, alpha: Float) = Views.paintIn(io, self.view(), m, alpha, Blend.Normal)
134
+
135
+ # `paintView`, culled to `area` (`Views.paintCulled`).
136
+ @final fun paintCulledView(self, io: Io, m: Affine, alpha: Float, area: Aabb) = Views.paintCulledIn(io, self.view(), m, alpha, area, Blend.Normal)
137
+
129
138
  # One tick of a screen, delivered: the screen after it, the commands its actions gave for
130
139
  # the game (std/game/Cmd), in order, the actions stepped, and whether the tick was a user
131
140
  # action (std/game/History): a subscription or a press gave an action for one of its
std/game/View.plum CHANGED
@@ -113,9 +113,7 @@ trait View =
113
113
  me: View := self
114
114
  blend := Views.blendOf(me)
115
115
  self.paintSelf(io, mk, ak)
116
- under := self.view()
117
- if !under.isEmpty()
118
- Views.paintIn(io, under, mk, ak, if blend < 0 then mode else blend)
116
+ Views.paintIn(io, self.view(), mk, ak, if blend < 0 then mode else blend)
119
117
  if blend >= 0
120
118
  Gfx.blendMode(io, mode)
121
119
 
@@ -129,9 +127,7 @@ trait View =
129
127
  ak := alpha * at.alpha
130
128
  blend := Views.blendOf(me)
131
129
  self.paintSelf(io, mk, ak)
132
- under := self.view()
133
- if !under.isEmpty()
134
- Views.paintCulledIn(io, under, mk, ak, area, if blend < 0 then mode else blend)
130
+ Views.paintCulledIn(io, self.view(), mk, ak, area, if blend < 0 then mode else blend)
135
131
  if blend >= 0
136
132
  Gfx.blendMode(io, mode)
137
133
 
tests/std/game/View.plum CHANGED
@@ -190,6 +190,51 @@ primitive ViewTest[UnitTest] =
190
190
  assert p.right.map(|x| x.time) == Some(0.25)
191
191
  assert p.right.map(|x| x.kids.map(|k| k.time)) == Some([0.25])
192
192
 
193
+ # a screen paints its view as the list would be painted, though no list is made: values,
194
+ # spreads of its own kind, of views and of an option, conditional items and spreads, a
195
+ # mapped range, a group's children, a kind of its own with a view of its own
196
+ fun aScreenPaintsItsViewAsItsListWouldBe() =
197
+ log := Slice<Float>()
198
+ assert ViewHelpers.paintsAsItsList(io, ViewHelpers.walked(log, true, 0), log)
199
+ assert ViewHelpers.paintsAsItsList(io, ViewHelpers.walked(log, true, 3), log)
200
+ assert ViewHelpers.paintsAsItsList(io, ViewHelpers.walked(log, false, 0), log)
201
+ assert ViewHelpers.paintsAsItsList(io, ViewHelpers.walked(log, false, 3), log)
202
+ s := ViewHelpers.walked(log, true, 2)
203
+ s.paintView(io, Affine.Identity, 1.0)
204
+ # x then alpha of each probe: the first, the two of `probes`, the loose one, the one shown,
205
+ # the option's, the two mapped (faded), the group's at 100 and the badge's two at 300.
206
+ expect := [1.0, 1.0, 6.0, 1.0, 7.0, 1.0, 8.0, 1.0, 2.0, 1.0, 9.0, 1.0, 10.0, 0.5, 11.0, 0.5, 103.0, 1.0, 301.0, 1.0, 302.0, 0.25]
207
+ assert List.fromSlice(log) == expect
208
+
209
+ # an empty view paints nothing, and a culled screen leaves out what misses the area, with its view
210
+ fun aCulledScreenLeavesOutWhatMissesTheArea() =
211
+ log := Slice<Float>()
212
+ s := ViewHelpers.walked(log, true, 1)
213
+ area := Aabb.of(0.0, 0.0, 150.0, 100.0)
214
+ s.paintCulledView(io, Affine.Identity, 1.0, area)
215
+ fused := List.fromSlice(log)
216
+ log.clear()
217
+ Views.paintCulled(io, s.view(), Affine.Identity, 1.0, area)
218
+ assert fused == List.fromSlice(log)
219
+ assert !fused.any(|x| x == 301.0) && fused.any(|x| x == 103.0)
220
+ log.clear()
221
+ Walked(log: log, shown: false, probes: Nil, loose: Nil, extra: None, n: 0, badge: false).paintView(io, Affine.Identity, 1.0)
222
+ assert log.isEmpty()
223
+
224
+ # the list a screen paints with none made is still its view: a press finds an item of it
225
+ fun aPressFindsAnItemOfAWalkedView() =
226
+ log := Slice<Float>()
227
+ s := ViewHelpers.walked(log, true, 2)
228
+ s.paintView(io, Affine.Identity, 1.0)
229
+ hit := Views.hitIn(s.view(), Vec2(x: 305.0, y: 5.0))
230
+ assert hit.isSome()
231
+ assert match hit.unwrap()
232
+ Badge as b => b.x == 300.0
233
+ _ => false
234
+ found := Slice<Drawn>()
235
+ Views.drawnIn(s.view(), Affine.Identity, 1.0, found, Aabb.of(0.0, 0.0, 0.0, 0.0), false)
236
+ assert found.length() == 13
237
+
193
238
  struct ViewProbe[View](x: Float, log: Slice<Float>, fade: Float) =
194
239
  fun place(self) -> Place = Place.at(self.x, 0.0).fade(self.fade)
195
240
 
@@ -255,6 +300,21 @@ primitive ViewHelpers =
255
300
 
256
301
  fun probeAt(x: Float, log: Slice<Float>) -> View = ViewProbe(x: x, log: log, fade: 1.0)
257
302
 
303
+ # Whether `s` paints what `Views.paint` of its view's list paints, and something; `log` is
304
+ # left empty.
305
+ fun paintsAsItsList(io: Io, s: Walked, log: Slice<Float>) -> Bool =
306
+ s.paintView(io, Affine.Identity, 1.0)
307
+ fused := List.fromSlice(log)
308
+ log.clear()
309
+ Views.paint(io, s.view(), Affine.Identity, 1.0)
310
+ same := fused == List.fromSlice(log)
311
+ log.clear()
312
+ same && !fused.isEmpty()
313
+
314
+ fun walked(log: Slice<Float>, shown: Bool, n: Int) -> Walked =
315
+ probes := [ViewProbe(x: 6.0, log: log, fade: 1.0), ViewProbe(x: 7.0, log: log, fade: 1.0)]
316
+ Walked(log: log, shown: shown, probes: probes, loose: [ViewHelpers.probeAt(8.0, log)], extra: Some(ViewProbe(x: 9.0, log: log, fade: 1.0)), n: n, badge: true)
317
+
258
318
  # A screen whose actors are stepped for it, of each kind a field can hold them in.
259
319
  struct Stage[Screen](
260
320
  n: Int,
@@ -277,3 +337,34 @@ struct Nest[Actor, Steps](time: Float, kids: List<Stepper>, inner: Stepper) =
277
337
  # An actor that is only what it holds.
278
338
  struct Pair[Actor, Steps](left: Stepper, right: Option<Nest>) =
279
339
  fun place(self) -> Place = Place.at(0.0, 0.0)
340
+
341
+ # A screen whose view is a list literal of every kind of item (`aScreenPaintsItsViewAsItsListWouldBe`).
342
+ struct Walked[Screen](
343
+ log: Slice<Float>, shown: Bool,
344
+ probes: List<ViewProbe>, loose: List<View>, extra: Option<ViewProbe>,
345
+ n: Int, badge: Bool
346
+ ) =
347
+ fun view(self) -> List<View> = [
348
+ if self.badge then ViewHelpers.probeAt(1.0, self.log)
349
+ ..self.probes
350
+ ..self.loose
351
+ if self.shown then ViewHelpers.probeAt(2.0, self.log)
352
+ if !self.shown then ..self.probes
353
+ ..self.extra
354
+ ..Range.until(0, self.n).map(|i| ViewProbe(x: 10.0 + Float(i), log: self.log, fade: 0.5))
355
+ if self.badge then Group(x: 100.0) { ViewHelpers.probeAt(3.0, self.log) }
356
+ if self.badge then Badge(x: 300.0, log: self.log, lit: self.shown)
357
+ ]
358
+
359
+ # A kind whose view is a literal, sized for culling and pressed.
360
+ struct Badge[View, Sized, Touch](x: Float, log: Slice<Float>, lit: Bool) =
361
+ fun place(self) -> Place = Place.at(self.x, 0.0)
362
+
363
+ fun bounds(self) -> Aabb = Aabb.of(0.0, 0.0, 10.0, 10.0)
364
+
365
+ fun touch(self) -> Touchable = Enabled
366
+
367
+ fun view(self) -> List<View> = [
368
+ if self.lit then ViewHelpers.probeAt(1.0, self.log)
369
+ ViewProbe(x: 2.0, log: self.log, fade: 0.25)
370
+ ]