plum

#treesitter#compiler#wasm

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

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


addf12c — Peter John 2026-11-16T12:29:39+05:30
derived stepping (std/game review R2b): a struct that lists `Steps` (`trait Steps`, a marker in std/game/View) has its fields holding actors stepped by code the compiler writes out before checking (core/steps_derive.rs, `deriveSteps`, first in the front end), the same static construction a hand-written one is, not a walk at run time: a field that is an `Actor` (a type implementing it, or a trait type that is one) is `self.f.step(dt)`, a `List` of actors `Views.stepAll(self.f, dt)`, an `Option` of one `Views.stepSome(self.f, dt)` (new in std), the other fields as they are; on a `Screen` it is `stepped(self, dt)`, and a screen that writes its own `stepped` keeps it (no error); on an `Actor` the fields are stepped after its own `step`, which is renamed `step$own`, the derived `step` being `self.step$own(dt).step$fields(dt)` (or the fields' stepping alone when it writes none), so a container writes only what is special about it and the fields' conditions read the actor after its own step; a field attribute, `@stepsWhen(cond) name: T` (grammar: an optional `field_attribute`, `@name(expr)`, before a struct field; `EnumVariant.field_steps_when`), steps that field only while `cond`, read on `self`, holds (`if cond then <stepped> else self.f`), which pauses one field where `steps()` pauses a whole screen (still there for hand-written ones); errors, each at the type or the condition: `Steps` on an enum, on a struct that is neither a `Screen` nor an `Actor`, or on one with no field holding actors; `@stepsWhen` on a field holding no actors, on a type that doesn't list `Steps`, or on a screen that writes its own `stepped` (it would do nothing); any other attribute name is a parse error; a `List<View>` field is not stepped (views, not actors: `Views.stepIn` by hand); games: Orbit Runner's screen is `[ScreenSlice<PlayAction>, Steps]` with `@stepsWhen(!self.over)` on `ship`, `orbs` and `mines`, so its `steps()`, its `stepped` and the rings stepped by hand in `advance` once the run is over are gone (the rings step on under the panel with no condition); Balloon Pop's playground and clicks' tap screen list `Steps` and lose `stepped`; the games are 15 lines removed, 5 added; Orbit Runner's checksum is unchanged, 946756219; benchmarks/screen_views (scale's `SpreadScreen` now derived, `CrowdScreen` keeps `Views.stepIn`): orbit update 12.9-13.3 ms before, 12.8-12.9 ms after, paint 132.9-133.2 ms before, 132.5-134.1 ms after, scale update spread (10,000 actors) 19.0-19.9 ms before, 19.2 ms after, update view 22.4-22.8 ms before, 22.4-22.6 ms after; formatter: a space after the attribute; highlights; tests: tests/std/game/View.plum (a screen's actor, list, option, trait-typed and plain fields, `@stepsWhen`, a hand-written `stepped` winning, an actor's fields after its own step, an actor with no `step` of its own holding a nested `[Steps]` actor), tests/port/game/screens.plum's `StillScreen` derived through the game, checker diagnostics for each error, a formatter test, a corpus case; docs: game.md (Stepping, the sample, the traits table, the "Beside master" row), language.md (field attributes and derived methods, the built-ins table), std.md, backlog, Screen and View doc comments, the review plan
benchmarks/screen_views/scale.plum CHANGED
@@ -134,7 +134,7 @@ struct CrowdScreen[ScreenSlice<CrowdAct>](hand: Bool, dots: List<View>) =
134
134
 
135
135
  fun frameSum(self) -> Int = Timing.hash(self.dots.map(|d| ScaleBench.frameOf(d)))
136
136
 
137
- struct SpreadScreen[ScreenSlice<CrowdAct>](dots: List<ViewDot>) =
137
+ struct SpreadScreen[ScreenSlice<CrowdAct>, Steps](dots: List<ViewDot>) =
138
138
  fun of(n: Int) -> SpreadScreen = SpreadScreen(dots: Range.until(0, n).map(|i| ViewDot.of(i)))
139
139
 
140
140
  fun name(self) -> Str = "spread"
@@ -144,8 +144,6 @@ struct SpreadScreen[ScreenSlice<CrowdAct>](dots: List<ViewDot>) =
144
144
  Box(w: 800.0, h: 4.0, color: Color.White)
145
145
  ]
146
146
 
147
- fun stepped(self, dt: Float) -> SpreadScreen = SpreadScreen(..self, dots: Views.stepAll(self.dots, dt))
148
-
149
147
  fun tick(self, dt: Float) -> Option<CrowdAct> = Some(CrowdTick(dt: dt))
150
148
 
151
149
  fun reduce(self, a: CrowdAct) -> SpreadScreen = match a
compiler/checker/tests/checker/diagnostic_tests.rs CHANGED
@@ -388,3 +388,45 @@ fn aBadFieldDefaultIsReportedOnce() {
388
388
  assert_eq!(es.len(), 2, "{es:?}");
389
389
  assert!(es[1].message.contains("variant 'P' field 'y'"), "{es:?}");
390
390
  }
391
+
392
+ const STEPS_TRAITS: &str = "trait Actor =\n fun step(self, dt: Float) -> Self\n\ntrait Screen =\n fun name(self) -> Str\n\ntrait Steps\n\nstruct W[Actor](t: Float) =\n fun step(self, dt: Float) -> W = W(t: self.t + dt)\n\n";
393
+
394
+ fn stepsErrors(rest: &str) -> Vec<plum_core::diag::Diagnostic> {
395
+ frontErrors(&format!("{STEPS_TRAITS}{rest}\nprimitive Main[App] =\n fun main() -> Int = 1\n"))
396
+ }
397
+
398
+ /// `[Steps]` is for a struct that is a `Screen` or an `Actor` and holds actors.
399
+ #[test]
400
+ fn stepsNeedsAScreenOrActorStructHoldingActors() {
401
+ let es = stepsErrors("enum E[Actor, Steps] = A | B\n");
402
+ assert!(es.iter().any(|e| e.message.contains("`E` lists `Steps`, which steps a struct's actor fields, but it is an enum")), "{es:?}");
403
+ let es = stepsErrors("struct P[Steps](w: W)\n");
404
+ assert_eq!(es.len(), 1, "{es:?}");
405
+ assert!(es[0].message.contains("`P` lists `Steps` but is neither a `Screen` nor an `Actor`"), "{es:?}");
406
+ assert_eq!((es[0].file.as_str(), es[0].line), ("main.plum", 12), "{es:?}");
407
+ let es = stepsErrors("struct P[Screen, Steps](n: Int, ws: List<Int>) =\n fun name(self) -> Str = \"p\"\n");
408
+ assert_eq!(es.len(), 1, "{es:?}");
409
+ assert!(es[0].message.contains("`P` lists `Steps` but holds no actors"), "{es:?}");
410
+ }
411
+
412
+ /// `@stepsWhen` goes on a field holding actors of a `[Steps]` type that derives its stepping.
413
+ #[test]
414
+ fn stepsWhenGoesOnAnActorFieldOfAStepsType() {
415
+ let es = stepsErrors("struct P[Screen, Steps](on: Bool, @stepsWhen(self.on) n: Int, w: W) =\n fun name(self) -> Str = \"p\"\n");
416
+ assert_eq!(es.len(), 1, "{es:?}");
417
+ assert!(es[0].message.contains("`@stepsWhen` on `P.n`, a `Int`: only a field holding actors is stepped"), "{es:?}");
418
+ assert_eq!((es[0].line, es[0].column), (12, 46), "{es:?}");
419
+ let es = stepsErrors("struct P[Screen](on: Bool, @stepsWhen(self.on) w: W) =\n fun name(self) -> Str = \"p\"\n");
420
+ assert_eq!(es.len(), 1, "{es:?}");
421
+ assert!(es[0].message.contains("`@stepsWhen` on `P.w`: `P` doesn't list `Steps`"), "{es:?}");
422
+ let es = stepsErrors("struct P[Screen, Steps](on: Bool, @stepsWhen(self.on) w: W) =\n fun name(self) -> Str = \"p\"\n\n fun stepped(self, dt: Float) -> P = self\n");
423
+ assert_eq!(es.len(), 1, "{es:?}");
424
+ assert!(es[0].message.contains("`@stepsWhen` on `P.w` does nothing: `P` writes its own `stepped`"), "{es:?}");
425
+ }
426
+
427
+ /// `@stepsWhen` is the one field attribute.
428
+ #[test]
429
+ fn anUnknownFieldAttributeIsAnError() {
430
+ let es = errors(&format!("{STEPS_TRAITS}struct P[Screen, Steps](@later(1) w: W) =\n fun name(self) -> Str = \"p\"\n\nprimitive Main[App] =\n fun main() -> Int = 1\n"));
431
+ assert!(es.iter().any(|e| e.message.contains("`@later` is not a field attribute")), "{es:?}");
432
+ }
compiler/core/src/ast.rs CHANGED
@@ -614,6 +614,10 @@ pub struct EnumVariant {
614
614
  /// field has one. A construction that leaves a defaulted field out gets a fresh copy of
615
615
  /// its default (`field_defaults::fillFieldDefaults`).
616
616
  pub field_defaults: Vec<Option<Expr>>,
617
+ /// `@stepsWhen(cond) name: T` on a `[Steps]` struct's field, aligned with `field_names`;
618
+ /// empty when no field has one. Moved into the derived `stepped`/`step` and emptied by
619
+ /// `steps_derive::deriveSteps`, first in the front end.
620
+ pub field_steps_when: Vec<Option<Expr>>,
617
621
  }
618
622
 
619
623
  // ---------- Functions ----------
compiler/core/src/lib.rs CHANGED
@@ -36,6 +36,7 @@ pub mod reuse;
36
36
  pub mod session;
37
37
  pub mod simplify;
38
38
  pub mod spread_paths;
39
+ pub mod steps_derive;
39
40
  pub mod tail;
40
41
  pub mod trait_defaults;
41
42
  pub mod tests_lower;
compiler/core/src/lower.rs CHANGED
@@ -30,6 +30,11 @@ pub fn frontEndDiag(source: &mut Source) -> Result<(), Vec<Diagnostic>> {
30
30
  if !nativeErrors.is_empty() {
31
31
  return Err(nativeErrors);
32
32
  }
33
+ // First: the derived `stepped`/`step` are ordinary methods for every pass after it.
34
+ let stepsErrors = crate::steps_derive::deriveSteps(source);
35
+ if !stepsErrors.is_empty() {
36
+ return Err(stepsErrors);
37
+ }
33
38
  let blockFieldErrors = crate::children_block::nameBlockFields(source);
34
39
  if !blockFieldErrors.is_empty() {
35
40
  return Err(blockFieldErrors);
compiler/core/src/parser.rs CHANGED
@@ -478,6 +478,28 @@ impl<'a> AstParser<'a> {
478
478
  } else {
479
479
  Vec::new()
480
480
  };
481
+ // `@stepsWhen(cond) name: T`: the one field attribute (std/game's `Steps`).
482
+ let field_steps_when: Vec<Option<Expr>> = if named_fields.iter().any(|n| n.child_by_field_name("attribute").is_some()) {
483
+ named_fields
484
+ .iter()
485
+ .map(|n| {
486
+ let a = n.child_by_field_name("attribute")?;
487
+ let name = a.child_by_field_name("name").map(|c| self.text(c)).unwrap_or_default();
488
+ if name != "stepsWhen" {
489
+ let pos = a.start_position();
490
+ self.litErrors.borrow_mut().push((
491
+ pos.row + 1,
492
+ pos.column + 1,
493
+ format!("`@{name}` is not a field attribute: the one there is is `@stepsWhen(condition)`, on a field of a `[Steps]` type"),
494
+ ));
495
+ return None;
496
+ }
497
+ a.child_by_field_name("argument").map(|d| self.parseExpression(self.unwrapExprNode(d)))
498
+ })
499
+ .collect()
500
+ } else {
501
+ Vec::new()
502
+ };
481
503
  let (fields, field_names): (Vec<Type>, Vec<String>) = if !named_fields.is_empty() {
482
504
  named_fields
483
505
  .iter()
@@ -511,6 +533,7 @@ impl<'a> AstParser<'a> {
511
533
  field_names,
512
534
  mut_fields,
513
535
  field_defaults,
536
+ field_steps_when,
514
537
  }
515
538
  }
516
539
 
compiler/core/src/steps_derive.rs ADDED
@@ -0,0 +1,269 @@
1
+ //! `[Steps]` (std/game/View): the stepping of a struct's actor fields, derived.
2
+ //!
3
+ //! A struct that lists `Steps` gets, as an ordinary method written out here before the
4
+ //! checker sees it, the stepping of each field that holds actors: a field whose type is an
5
+ //! `Actor` (a type that implements it, or a trait type that is one), a `List` of actors or an
6
+ //! `Option` of one. Other fields are left as they are. What is made is what a screen would
7
+ //! write by hand, one static construction:
8
+ //!
9
+ //! fun stepped(self, dt: Float) -> PlayingScreen =
10
+ //! PlayingScreen(..self, ship: self.ship.step(dt), mines: Views.stepAll(self.mines, dt))
11
+ //!
12
+ //! (`Views.stepSome` for an `Option`), so it costs what the hand-written one did.
13
+ //!
14
+ //! - On a `Screen` it is `stepped(dt)`, what the game calls each tick unless `steps()` is
15
+ //! false. A screen that writes its own `stepped` keeps it: nothing is derived.
16
+ //! - On an `Actor` it is part of `step`: the actor's own `step`, if it writes one, runs first
17
+ //! (it is renamed `step$own`), and then its actor fields are stepped (`step$fields`), so a
18
+ //! container writes only what is special about itself, and the fields' conditions see the
19
+ //! actor after its own step.
20
+ //! - `@stepsWhen(cond) name: T` steps that field only while `cond` (read on `self`) holds:
21
+ //! `if cond then <stepped> else self.name`. It pauses one field where `steps()` pauses the
22
+ //! whole screen.
23
+ //!
24
+ //! Errors: `Steps` on an enum, on a struct that is neither a `Screen` nor an `Actor`, or on
25
+ //! one with no field holding actors; `@stepsWhen` on a field that holds no actors, on a type
26
+ //! that doesn't list `Steps`, or on a screen that writes its own `stepped` (the attribute
27
+ //! would do nothing).
28
+
29
+ use std::collections::{HashMap, HashSet};
30
+
31
+ use crate::ast::*;
32
+ use crate::diag::{DiagKind, Diagnostic};
33
+ use crate::forms::mapExprs;
34
+ use crate::main_result::{parseItems, typeText};
35
+
36
+ /// The trait a struct lists to have its actor fields stepped.
37
+ pub const STEPS_TRAIT: &str = "Steps";
38
+ const ACTOR: &str = "Actor";
39
+ const SCREEN: &str = "Screen";
40
+ /// An actor's own `step`, renamed when the derived `step` steps its fields after it.
41
+ pub const OWN_STEP: &str = "step$own";
42
+ /// The stepping of an actor's fields, called by the derived `step` after `step$own`.
43
+ pub const FIELDS_STEP: &str = "step$fields";
44
+ const COND: &str = "stepsWhenDerived";
45
+
46
+ #[derive(Clone, Copy)]
47
+ enum Holds {
48
+ One,
49
+ List,
50
+ Some_,
51
+ }
52
+
53
+ /// Writes out each `[Steps]` struct's stepping (see the module doc) and empties every
54
+ /// `field_steps_when`. Returns the errors.
55
+ pub fn deriveSteps(source: &mut Source) -> Vec<Diagnostic> {
56
+ let anyAttr = source.items.iter().any(|i| matches!(i, Item::Enum(e) if e.variants.iter().any(|v| !v.field_steps_when.is_empty())));
57
+ let anySteps = source.items.iter().any(|i| matches!(i, Item::Enum(e) if lists(e, STEPS_TRAIT)));
58
+ if !anyAttr && !anySteps {
59
+ return Vec::new();
60
+ }
61
+ let supers: HashMap<String, Vec<String>> = source
62
+ .items
63
+ .iter()
64
+ .filter_map(|i| match i {
65
+ Item::Trait(t) => Some((t.name.clone(), t.supers.iter().map(|s| s.name.clone()).collect())),
66
+ _ => None,
67
+ })
68
+ .collect();
69
+ let closure = |start: Vec<String>| -> HashSet<String> {
70
+ let mut seen: HashSet<String> = HashSet::new();
71
+ let mut todo = start;
72
+ while let Some(n) = todo.pop() {
73
+ if seen.insert(n.clone()) {
74
+ todo.extend(supers.get(&n).cloned().unwrap_or_default());
75
+ }
76
+ }
77
+ seen
78
+ };
79
+ let traitsOf: HashMap<String, HashSet<String>> = source
80
+ .items
81
+ .iter()
82
+ .filter_map(|i| match i {
83
+ Item::Enum(e) => Some((e.name.clone(), closure(e.implements.iter().map(|t| t.name.clone()).collect()))),
84
+ _ => None,
85
+ })
86
+ .collect();
87
+ let isActor = |name: &str| {
88
+ name == ACTOR
89
+ || (supers.contains_key(name) && closure(vec![name.to_string()]).contains(ACTOR))
90
+ || traitsOf.get(name).is_some_and(|ts| ts.contains(ACTOR))
91
+ };
92
+ let holds = |t: &Type| -> Option<Holds> {
93
+ let inner = |h: Holds| (t.generics.len() == 1 && isActor(&t.generics[0].name)).then_some(h);
94
+ match t.name.as_str() {
95
+ "List" => inner(Holds::List),
96
+ "Option" => inner(Holds::Some_),
97
+ n if isActor(n) => Some(Holds::One),
98
+ _ => None,
99
+ }
100
+ };
101
+ let hasMethod = |items: &[Item], ty: &str, name: &str| {
102
+ items.iter().any(|i| matches!(i, Item::Fn(f) if f.name == name && f.has_self && f.type_param.as_deref() == Some(ty)))
103
+ };
104
+
105
+ let mut errors: Vec<Diagnostic> = Vec::new();
106
+ let mut made: Vec<Item> = Vec::new();
107
+ let mut renames: Vec<String> = Vec::new();
108
+ for item in &source.items {
109
+ let Item::Enum(e) = item else { continue };
110
+ let at = |line: usize, column: usize, msg: String| Diagnostic::new(DiagKind::Type, e.file.clone(), line, column, msg);
111
+ let here = |msg: String| at(e.line, e.column, msg);
112
+ let name = &e.name;
113
+ let attrs: Vec<(usize, &Expr)> = e
114
+ .variants
115
+ .iter()
116
+ .flat_map(|v| v.field_steps_when.iter().enumerate().filter_map(|(i, c)| c.as_ref().map(|c| (i, c))))
117
+ .collect();
118
+ let attrAt = |c: &Expr, msg: String| at(c.span.startLine.max(e.line), if c.span.startLine == 0 { e.column } else { c.span.startColumn }, msg);
119
+ if !lists(e, STEPS_TRAIT) {
120
+ for (i, c) in &attrs {
121
+ let field = e.variants.iter().find_map(|v| v.field_names.get(*i)).cloned().unwrap_or_default();
122
+ errors.push(attrAt(
123
+ c,
124
+ format!("`@stepsWhen` on `{name}.{field}`: `{name}` doesn't list `Steps`, which steps its actor fields (`struct {name}[.., Steps](..)`)"),
125
+ ));
126
+ }
127
+ continue;
128
+ }
129
+ if !e.isStruct() {
130
+ errors.push(here(format!("`{name}` lists `Steps`, which steps a struct's actor fields, but it is an enum")));
131
+ continue;
132
+ }
133
+ let traits = &traitsOf[name];
134
+ let actor = traits.contains(ACTOR);
135
+ if !actor && !traits.contains(SCREEN) {
136
+ errors.push(here(format!(
137
+ "`{name}` lists `Steps` but is neither a `Screen` nor an `Actor`: `Steps` derives a screen's `stepped` or steps an actor's fields after its `step`"
138
+ )));
139
+ continue;
140
+ }
141
+ let v = &e.variants[0];
142
+ let fields: Vec<(String, Holds, Option<&Expr>)> = v
143
+ .field_names
144
+ .iter()
145
+ .zip(&v.fields)
146
+ .enumerate()
147
+ .filter_map(|(i, (n, t))| holds(t).map(|h| (n.clone(), h, v.field_steps_when.get(i).and_then(|c| c.as_ref()))))
148
+ .collect();
149
+ for (i, c) in &attrs {
150
+ if holds(&v.fields[*i]).is_none() {
151
+ errors.push(attrAt(
152
+ c,
153
+ format!(
154
+ "`@stepsWhen` on `{name}.{}`, a `{}`: only a field holding actors is stepped (an `Actor`, a `List` of actors or an `Option` of one)",
155
+ v.field_names[*i],
156
+ typeText(&v.fields[*i])
157
+ ),
158
+ ));
159
+ }
160
+ }
161
+ if fields.is_empty() {
162
+ errors.push(here(format!(
163
+ "`{name}` lists `Steps` but holds no actors: no field is an `Actor`, a `List` of actors or an `Option` of one"
164
+ )));
165
+ continue;
166
+ }
167
+ let ownStepped = !actor && hasMethod(&source.items, name, "stepped");
168
+ if ownStepped {
169
+ if let Some((i, c)) = attrs.first() {
170
+ errors.push(attrAt(
171
+ c,
172
+ format!(
173
+ "`@stepsWhen` on `{name}.{}` does nothing: `{name}` writes its own `stepped`, which wins over the derived one (leave out the `stepped` or the attribute)",
174
+ v.field_names[*i]
175
+ ),
176
+ ));
177
+ }
178
+ continue;
179
+ }
180
+ let gens = if e.generics.is_empty() {
181
+ String::new()
182
+ } else {
183
+ format!("<{}>", e.generics.iter().map(|g| g.name.clone()).collect::<Vec<_>>().join(", "))
184
+ };
185
+ let ty = format!("{name}{gens}");
186
+ let mut conds: Vec<Expr> = Vec::new();
187
+ let args: Vec<String> = fields
188
+ .iter()
189
+ .map(|(f, h, c)| {
190
+ let stepped = match h {
191
+ Holds::One => format!("self.{f}.step(dt)"),
192
+ Holds::List => format!("Views.stepAll(self.{f}, dt)"),
193
+ Holds::Some_ => format!("Views.stepSome(self.{f}, dt)"),
194
+ };
195
+ match c {
196
+ Some(c) => {
197
+ conds.push((*c).clone());
198
+ format!("{f}: if {COND}{} then {stepped} else self.{f}", conds.len() - 1)
199
+ }
200
+ None => format!("{f}: {stepped}"),
201
+ }
202
+ })
203
+ .collect();
204
+ let body = format!("{name}(..self, {})", args.join(", "));
205
+ let text = if !actor {
206
+ format!("struct {ty} =\n fun stepped(self, dt: Float) -> {ty} = {body}\n")
207
+ } else if hasMethod(&source.items, name, "step") {
208
+ renames.push(name.clone());
209
+ format!(
210
+ "struct {ty} =\n fun step(self, dt: Float) -> {ty} = self.{own}(dt).{fs}(dt)\n\n fun {fs}(self, dt: Float) -> {ty} = {body}\n",
211
+ own = "stepOwnDerived",
212
+ fs = "stepFieldsDerived"
213
+ )
214
+ } else {
215
+ format!("struct {ty} =\n fun step(self, dt: Float) -> {ty} = {body}\n")
216
+ };
217
+ for it in parseItems(&text, &e.file) {
218
+ let Item::Fn(mut f) = it else { continue };
219
+ if f.type_param.as_deref() != Some(name.as_str()) {
220
+ continue;
221
+ }
222
+ f.name = fixName(&f.name);
223
+ mapExprs(&mut f.body, &mut |x| {
224
+ match &mut x.kind {
225
+ ExprKind::Var(n) => {
226
+ if let Some(k) = n.strip_prefix(COND).and_then(|k| k.parse::<usize>().ok()) {
227
+ *x = conds[k].clone();
228
+ }
229
+ }
230
+ ExprKind::Attribute(a) => {
231
+ if let AttrKind::Method(c) = &mut a.attr {
232
+ c.name = fixName(&c.name);
233
+ }
234
+ }
235
+ _ => {}
236
+ }
237
+ });
238
+ made.push(Item::Fn(f));
239
+ }
240
+ }
241
+ for item in &mut source.items {
242
+ match item {
243
+ Item::Fn(f) if f.name == "step" && f.has_self && f.type_param.as_ref().is_some_and(|t| renames.contains(t)) => {
244
+ f.name = OWN_STEP.to_string();
245
+ }
246
+ Item::Enum(e) => {
247
+ for v in &mut e.variants {
248
+ v.field_steps_when.clear();
249
+ }
250
+ }
251
+ _ => {}
252
+ }
253
+ }
254
+ source.items.extend(made);
255
+ errors
256
+ }
257
+
258
+ /// The generated text spells `step$own` and `step$fields` as identifiers the grammar takes.
259
+ fn fixName(n: &str) -> String {
260
+ match n {
261
+ "stepOwnDerived" => OWN_STEP.to_string(),
262
+ "stepFieldsDerived" => FIELDS_STEP.to_string(),
263
+ _ => n.to_string(),
264
+ }
265
+ }
266
+
267
+ fn lists(e: &Enum, name: &str) -> bool {
268
+ e.implements.iter().any(|t| t.name == name)
269
+ }
compiler/core/src/tests_lower.rs CHANGED
@@ -48,6 +48,7 @@ fn reportStruct() -> crate::ast::Item {
48
48
  field_names: vec![REPORT_FIELD.to_string()],
49
49
  mut_fields: vec![true],
50
50
  field_defaults: Vec::new(),
51
+ field_steps_when: Vec::new(),
51
52
  }],
52
53
  kind: crate::ast::TypeKind::Struct(crate::ast::StructInfo::default()),
53
54
  })
compiler/core/tests/core/formatter_test.rs CHANGED
@@ -380,3 +380,13 @@ fn blocksAndListLinesFormat() {
380
380
  assert_eq!(once, expected);
381
381
  assertFormatsUnchanged(expected);
382
382
  }
383
+
384
+ /// A field's attribute stays before it, one space between.
385
+ #[test]
386
+ fn aFieldAttributeFormats() {
387
+ let input = "struct P[Screen, Steps](over: Bool, @stepsWhen( !self.over ) mines: List<Mine>, rings: List<Ring>) =\n fun name(self) -> Str = \"p\"\n";
388
+ let once = formatSource(input).expect("first pass");
389
+ let expected = "struct P[Screen, Steps](over: Bool, @stepsWhen(!self.over) mines: List<Mine>, rings: List<Ring>) =\n fun name(self) -> Str = \"p\"\n";
390
+ assert_eq!(once, expected);
391
+ assertFormatsUnchanged(expected);
392
+ }
compiler/tooling/tree-sitter-plum/grammar.js CHANGED
@@ -262,9 +262,11 @@ module.exports = grammar({
262
262
  ),
263
263
 
264
264
  // A struct field: `x: Float`, or with a default a construction may leave it out for:
265
- // `size: Float = 20.0`.
265
+ // `size: Float = 20.0`. An attribute may come first: `@stepsWhen(!self.over) mines:
266
+ // List<Mine>` (a `[Steps]` type's field stepped only while the condition holds).
266
267
  ctor_field: ($) =>
267
268
  seq(
269
+ optional(field("attribute", $.field_attribute)),
268
270
  optional(field("mutKw", "mut")),
269
271
  field("name", $.var_identifier),
270
272
  ":",
@@ -272,6 +274,10 @@ module.exports = grammar({
272
274
  optional(seq("=", field("default", $.expression))),
273
275
  ),
274
276
 
277
+ // `@stepsWhen(!self.over)` before a struct field: a name and one expression.
278
+ field_attribute: ($) =>
279
+ seq("@", field("name", $.var_identifier), "(", field("argument", $.expression), ")"),
280
+
275
281
  fn: ($) =>
276
282
  prec.left(
277
283
  seq(
compiler/tooling/tree-sitter-plum/queries/plum/format.scm CHANGED
@@ -421,6 +421,9 @@
421
421
  ; `mut x: T` fields and `export fun`.
422
422
  "mut" @append_space
423
423
 
424
+ ; `@stepsWhen(!self.over) mines: List<Mine>`: a field's attribute, then the field.
425
+ (field_attribute ")" @append_space)
426
+
424
427
  (fn "export" @append_space)
425
428
 
426
429
  ; ============================================================
compiler/tooling/tree-sitter-plum/queries/plum/highlights.scm CHANGED
@@ -144,6 +144,10 @@
144
144
  "@" @function.builtin
145
145
  name: (var_identifier) @function.builtin)
146
146
 
147
+ (field_attribute
148
+ "@" @attribute
149
+ name: (var_identifier) @attribute)
150
+
147
151
  "crash" @keyword.control.exception
148
152
 
149
153
  "match" @keyword
compiler/tooling/tree-sitter-plum/src/grammar.json CHANGED
Binary file
compiler/tooling/tree-sitter-plum/src/node-types.json CHANGED
Binary file
compiler/tooling/tree-sitter-plum/src/parser.c CHANGED
Binary file
compiler/tooling/tree-sitter-plum/test/corpus/field_attribute.txt ADDED
@@ -0,0 +1,36 @@
1
+ ================================================================================
2
+ field attribute before a struct field
3
+ ================================================================================
4
+
5
+ struct P[Screen, Steps](over: Bool, @stepsWhen(!self.over) mines: List<Mine>)
6
+
7
+ --------------------------------------------------------------------------------
8
+
9
+ (source
10
+ (struct
11
+ name: (type_identifier)
12
+ implements: (implements
13
+ (type
14
+ (type_identifier))
15
+ (type
16
+ (type_identifier)))
17
+ field: (enum_named_field
18
+ name: (var_identifier)
19
+ type: (type
20
+ (type_identifier)))
21
+ field: (enum_named_field
22
+ attribute: (field_attribute
23
+ name: (var_identifier)
24
+ argument: (expression
25
+ (not_operator
26
+ argument: (expression
27
+ (primary_expression
28
+ (attribute
29
+ object: (primary_expression
30
+ (self))
31
+ member: (fn_identifier)))))))
32
+ name: (var_identifier)
33
+ type: (type
34
+ (type_identifier)
35
+ generics: (type
36
+ (type_identifier))))))
docs/backlog.md CHANGED
@@ -12,7 +12,7 @@ The retained scene tree was replaced by master's screen view in functional form:
12
12
  - **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.
13
13
  - **Master's other games** (`clockwork`, `menu`) are not ported.
14
14
  - **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).
15
- - **Stepping without the screen naming its actors**: the game cannot step an actor found in a view, as the screen holding it is a value; each screen maps its own fields in `stepped`. A lens per field, or a view walk that rebuilds the screen, would let std do it; not designed.
15
+ - **Stepping without the screen naming its actors**: done at compile time on 2026-11-16: a screen or an actor that lists `Steps` (std/game/View) has its fields holding actors stepped by a derived `stepped` (or after its own `step`), one field paused by `@stepsWhen(cond)` (`docs/game.md`, "Stepping"). Still by hand: a `List<View>` field (`Views.stepIn`).
16
16
 
17
17
  ## Decided, not built
18
18
 
docs/game.md CHANGED
@@ -47,7 +47,7 @@ struct Ball[Actor](x: Float, y: Float, vx: Float) =
47
47
 
48
48
  fun step(self, dt: Float) -> Ball = Ball(..self, x: self.x + self.vx * dt)
49
49
 
50
- struct TapScreen[ScreenSlice<TapAction>](taps: Int, ball: Ball) =
50
+ struct TapScreen[ScreenSlice<TapAction>, Steps](taps: Int, ball: Ball) =
51
51
  fun start() -> TapScreen =
52
52
  TapScreen(taps: 0, ball: Ball(x: 20.0, y: 150.0, vx: 0.0))
53
53
 
@@ -61,8 +61,6 @@ struct TapScreen[ScreenSlice<TapAction>](taps: Int, ball: Ball) =
61
61
  Label(x: 20.0, y: 20.0, text: "Taps: {self.taps}", size: 24.0)
62
62
  ]
63
63
 
64
- fun stepped(self, dt: Float) -> TapScreen = TapScreen(..self, ball: self.ball.step(dt))
65
-
66
64
  fun onKey(self, e: InputEvent) -> Option<TapAction> = match e
67
65
  KeyDown(k) => if k == Key.Escape then Some(Quit) else None
68
66
  _ => None
@@ -162,31 +160,46 @@ struct Mine[Actor](at: Place, vx: Float, vy: Float, clock: Float, tex: Texture)
162
160
  Mine(..moved, at: moved.at.rotateBy(2.0 * dt))
163
161
  ```
164
162
 
165
- **Stepping.** Each tick the shown screen gets, between `held` and its tick action, the game has it step its actors: it calls the screen's `stepped(dt)` and keeps the screen it returns, unless the screen's `steps()` is false. 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 says where its actors are, in one line that maps its fields (`Views.stepAll` steps each actor of a list, `Views.stepIn` each `Actor` of a `List<View>` and each one a `Group` or an `Overlay` in it holds, the others as they are):
163
+ **Stepping.** Each tick the shown screen gets, between `held` and its tick action, the game has it step its actors: it calls the screen's `stepped(dt)` and keeps the screen it returns, unless the screen's `steps()` is false. 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. A screen that lists `Steps` (std/game/View) has its `stepped` derived by the compiler: each field that is an `Actor`, a `List` of actors (of one type, or of a trait type that is an `Actor`) or an `Option` of one is stepped, and the other fields are as they are. `@stepsWhen(cond)` before a field steps it only while `cond`, read on `self`, holds. Orbit Runner's:
166
164
 
167
165
  ```plum
166
+ struct PlayingScreen[ScreenSlice<PlayAction>, Steps](
167
+ rng: Random, assets: Assets, score: Int, best: Int, lives: Int, over: Bool, clock: Float,
168
+ @stepsWhen(!self.over) ship: Ship, @stepsWhen(!self.over) orbs: List<Orb>, @stepsWhen(!self.over) mines: List<Mine>, rings: List<Ring>) =
168
- fun steps(self) -> Bool = !self.over
169
+ fun name(self) -> Str = "play"
170
+ ```
171
+
172
+ is stepped as if it had written
169
173
 
174
+ ```plum
170
175
  fun stepped(self, dt: Float) -> PlayingScreen =
176
+ PlayingScreen(..self,
177
+ ship: if !self.over then self.ship.step(dt) else self.ship,
178
+ orbs: if !self.over then Views.stepAll(self.orbs, dt) else self.orbs,
171
- PlayingScreen(..self, mines: Views.stepAll(self.mines, dt), orbs: Views.stepAll(self.orbs, dt), ship: self.ship.step(dt), rings: Views.stepAll(self.rings, dt))
179
+ mines: if !self.over then Views.stepAll(self.mines, dt) else self.mines,
180
+ rings: Views.stepAll(self.rings, dt))
172
181
  ```
173
182
 
174
- That is the only line a game writes for stepping, one per screen that holds actors; the default returns the screen as it is. A plain screen (no slice) is stepped the same way; an `OnDemand` screen asleep steps nothing, as it gets no tick; a replay, a rewind and the kit's `tick` go through the same tick. An actor steps what it holds itself, in its own `step` (`Views.stepIn` doesn't look inside an actor, nor make its view); a `Group` or an `Overlay` is made again with its actors stepped; any other view of your own that holds actors is passed over, so make it an `Actor` that steps them. An actor the screen leaves out of `stepped` is not stepped, whether it is in the view or not, and one stepped there moves whether it is visible or not. So the tick action only runs the rules on what has moved:
183
+ and that is what is compiled: the derive is written out before checking, the same static construction (`Views.stepAll` for a list, `Views.stepSome` for an `Option`), not a walk at run time, so it costs what the hand-written one did (`benchmarks/screen_views`: Orbit Runner's update 12.8-13.3 ms before and after, the 10,000 actors of `scale update spread` 19.0-19.9 ms before, 19.2 ms after). A screen that writes its own `stepped` keeps it, and `steps()` still pauses it as a whole; a field `@stepsWhen` pauses one field, so a screen that derives its stepping has no need of `steps()`. A screen holding no actors lists no `Steps` (the default `stepped` returns the screen as it is). A plain screen (no slice) is stepped the same way; an `OnDemand` screen asleep steps nothing, as it gets no tick; a replay, a rewind and the kit's `tick` go through the same tick.
184
+
185
+ An actor that lists `Steps` has its actor fields stepped after its own `step`: the compiler renames the `step` it writes `step$own` and makes `step` that and then the fields' stepping, whose conditions read the actor after its own step. So a container actor writes only what is special about itself, or no `step` at all when it is only what it holds. An actor that doesn't list `Steps` steps what it holds itself, in its own `step`. `Views.stepIn` steps each `Actor` of a `List<View>` and each one a `Group` or an `Overlay` in it holds, the others as they are; it doesn't look inside an actor, nor make its view; any other view of your own that holds actors is passed over, so make it an `Actor` that steps them. A `List<View>` field is not stepped by `Steps` (it holds views, not actors): a screen holding one writes `stepped` with `Views.stepIn`. An actor left out of the stepping is not stepped, whether it is in the view or not, and one stepped moves whether it is visible or not. So the tick action only runs the rules on what has moved:
175
186
 
176
187
  ```plum
177
188
  fun advance(self, dt: Float) -> Next<PlayingScreen, PlayAction> =
178
- rings := if self.over then Views.stepAll(self.rings, dt) else self.rings
179
- moved := PlayingScreen(..self, clock: self.clock + dt, rings: rings.filter(|r| !r.done()))
189
+ moved := PlayingScreen(..self, clock: self.clock + dt, rings: self.rings.filter(|r| !r.done()))
180
190
  if self.over then Next(state: moved) else moved.rules()
181
191
  ```
182
192
 
183
- Once Orbit Runner's run is over the screen steps nothing, so the mines and orbs stand still under the game over panel, while the stars, which read the screen's clock, keep twinkling, and the ship is left out of the view. What should move while the rest is held, the reducer still steps by hand: here the ripple of the last hit grows on under the panel.
193
+ Once Orbit Runner's run is over its ship, orbs and mines stand still under the game over panel, while the stars, which read the screen's clock, keep twinkling, and the ship is left out of the view; the rings, with no condition, step on, so the ripple of the last hit grows on under the panel.
194
+
195
+ `Steps` is an error on an enum, on a struct that is neither a `Screen` nor an `Actor`, and on one with no field holding actors; `@stepsWhen` is an error on a field that holds no actors, on a type that doesn't list `Steps`, and on a screen that writes its own `stepped` (it would do nothing).
184
196
 
185
197
  What else a view is, it says with a small trait:
186
198
 
187
199
  | Trait | What it says |
188
200
  |---|---|
189
201
  | `Actor` (`std/game/View`) | `step(self, dt) -> Self`: its next version `dt` seconds on, which the screen's `stepped` keeps |
202
+ | `Steps` (`std/game/View`) | nothing to write: on a screen the compiler derives `stepped`, on an actor it steps the actor's fields after its `step` (above); `@stepsWhen(cond)` on a field |
190
203
  | `Sized` (`std/game/Sized`) | `bounds(self) -> Aabb`, the box it covers in its own coordinates. A view with bounds can be hit; one without cannot. `hit(self, p) -> Bool` is inside the bounds, edges included, unless the view says otherwise for an exact shape (`Circle` is hit inside its circle; a balloon on its body, its knot and its string). Culling goes by the bounds too |
191
204
  | `Touch` (`std/game/Touch`) | `touch(self) -> Touchable`: whether it takes presses. `Enabled`: it is hit where it is (when it is `Sized`) and what is under it is; `Disabled`: neither it nor anything under it is hit; `ChildrenOnly`: what is under it is, it is not. A view that says nothing is `ChildrenOnly` |
192
205
 
@@ -463,7 +476,7 @@ The engine has master's shape at e91c40ce (`View` and `Actor`, `Screen` with its
463
476
  | Master | Here | Why |
464
477
  |---|---|---|
465
478
  | `trait Actor[View]` with `step(&self, dt)` | `step(self, dt) -> Self` | a value is not changed in place: `step` returns the actor's next version |
466
- | the game walks the view and the hud and steps each `Actor` it finds; an actor steps what it holds, and a view that is not an actor is looked inside only when it says `holdsActors()` (`Group` and `Overlay` do), the kit stopping a test on one that holds actors and says not (`unsteppedIn`) | the game calls the screen's `stepped(dt) -> Self` (default: the screen as it is), which maps the fields that hold actors (`Views.stepAll`, `Views.stepIn`); `steps()` pauses it as on master. `Views.stepIn` steps an actor without looking inside it and makes a `Group` or an `Overlay` again with its actors stepped; any other view is as it is | an actor found in a view can't be put back into the field of the value that holds it, so the screen says where its actors are, one line per screen. Making a view again is only possible for a kind std knows (`Group(..g, children: ..)`), so `holdsActors()` is std's two containers, not a trait method, and a kind of your own that holds actors is an `Actor` that steps them; the kit's `unsteppedIn` check has nothing to find, since nothing is stepped behind the screen's back. The walk makes no view to look under an actor, so `benchmarks/screen_views/scale.plum`'s `update view` makes 10,000 fewer one-`Sprite` lists a tick than master's |
479
+ | the game walks the view and the hud and steps each `Actor` it finds; an actor steps what it holds, and a view that is not an actor is looked inside only when it says `holdsActors()` (`Group` and `Overlay` do), the kit stopping a test on one that holds actors and says not (`unsteppedIn`) | the game calls the screen's `stepped(dt) -> Self` (default: the screen as it is), which maps the fields that hold actors: derived by the compiler for a screen that lists `Steps`, a field paused by `@stepsWhen(cond)`, or written by hand (`Views.stepAll`, `Views.stepIn`); `steps()` pauses it as on master. An actor that lists `Steps` has its actor fields stepped after its own `step`. `Views.stepIn` steps an actor without looking inside it and makes a `Group` or an `Overlay` again with its actors stepped; any other view is as it is | an actor found in a view can't be put back into the field of the value that holds it, so the screen says where its actors are, one line per screen. Making a view again is only possible for a kind std knows (`Group(..g, children: ..)`), so `holdsActors()` is std's two containers, not a trait method, and a kind of your own that holds actors is an `Actor` that steps them; the kit's `unsteppedIn` check has nothing to find, since nothing is stepped behind the screen's back. The walk makes no view to look under an actor, so `benchmarks/screen_views/scale.plum`'s `update view` makes 10,000 fewer one-`Sprite` lists a tick than master's |
467
480
  | `trait Slice<A>[Screen]` | `trait ScreenSlice<A>[Screen]` | `Slice` is std's growable array here, and a trait can't share a type's name |
468
481
  | `fun reduce(&self, a: A)`, `fun dispatch(&self, a: A)` | `fun reduce(self, a: A) -> Self`, and `fun act(self, a: A) -> Next<Self, A>` returning the actions that follow (`then`) with the next screen; no `dispatch` | the reducer returns the next screen, and what follows from an action is part of what it returns, not a call that queues it |
469
482
  | `onKey(..) -> A?` and the other mappings | `-> Option<A>` | no `T?` in this dialect |
docs/language.md CHANGED
@@ -233,6 +233,13 @@ primitive Demo[App] =
233
233
  b.x = 9.0 # a.x is still 1.0
234
234
  ```
235
235
 
236
+ **Field attributes and derived methods:** a field may start with an attribute, `@name(expr)`. The one there is is `@stepsWhen(cond)`, for std/game's `Steps` trait: a struct that lists `Steps` and is a `Screen` gets a `stepped(self, dt)` written out by the compiler before checking, which steps each field holding actors (an `Actor`, a `List` of actors or an `Option` of one, the others as they are); an `Actor` that lists it has those fields stepped after its own `step`. `@stepsWhen(cond)` steps its field only while `cond`, an expression on `self`, holds. What is derived is an ordinary method, the same static construction one would write (`Screen(..self, ship: self.ship.step(dt), ..)`), so it costs nothing at run time; a screen that writes its own `stepped` keeps it. Any other attribute name is an error, and so is `@stepsWhen` on a field holding no actors or of a type that doesn't list `Steps`. See docs/game.md, "Stepping".
237
+
238
+ ```plum
239
+ struct PlayingScreen[ScreenSlice<PlayAction>, Steps](over: Bool, @stepsWhen(!self.over) ship: Ship, rings: List<Ring>) =
240
+ fun name(self) -> Str = "play"
241
+ ```
242
+
236
243
  **Setting up extra fields:** the header lists what callers pass. Anything else is set in `init`, which runs on construction.
237
244
 
238
245
  ```plum
@@ -896,6 +903,7 @@ primitive Demo[App] =
896
903
  | `@memStoreF32(addr, v)` | stores the `Float` `v` at `addr` as a 32-bit float. |
897
904
  | `@memLoadF32(addr)` | the 32-bit float at `addr` as a `Float`. |
898
905
  | `@native` | not a call: the whole body of a std function the compiler supplies. See [`@native`](#native). |
906
+ | `@stepsWhen(cond)` | not a call: an attribute before a struct field. See [Structs](#structs), "Field attributes and derived methods". |
899
907
 
900
908
  ### Reference identity
901
909
 
docs/plans/2026-11-13-std-game-review.md CHANGED
@@ -28,5 +28,5 @@ Events stay the only source of truth; std keeps held state as a pure fold of the
28
28
  - Per tick, not per actor: the 10,000-actor benchmark is unaffected. Pairs with the `Key` enum.
29
29
 
30
30
  ## Chosen (user 2026-11-16)
31
- - Building: R1 items 1+2 (done cfbc7a67), R2 item 3 + input addendum, R2b derived `stepped` (user: "Yes derived stepped is good"): a `[Steps]` trait on a screen or actor makes the compiler generate `stepped`/child stepping from Actor / List<Actor> / Option<Actor> fields at compile time; per-field pause by an attribute (e.g. `@stepsWhen(!self.over)`); a hand-written `stepped` still wins. Then R3 items 10-12.
31
+ - Building: R1 items 1+2 (done cfbc7a67), R2 item 3 + input addendum, R2b derived `stepped` (user: "Yes derived stepped is good"): a `[Steps]` trait on a screen or actor makes the compiler generate `stepped`/child stepping from Actor / List<Actor> / Option<Actor> fields at compile time; per-field pause by an attribute (e.g. `@stepsWhen(!self.over)`); a hand-written `stepped` still wins (done on `sl/steps`: `trait Steps` in std/game/View, `@stepsWhen(cond)` before a field, core/steps_derive.rs). Then R3 items 10-12.
32
32
  - Waiting: Key enum, one time model, Setup value, typed navigation.
docs/std.md CHANGED
@@ -270,7 +270,7 @@ Tests live in the `tests/` mirror of the code (std's in `tests/std/...`), as the
270
270
 
271
271
  ## Game screens and slices
272
272
 
273
- A game (`std/game/Game`) is a list of screens. A screen (`std/game/Screen`) has a name and a `view(self) -> List<View>`, what the frame shows, made again from its fields every frame (`std/game/View`: stateless views, and actors, `Actor[View]`, with `step(self, dt) -> Self`, which the game steps each tick through the screen's `stepped(dt)`), and may have a `hud(window)` drawn over it one unit a pixel and a `camera(base)` (`Viewport.lookAt`); a screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`): its fields are its state, `A` its actions, `reduce(self, a) -> Self` its reducer (pure, with no `Io`, so the same actions from the same state give the same state) and `act(self, a) -> Next<Self, A>` the reducer with what follows: the actions that follow and the commands for the game (`std/game/Cmd`: a sound, `GoTo(name: "play")`), done after the tick. std maps each tick's input (`std/game/Input`: its events, and what is held after them, `Held`, their fold) to the screen's actions (`onKey`, `onPress`, `onPointer`, `held`, `tick`; a press on an item that says what it means, a `Presses<A>` such as a `Button` from `std/game/Button`, is that action by default) and keeps the screen each `reduce` returns. All of it is in [the game engine](game.md).
273
+ A game (`std/game/Game`) is a list of screens. A screen (`std/game/Screen`) has a name and a `view(self) -> List<View>`, what the frame shows, made again from its fields every frame (`std/game/View`: stateless views, and actors, `Actor[View]`, with `step(self, dt) -> Self`, which the game steps each tick through the screen's `stepped(dt)`, derived for a screen that lists `Steps`), and may have a `hud(window)` drawn over it one unit a pixel and a `camera(base)` (`Viewport.lookAt`); a screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`): its fields are its state, `A` its actions, `reduce(self, a) -> Self` its reducer (pure, with no `Io`, so the same actions from the same state give the same state) and `act(self, a) -> Next<Self, A>` the reducer with what follows: the actions that follow and the commands for the game (`std/game/Cmd`: a sound, `GoTo(name: "play")`), done after the tick. std maps each tick's input (`std/game/Input`: its events, and what is held after them, `Held`, their fold) to the screen's actions (`onKey`, `onPress`, `onPointer`, `held`, `tick`; a press on an item that says what it means, a `Presses<A>` such as a `Button` from `std/game/Button`, is that action by default) and keeps the screen each `reduce` returns. All of it is in [the game engine](game.md).
274
274
 
275
275
  ```plum
276
276
  import std/Int
examples/games/balloonpop/screens/PlaygroundScreen.plum CHANGED
@@ -38,7 +38,7 @@ enum PopAction =
38
38
  TakeBack => "TakeBack"
39
39
  Tick(dt) => "Tick({dt})"
40
40
 
41
- struct PlaygroundScreen[ScreenSlice<PopAction>](
41
+ struct PlaygroundScreen[ScreenSlice<PopAction>, Steps](
42
42
  rng: Random, assets: Assets, pops: Int, partyAt: Float, clock: Float, balloons: List<Balloon>) =
43
43
  const Count = 6
44
44
  const PartyEvery = 10
@@ -74,8 +74,6 @@ struct PlaygroundScreen[ScreenSlice<PopAction>](
74
74
  Label(x: 80.0, y: 20.0, text: "{self.pops}", size: 44.0, color: Color.rgb(0.15, 0.15, 0.3))
75
75
  ]
76
76
 
77
- fun stepped(self, dt: Float) -> PlaygroundScreen = PlaygroundScreen(..self, balloons: Views.stepAll(self.balloons, dt))
78
-
79
77
  fun onKey(self, e: InputEvent) -> Option<PopAction> = match e
80
78
  KeyDown(k) => if k == Key.KeyZ || k == Key.Backspace then Some(TakeBack) else None
81
79
  _ => None
examples/games/clicks.plum CHANGED
@@ -33,7 +33,7 @@ struct Ball[Actor](x: Float, y: Float, vx: Float) =
33
33
 
34
34
  fun step(self, dt: Float) -> Ball = Ball(..self, x: self.x + self.vx * dt)
35
35
 
36
- struct TapScreen[ScreenSlice<TapAction>](taps: Int, ball: Ball) =
36
+ struct TapScreen[ScreenSlice<TapAction>, Steps](taps: Int, ball: Ball) =
37
37
  fun start() -> TapScreen =
38
38
  TapScreen(taps: 0, ball: Ball(x: 20.0, y: 150.0, vx: 0.0))
39
39
 
@@ -47,8 +47,6 @@ struct TapScreen[ScreenSlice<TapAction>](taps: Int, ball: Ball) =
47
47
  Label(x: 20.0, y: 20.0, text: "Taps: {self.taps}", size: 24.0)
48
48
  ]
49
49
 
50
- fun stepped(self, dt: Float) -> TapScreen = TapScreen(..self, ball: self.ball.step(dt))
51
-
52
50
  fun onKey(self, e: InputEvent) -> Option<TapAction> = match e
53
51
  KeyDown(k) => if k == Key.Escape then Some(Quit) else None
54
52
  _ => None
examples/games/orbitrunner/screens/PlayingScreen.plum CHANGED
@@ -46,9 +46,9 @@ enum PlayAction =
46
46
  Hit => "Hit"
47
47
  StartOver => "StartOver"
48
48
 
49
- struct PlayingScreen[ScreenSlice<PlayAction>](
49
+ struct PlayingScreen[ScreenSlice<PlayAction>, Steps](
50
50
  rng: Random, assets: Assets, score: Int, best: Int, lives: Int, over: Bool, clock: Float,
51
- ship: Ship, orbs: List<Orb>, mines: List<Mine>, rings: List<Ring>) =
51
+ @stepsWhen(!self.over) ship: Ship, @stepsWhen(!self.over) orbs: List<Orb>, @stepsWhen(!self.over) mines: List<Mine>, rings: List<Ring>) =
52
52
  const OrbCount = 3
53
53
  const StartLives = 3
54
54
 
@@ -66,11 +66,6 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
66
66
 
67
67
  fun background(self) -> Color = Color.rgb(0.04, 0.05, 0.1)
68
68
 
69
- fun steps(self) -> Bool = !self.over
70
-
71
- fun stepped(self, dt: Float) -> PlayingScreen =
72
- PlayingScreen(..self, mines: Views.stepAll(self.mines, dt), orbs: Views.stepAll(self.orbs, dt), ship: self.ship.step(dt), rings: Views.stepAll(self.rings, dt))
73
-
74
69
  fun view(self) -> List<View> = [
75
70
  Box(w: Arena.W, h: Arena.H, color: Color.rgb(0.07, 0.08, 0.16))
76
71
  ..Range.until(0, Star.Count).map(|i| Star(index: i, clock: self.clock))
@@ -138,8 +133,7 @@ struct PlayingScreen[ScreenSlice<PlayAction>](
138
133
  _ => Next(state: self)
139
134
 
140
135
  fun advance(self, dt: Float) -> Next<PlayingScreen, PlayAction> =
141
- rings := if self.over then Views.stepAll(self.rings, dt) else self.rings
142
- moved := PlayingScreen(..self, clock: self.clock + dt, rings: rings.filter(|r| !r.done()))
136
+ moved := PlayingScreen(..self, clock: self.clock + dt, rings: self.rings.filter(|r| !r.done()))
143
137
  if self.over then Next(state: moved) else moved.rules()
144
138
 
145
139
  fun rules(self) -> Next<PlayingScreen, PlayAction> =
std/game/Screen.plum CHANGED
@@ -32,12 +32,19 @@ import std/game/ScreenSlice
32
32
  # `Actor`s (std/game/View), unless it says `steps()` is false: it calls the screen's
33
33
  # `stepped(dt)`, which returns the screen with each actor it holds stepped. The game can't
34
34
  # step an actor where it finds it in the view, since the screen holding it is a value, so
35
+ # its own fields are stepped. A screen that lists `Steps` (std/game/View) has `stepped`
35
- # the screen maps its own fields (`Views.stepAll` for a list of actors):
36
+ # derived by the compiler, each field holding actors stepped (`@stepsWhen(cond)` before a
37
+ # field steps it only while `cond` holds):
38
+ #
39
+ # struct PlayingScreen[ScreenSlice<PlayAction>, Steps](over: Bool, @stepsWhen(!self.over) ship: Ship, mines: List<Mine>)
40
+ #
41
+ # is stepped as if it wrote
36
42
  #
37
43
  # fun stepped(self, dt: Float) -> PlayingScreen =
38
- # PlayingScreen(..self, ship: self.ship.step(dt), mines: Views.stepAll(self.mines, dt))
44
+ # PlayingScreen(..self, ship: if !self.over then self.ship.step(dt) else self.ship, mines: Views.stepAll(self.mines, dt))
39
45
  #
46
+ # which a screen may write itself (it wins over the derive). A screen holding no actors
40
- # A screen holding no actors leaves it out (the default returns the screen as it is).
47
+ # leaves both out (the default returns the screen as it is).
41
48
  #
42
49
  # What sits over a view (a game over, a pause, a dialog) is not a screen: it is part of
43
50
  # the screen it sits on, an `Overlay` (std/game/Overlay) in its view, there while the
std/game/View.plum CHANGED
@@ -43,9 +43,9 @@ import std/game/Overlay
43
43
  # extends `View` with `step(self, dt) -> Self`, its next version `dt` seconds on. The game
44
44
  # steps the shown screen's actors each tick it gets, before its tick action is reduced
45
45
  # (std/game/Screen's `steps` and `stepped`): a screen is a value, so the game cannot step
46
- # an actor where it finds it in the view, and the screen's `stepped` puts each list of
46
+ # an actor where it finds it in the view, and the screen's `stepped`, derived when it lists
47
- # actors it holds through `Views.stepAll` (`ship: self.ship.step(dt)`, `mines:
47
+ # `Steps` (below), puts each list of actors it holds through `Views.stepAll` (`ship:
48
- # Views.stepAll(self.mines, dt)`).
48
+ # self.ship.step(dt)`, `mines: Views.stepAll(self.mines, dt)`).
49
49
  #
50
50
  # struct Walker[Actor](at: Place, speed: Float) =
51
51
  # fun place(self) -> Place = self.at
@@ -100,6 +100,19 @@ trait View =
100
100
  trait Actor[View] =
101
101
  fun step(self, dt: Float) -> Self
102
102
 
103
+ # A screen or an actor whose fields holding actors the compiler steps: each field that is
104
+ # an `Actor`, a `List` of actors or an `Option` of one, the others as they are, at compile
105
+ # time (the same static construction a hand-written `stepped` is). On a `Screen` it derives
106
+ # `stepped(dt)` (a screen that writes its own keeps it); on an `Actor` its fields are
107
+ # stepped after its own `step`, which then holds only what is special about it.
108
+ # `@stepsWhen(cond)` before a field steps it only while `cond` holds, read on `self`:
109
+ #
110
+ # struct PlayingScreen[ScreenSlice<PlayAction>, Steps](
111
+ # over: Bool, @stepsWhen(!self.over) ship: Ship, rings: List<Ring>)
112
+ #
113
+ # steps the rings each tick and the ship only while the run is on (docs/game.md, "Stepping").
114
+ trait Steps
115
+
103
116
  # One entry of a draw list: an item drawn, its transform (its own coordinates to the
104
117
  # world's) and its alpha.
105
118
  struct Drawn(actor: View, m: Affine, alpha: Float)
@@ -110,6 +123,12 @@ primitive Views =
110
123
  # actors it holds.
111
124
  fun stepAll<T: Actor>(xs: List<T>, dt: Float) -> List<T> = xs.map(|x| x.step(dt))
112
125
 
126
+ # The actor `x` holds stepped by `dt`, or None: what a `[Steps]` type does with an
127
+ # `Option` of an actor.
128
+ fun stepSome<T: Actor>(x: Option<T>, dt: Float) -> Option<T> = match x
129
+ Some(a) => Some(a.step(dt))
130
+ None => None
131
+
113
132
  # Each `Actor` of `items` stepped by `dt`, in order: an actor steps what it holds itself
114
133
  # (its own `step`), so its view is neither made nor looked inside. A `Group` or an
115
134
  # `Overlay` is made again with its children stepped the same way; any other view is as it
tests/port/game/screens.plum CHANGED
@@ -230,14 +230,13 @@ struct WalkScreen[ScreenSlice<WalkAct>](walker: Walker, seen: List<Float>, pause
230
230
  TakeBack => Next(state: self, cmds: [Undo])
231
231
  _ => Next(state: self.reduce(a))
232
232
 
233
- # A screen with no rules holding a walker: the game steps it all the same.
233
+ # A screen with no rules holding a walker: the game steps it all the same, through the
234
+ # `stepped` that `Steps` derives.
234
- struct StillScreen[Screen](walker: Walker) =
235
+ struct StillScreen[Screen, Steps](walker: Walker) =
235
236
  fun name(self) -> Str = "still"
236
237
 
237
238
  fun view(self) -> List<View> = [self.walker]
238
239
 
239
- fun stepped(self, dt: Float) -> StillScreen = StillScreen(walker: self.walker.step(dt))
240
-
241
240
  primitive ScreensTest[UnitTest] =
242
241
  # a press reaches onPress as the item it is on, through the view's groups and their turns, never under a Disabled one
243
242
  fun aPressReachesOnPressAsTheItemIt() =
tests/std/game/View.plum CHANGED
@@ -20,6 +20,7 @@ import std/game/Label
20
20
  import std/game/Circle
21
21
  import std/game/Overlay
22
22
  import std/game/View
23
+ import std/game/Screen
23
24
  import std/Test
24
25
 
25
26
  primitive ViewTest[UnitTest] =
@@ -128,6 +129,43 @@ primitive ViewTest[UnitTest] =
128
129
  assert b.min.x == 80.0 && b.max.x == 100.0 && b.min.y == 0.0 && b.max.y == 10.0
129
130
 
130
131
  # A view that logs where it is painted (the x of its origin) and at what alpha.
132
+
133
+ # a [Steps] screen's derived `stepped` steps each field holding actors, and leaves the others
134
+ fun aStepsScreenStepsItsActorFields() =
135
+ s := Stage(n: 7, one: Stepper(time: 0.0), many: [Stepper(time: 1.0), Stepper(time: 2.0)], maybe: Some(Stepper(time: 3.0)), nothing: None, anyOne: Stepper(time: 4.0), anyMany: [Stepper(time: 5.0)], loose: Stepper(time: 6.0)).stepped(0.5)
136
+ assert s.n == 7 && s.one.time == 0.5 && ViewHelpers.timeOf(s.loose) == 6.0
137
+ assert s.many.map(|x| x.time) == [1.5, 2.5]
138
+ assert s.maybe.map(|x| x.time) == Some(3.5) && s.nothing.isNone()
139
+ assert ViewHelpers.timeOf(s.anyOne) == 4.5
140
+ assert s.anyMany.map(|x| ViewHelpers.timeOf(x)) == [5.5]
141
+
142
+ # `@stepsWhen` steps a field only while its condition holds, the others always
143
+ fun stepsWhenPausesOneField() =
144
+ on := Paused(paused: false, walker: Stepper(time: 0.0), clocks: [Stepper(time: 0.0)])
145
+ off := Paused(..on, paused: true)
146
+ assert on.stepped(1.0).walker.time == 1.0 && on.stepped(1.0).clocks.map(|x| x.time) == [1.0]
147
+ assert off.stepped(1.0).walker.time == 0.0 && off.stepped(1.0).clocks.map(|x| x.time) == [1.0]
148
+
149
+ # a screen that writes its own `stepped` keeps it
150
+ fun aHandWrittenSteppedWins() =
151
+ assert Owned(one: Stepper(time: 0.0)).stepped(1.0).one.time == 2.0
152
+
153
+ # a [Steps] actor's fields are stepped after its own `step`, which sees them unstepped
154
+ fun aStepsActorStepsItsFieldsAfterItsOwnStep() =
155
+ n := Nest(time: 0.0, kids: [Stepper(time: 1.0)], held: false, inner: Stepper(time: 0.0)).step(0.5)
156
+ assert n.time == 0.5
157
+ assert n.kids.map(|x| x.time) == [1.5, 0.5]
158
+ assert n.inner.time == 0.0
159
+ again := n.step(0.5)
160
+ assert again.inner.time == 0.0 && again.kids.length() == 3
161
+
162
+ # a [Steps] actor with no `step` of its own steps its fields alone, nested actors too
163
+ fun aStepsActorWithoutAStepStepsItsFields() =
164
+ p := Pair(left: Stepper(time: 0.0), right: Some(Nest(time: 0.0, kids: Nil, held: true, inner: Stepper(time: 0.0)))).step(0.25)
165
+ assert p.left.time == 0.25
166
+ assert p.right.map(|x| x.time) == Some(0.25)
167
+ assert p.right.map(|x| x.kids.map(|k| k.time)) == Some([0.25])
168
+
131
169
  struct ViewProbe[View](x: Float, log: Slice<Float>, fade: Float) =
132
170
  fun place(self) -> Place = Place.at(self.x, 0.0).fade(self.fade)
133
171
 
@@ -187,3 +225,28 @@ primitive ViewHelpers =
187
225
  _ => -1.0
188
226
 
189
227
  fun probeAt(x: Float, log: Slice<Float>) -> View = ViewProbe(x: x, log: log, fade: 1.0)
228
+
229
+ # A screen whose actors are stepped for it, of each kind a field can hold them in.
230
+ struct Stage[Screen, Steps](n: Int, one: Stepper, many: List<Stepper>, maybe: Option<Stepper>, nothing: Option<Stepper>, anyOne: Actor, anyMany: List<Actor>, loose: View) =
231
+ fun name(self) -> Str = "stage"
232
+
233
+ # A walker paused with the screen, clocks that run on.
234
+ struct Paused[Screen, Steps](paused: Bool, @stepsWhen(!self.paused) walker: Stepper, clocks: List<Stepper>) =
235
+ fun name(self) -> Str = "paused"
236
+
237
+ # A screen that lists `Steps` and steps its actor twice as fast itself.
238
+ struct Owned[Screen, Steps](one: Stepper) =
239
+ fun name(self) -> Str = "owned"
240
+
241
+ fun stepped(self, dt: Float) -> Owned = Owned(one: self.one.step(dt * 2.0))
242
+
243
+ # An actor that adds a kid each step, its kids stepped after; its inner stepper only
244
+ # while not held, read after its own step (which holds it from the second step on).
245
+ struct Nest[Actor, Steps](time: Float, kids: List<Stepper>, held: Bool, @stepsWhen(!self.held) inner: Stepper) =
246
+ fun place(self) -> Place = Place.at(0.0, 0.0)
247
+
248
+ fun step(self, dt: Float) -> Nest = Nest(..self, time: self.time + dt, kids: self.kids.append([Stepper(time: 0.0)]), held: true)
249
+
250
+ # An actor that is only what it holds.
251
+ struct Pair[Actor, Steps](left: Stepper, right: Option<Nest>) =
252
+ fun place(self) -> Place = Place.at(0.0, 0.0)