plum

#treesitter#compiler#wasm

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

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


6362264 — Peter John 2026-11-09T15:35:02+05:30
FBIP through trait objects, nested spread reuse, and reboxing value structs
compiler/core/src/ast.rs CHANGED
@@ -1117,6 +1117,9 @@ pub struct ClassCall {
1117
1117
  pub unique: bool,
1118
1118
  /// Set by the reuse analysis: name of the dead value whose cell is reused.
1119
1119
  pub reuse: Option<String>,
1120
+ /// Set by the uniqueness analysis with `unique`: the given fields that no other object
1121
+ /// shares. A value struct in one of them (held in a box) is written into its old box.
1122
+ pub reboxed: Vec<String>,
1120
1123
  }
1121
1124
 
1122
1125
  #[derive(Debug, Clone, PartialEq)]
compiler/core/src/ctors.rs CHANGED
@@ -317,6 +317,7 @@ pub fn lowerCtors(source: &mut Source) -> Vec<String> {
317
317
  spread: None,
318
318
  unique: false,
319
319
  reuse: None,
320
+ reboxed: vec![],
320
321
  })],
321
322
  declare: true,
322
323
  ty: None,
compiler/core/src/parser.rs CHANGED
@@ -1566,6 +1566,7 @@ impl<'a> AstParser<'a> {
1566
1566
  spread: None,
1567
1567
  unique: false,
1568
1568
  reuse: None,
1569
+ reboxed: vec![],
1569
1570
  });
1570
1571
  }
1571
1572
  out
@@ -1728,6 +1729,7 @@ impl<'a> AstParser<'a> {
1728
1729
  spread,
1729
1730
  unique: false,
1730
1731
  reuse: None,
1732
+ reboxed: vec![],
1731
1733
  }
1732
1734
  }
1733
1735
 
compiler/core/src/question.rs CHANGED
@@ -323,6 +323,7 @@ impl Pass {
323
323
  spread: None,
324
324
  unique: false,
325
325
  reuse: None,
326
+ reboxed: vec![],
326
327
  })
327
328
  .at_span(span);
328
329
  ("Ok", CasePattern::class("Err".to_string(), vec![CasePattern::Name(q)]), err)
compiler/core/src/simplify.rs CHANGED
@@ -468,6 +468,7 @@ impl<'a> Cx<'a> {
468
468
  spread: None,
469
469
  unique: false,
470
470
  reuse: None,
471
+ reboxed: vec![],
471
472
  };
472
473
  self.pinCall(cc, t, &open).map_or_else(|| fail(e), Some)
473
474
  }
compiler/core/src/spread_paths.rs CHANGED
@@ -118,7 +118,7 @@ impl Pass<'_> {
118
118
  value.span = f.value.span;
119
119
  out.push(FieldArg { name: head.to_string(), value });
120
120
  }
121
- Ok(ClassCall { type_name: ty.to_string(), fields: out, generics, spread: Some(Box::new(base)), unique: false, reuse: None })
121
+ Ok(ClassCall { type_name: ty.to_string(), fields: out, generics, spread: Some(Box::new(base)), unique: false, reuse: None, reboxed: vec![] })
122
122
  }
123
123
 
124
124
  fn rewrite(&mut self, e: &mut Expr, errors: &mut Vec<(Span, String)>) {
compiler/core/src/tests_lower.rs CHANGED
@@ -130,6 +130,7 @@ fn desugarTestsToFns(source: &crate::ast::Source) -> (crate::ast::Source, Vec<(S
130
130
  spread: None,
131
131
  unique: false,
132
132
  reuse: None,
133
+ reboxed: vec![],
133
134
  })],
134
135
  declare: true,
135
136
  ty: None,
compiler/core/src/trmc.rs CHANGED
@@ -474,6 +474,7 @@ impl<'a> Cx<'a> {
474
474
  spread: None,
475
475
  unique: false,
476
476
  reuse: None,
477
+ reboxed: vec![],
477
478
  }),
478
479
  ));
479
480
  stmts.extend(self.fill(var(&cell)));
compiler/core/src/uniqueness.rs CHANGED
@@ -457,6 +457,9 @@ struct An {
457
457
  freeIdx: HashMap<String, usize>,
458
458
  /// Every method unit by name: a call `x.m()` is resolved to all of them (no types here).
459
459
  methodIdx: HashMap<String, Vec<usize>>,
460
+ /// The program's traits: a call whose receiver is a trait object may run the method of any
461
+ /// implementer, so it resolves by name.
462
+ traits: HashSet<String>,
460
463
  enums: HashMap<String, Vec<String>>,
461
464
  sites: Vec<Site>,
462
465
  escaped: HashSet<usize>,
@@ -639,8 +642,8 @@ impl An {
639
642
  fn cands(&self, c: &FnCall) -> Vec<usize> {
640
643
  let all = self.methodIdx.get(&c.name).map(|v| v.as_slice()).unwrap_or(&[]);
641
644
  match &c.recv {
642
- Some(t) => all.iter().copied().filter(|&g| self.units[g].ty.as_deref() == Some(t.as_str())).collect(),
645
+ Some(t) if !self.traits.contains(t) => all.iter().copied().filter(|&g| self.units[g].ty.as_deref() == Some(t.as_str())).collect(),
643
- None => all.to_vec(),
646
+ _ => all.to_vec(),
644
647
  }
645
648
  }
646
649
 
@@ -1503,6 +1506,11 @@ pub fn markUnique(src: &mut Source) -> UniqueReport {
1503
1506
  if let Some(v) = varName(s) {
1504
1507
  if ok.contains(v) && an.varOk(ui, v).is_ok() && an.copyReason(c, v).is_none() {
1505
1508
  c.unique = true;
1509
+ // A unique field's old object is held by this one alone, which the update
1510
+ // overwrites: codegen may write a value struct into the box it had.
1511
+ let owner = an.owner.get(&c.type_name).cloned().unwrap_or_else(|| c.type_name.clone());
1512
+ let uf = an.uf.borrow();
1513
+ c.reboxed = c.fields.iter().filter(|f| uf.contains(&fieldKey(&owner, &f.name))).map(|f| f.name.clone()).collect();
1506
1514
  }
1507
1515
  }
1508
1516
  }
@@ -1805,6 +1813,7 @@ fn build(src: &Source) -> An {
1805
1813
  units,
1806
1814
  freeIdx,
1807
1815
  methodIdx,
1816
+ traits: src.items.iter().filter_map(|i| if let Item::Trait(t) = i { Some(t.name.clone()) } else { None }).collect(),
1808
1817
  enums,
1809
1818
  sites: vec![],
1810
1819
  escaped: HashSet::new(),
@@ -2255,7 +2264,9 @@ fn nodeKey(id: NodeId) -> NodeId {
2255
2264
  /// lowers to). A read counts as a move only when
2256
2265
  ///
2257
2266
  /// * the owner has exactly one spread in the unit, it gives the field, and the read is the only
2258
- /// mention of `o.f` in the unit;
2267
+ /// mention of `o.f` in the unit other than reads of its own fields (`o.f.x`) that run before the
2268
+ /// call: in the call's receiver and arguments, or in a statement before the spread's (in the
2269
+ /// unit's block, or an `if`, `match` or `while` body on the way to the spread);
2259
2270
  /// * for the call form, the read is the receiver or an argument of a call inside the value given
2260
2271
  /// to that field; for the binding form, the binding comes before the spread and every mention of
2261
2272
  /// the bound name is inside the value given to that field.
@@ -2357,32 +2368,35 @@ fn collectMoves(a: &An, _spreads: &[SpreadSite]) -> (HashMap<NodeId, String>, Ve
2357
2368
  }
2358
2369
  for k in 0..cc.fields.len() {
2359
2370
  let Some(g) = fieldName(cc, k) else { continue };
2360
- if g.contains('.') || fieldReads.get(&(o.clone(), g.clone())) != Some(&1) {
2371
+ let total = fieldReads.get(&(o.clone(), g.clone())).copied().unwrap_or(0);
2372
+ if g.contains('.') || total == 0 {
2361
2373
  continue;
2362
2374
  }
2363
2375
  let isRead = |x: &Expr| {
2364
2376
  matches!(&x.kind, ExprKind::Attribute(y)
2365
2377
  if y.attr == AttrKind::Field(g.clone()) && varName(&y.object) == Some(o.as_str()))
2366
2378
  };
2379
+ // The read handed to the call, and the call's receiver and arguments.
2367
- let mut found: Option<NodeId> = None;
2380
+ let mut found: Option<(NodeId, Vec<&Expr>)> = None;
2368
2381
  walkExpr(&cc.fields[k].value, &mut |n| {
2369
2382
  match n {
2370
2383
  Node::E(Expr { kind: ExprKind::Closure(_), .. }) => return false,
2371
2384
  Node::E(Expr { kind: ExprKind::FnCall(c), .. }) => {
2372
2385
  for x in &c.args {
2373
2386
  if isRead(argExpr(x)) {
2374
- found = Some(argExpr(x).id);
2387
+ found = Some((argExpr(x).id, c.args.iter().map(argExpr).collect()));
2375
2388
  }
2376
2389
  }
2377
2390
  }
2378
2391
  Node::E(Expr { kind: ExprKind::Attribute(y), .. }) => {
2379
2392
  if let AttrKind::Method(c) = &y.attr {
2393
+ let operands = || std::iter::once(&y.object).chain(c.args.iter().map(argExpr)).collect();
2380
2394
  if isRead(&y.object) {
2381
- found = Some(y.object.id);
2395
+ found = Some((y.object.id, operands()));
2382
2396
  }
2383
2397
  for x in &c.args {
2384
2398
  if isRead(argExpr(x)) {
2385
- found = Some(argExpr(x).id);
2399
+ found = Some((argExpr(x).id, operands()));
2386
2400
  }
2387
2401
  }
2388
2402
  }
@@ -2391,7 +2405,18 @@ fn collectMoves(a: &An, _spreads: &[SpreadSite]) -> (HashMap<NodeId, String>, Ve
2391
2405
  }
2392
2406
  true
2393
2407
  });
2408
+ // Other reads of `o.g` may only read a field of it (`o.g.h`, which holds no
2409
+ // reference to `o.g`) before the call can write it in place: in the call's own
2410
+ // receiver and arguments, or in a statement before the spread's.
2411
+ let found = found.filter(|(_, operands)| {
2412
+ let mut early: Vec<NodeId> = vec![];
2413
+ for x in operands {
2414
+ subReads(x, o, &g, &mut early);
2415
+ }
2416
+ readsBefore(&u.block, *node, o, &g, &mut early);
2417
+ total == 1 + early.len()
2418
+ });
2394
- if let Some(id) = found {
2419
+ if let Some((id, _)) = found {
2395
2420
  // `o` is spread into `cc`, so `cc`'s type owns the field.
2396
2421
  let Some(t) = a.owner.get(&cc.type_name) else { continue };
2397
2422
  let key = fieldKey(t, &g);
@@ -2424,6 +2449,125 @@ fn collectMoves(a: &An, _spreads: &[SpreadSite]) -> (HashMap<NodeId, String>, Ve
2424
2449
  (reads, moves)
2425
2450
  }
2426
2451
 
2452
+ /// The reads `self.f` of getters (`fun place(self) -> Place = self.at`) that hand out no reference:
2453
+ /// every call of a method of that name, anywhere, is read through at once, as the object of a
2454
+ /// field read (`a.place().x`) or the receiver of methods that only read their `self`
2455
+ /// (`a.place().local()`), as `x.f.h` and `x.f.m()` are for the field itself. Calls resolve by name,
2456
+ /// so one call of the name used otherwise keeps every getter's read a plain one.
2457
+ fn getterReads(a: &An, escaped: &HashSet<usize>) -> Vec<NodeId> {
2458
+ let mut getters: HashMap<&str, Vec<NodeId>> = HashMap::new();
2459
+ for (ui, u) in a.units.iter().enumerate() {
2460
+ if !(a.live[ui] && u.method && u.hasSelf && u.params.len() == 1) || IMPLICIT.contains(&u.name.as_str()) {
2461
+ continue;
2462
+ }
2463
+ if let [Stmt { kind: StmtKind::Expr(e, _, _), .. }] = &u.block.stmts[..] {
2464
+ if let ExprKind::Attribute(x) = &e.kind {
2465
+ if matches!(x.attr, AttrKind::Field(_)) && matches!(x.object.kind, ExprKind::Self_) {
2466
+ getters.entry(u.name.as_str()).or_default().push(e.id);
2467
+ }
2468
+ }
2469
+ }
2470
+ }
2471
+ if getters.is_empty() {
2472
+ return vec![];
2473
+ }
2474
+ let mut calls: HashMap<&str, usize> = HashMap::new();
2475
+ let mut good: HashMap<&str, usize> = HashMap::new();
2476
+ let mut named = HashSet::new();
2477
+ for (_, u) in a.units.iter().enumerate().filter(|(ui, _)| a.live[*ui]) {
2478
+ walkBlock(&u.block, &mut |n| {
2479
+ if let Node::E(Expr { kind: ExprKind::Attribute(x), .. }) = n {
2480
+ let getterCall = |o: &Expr| match &o.kind {
2481
+ ExprKind::Attribute(y) => match &y.attr {
2482
+ AttrKind::Method(c) => getters.get_key_value(c.name.as_str()).map(|(k, _)| *k),
2483
+ _ => None,
2484
+ },
2485
+ _ => None,
2486
+ };
2487
+ match &x.attr {
2488
+ AttrKind::Method(c) => {
2489
+ if let Some(k) = getters.get_key_value(c.name.as_str()).map(|(k, _)| *k) {
2490
+ *calls.entry(k).or_default() += 1;
2491
+ }
2492
+ if let Some(k) = getterCall(&x.object) {
2493
+ let cands = a.cands(c);
2494
+ if !cands.is_empty() && cands.iter().all(|g| a.ro.contains(g)) {
2495
+ *good.entry(k).or_default() += 1;
2496
+ }
2497
+ }
2498
+ }
2499
+ AttrKind::Field(f) => {
2500
+ if matches!(x.object.kind, ExprKind::TypeName(_)) {
2501
+ if let Some(k) = getters.get_key_value(f.as_str()).map(|(k, _)| *k) {
2502
+ named.insert(k);
2503
+ }
2504
+ }
2505
+ if let Some(k) = getterCall(&x.object) {
2506
+ *good.entry(k).or_default() += 1;
2507
+ }
2508
+ }
2509
+ }
2510
+ }
2511
+ true
2512
+ });
2513
+ }
2514
+ getters
2515
+ .into_iter()
2516
+ .filter(|(k, _)| !named.contains(k) && !a.methodIdx.get(*k).is_some_and(|gs| gs.iter().any(|g| escaped.contains(g))))
2517
+ .filter(|(k, _)| calls.get(k).copied().unwrap_or(0) == good.get(k).copied().unwrap_or(0))
2518
+ .flat_map(|(_, ids)| ids)
2519
+ .collect()
2520
+ }
2521
+
2522
+ /// The ids of the reads `o.g` in `e` that are the object of a field read `o.g.h`, outside closures.
2523
+ fn subReads(e: &Expr, o: &str, g: &str, out: &mut Vec<NodeId>) {
2524
+ walkExpr(e, &mut |n| subRead(n, o, g, out));
2525
+ }
2526
+
2527
+ fn subRead(n: Node, o: &str, g: &str, out: &mut Vec<NodeId>) -> bool {
2528
+ match n {
2529
+ Node::E(Expr { kind: ExprKind::Closure(_), .. }) => false,
2530
+ Node::E(Expr { kind: ExprKind::Attribute(x), .. }) => {
2531
+ if let (AttrKind::Field(_), ExprKind::Attribute(y)) = (&x.attr, &x.object.kind) {
2532
+ if y.attr == AttrKind::Field(g.to_string()) && varName(&y.object) == Some(o) {
2533
+ out.push(x.object.id);
2534
+ }
2535
+ }
2536
+ true
2537
+ }
2538
+ _ => true,
2539
+ }
2540
+ }
2541
+
2542
+ fn containsNode(s: &Stmt, id: NodeId) -> bool {
2543
+ let mut hit = false;
2544
+ walkStmt(s, &mut |n| {
2545
+ if let Node::E(e) = n {
2546
+ hit |= e.id == id;
2547
+ }
2548
+ !hit
2549
+ });
2550
+ hit
2551
+ }
2552
+
2553
+ /// `subReads` in the statements that run before the one holding node `spread`, in `b` and in
2554
+ /// each `if`, `match` or `while` body on the way down to it.
2555
+ fn readsBefore(b: &Block, spread: NodeId, o: &str, g: &str, out: &mut Vec<NodeId>) {
2556
+ let Some(i) = b.stmts.iter().position(|s| containsNode(s, spread)) else { return };
2557
+ for s in &b.stmts[..i] {
2558
+ walkStmt(s, &mut |n| subRead(n, o, g, out));
2559
+ }
2560
+ let inner: Vec<&Block> = match &b.stmts[i].kind {
2561
+ StmtKind::If(f) => std::iter::once(&f.body).chain(f.else_ifs.iter().map(|e| &e.body)).chain(f.else_.iter()).collect(),
2562
+ StmtKind::Match(m) => m.cases.iter().map(|c| &c.body).collect(),
2563
+ StmtKind::While(w) => vec![&w.body],
2564
+ _ => vec![],
2565
+ };
2566
+ for blk in inner {
2567
+ readsBefore(blk, spread, o, g, out);
2568
+ }
2569
+ }
2570
+
2427
2571
  /// The methods whose `self` is only read (see `An.ro`): a greatest fixpoint, since a method may
2428
2572
  /// call another read-only one on `self`.
2429
2573
  fn readOnlySelf(an: &An) -> HashSet<usize> {
@@ -2809,6 +2953,7 @@ fn collectFacts(an: &mut An) {
2809
2953
  }
2810
2954
  let (moveReads, moves) = collectMoves(a, &spreads);
2811
2955
  allowed.extend(moveReads.keys().copied());
2956
+ allowed.extend(getterReads(a, &escaped));
2812
2957
  let readsEscape: HashSet<String> =
2813
2958
  reads.into_iter().filter(|(p, _)| !allowed.contains(p)).flat_map(|(_, f)| f).collect();
2814
2959
  badField.extend(readsEscape);
@@ -3228,7 +3373,7 @@ fn methodRecvKnown(an: &An, caller: usize, node: NodeId, src: &Source) -> bool {
3228
3373
  if e.id == node {
3229
3374
  if let ExprKind::Attribute(a) = &e.kind {
3230
3375
  if let AttrKind::Method(c) = &a.attr {
3231
- known = c.recv.is_some();
3376
+ known = c.recv.as_ref().is_some_and(|t| !an.traits.contains(t));
3232
3377
  }
3233
3378
  }
3234
3379
  }
compiler/core/tests/core/uniqueness_moves_test.rs CHANGED
@@ -190,10 +190,32 @@ fn a_field_moved_into_another_field_stays_shared() {
190
190
  assert!(!provedFn(&r, "Ship.update"), "{r:?}");
191
191
  }
192
192
 
193
+ /// `self.ship.x` is an `Int` read in the call's own argument: it is done before `update` runs, so
194
+ /// the move still proves.
193
195
  #[test]
194
- fn a_field_read_twice_in_the_update_stays_shared() {
196
+ fn a_field_of_the_moved_field_read_in_its_own_argument_proves() {
195
197
  let s = SHIP.replace("self.ship.update(dt)", "self.ship.update(self.ship.x)");
196
198
  let r = run(&format!("{s}fun go() -> S = mkS().step(1)\n"));
199
+ assert!(provedFn(&r, "Ship.update"), "{r:?}");
200
+ }
201
+
202
+ /// A second read that is not provably done before the move keeps the field shared: a later field
203
+ /// of the same construction, a method call on it, or a read in a closure.
204
+ #[test]
205
+ fn a_field_read_twice_in_the_update_stays_shared() {
206
+ for other in ["n: self.ship.x", "n: self.ship.update(0).x"] {
207
+ let s = SHIP.replace("ship: self.ship.update(dt))", &format!("ship: self.ship.update(dt), {other})"));
208
+ let r = run(&format!("{s}fun go() -> S = mkS().step(1)\n"));
209
+ assert!(!provedFn(&r, "Ship.update"), "{other}: {r:?}");
210
+ }
211
+ let s = SHIP.replace("self.ship.update(dt)", "self.ship.update(self.ship.update(0).x)");
212
+ let r = run(&format!("{s}fun go() -> S = mkS().step(1)\n"));
213
+ assert!(!provedFn(&r, "Ship.update"), "{r:?}");
214
+ let s = SHIP.replace(
215
+ "fun step(self, dt: Int) -> S = S(..self, ship: self.ship.update(dt))",
216
+ "fun step(self, dt: Int) -> S =\n f := |k: Int| self.ship.x + k\n S(..self, ship: self.ship.update(f(dt)))",
217
+ );
218
+ let r = run(&format!("{s}fun go() -> S = mkS().step(1)\n"));
197
219
  assert!(!provedFn(&r, "Ship.update"), "{r:?}");
198
220
  }
199
221
 
compiler/wasm-codegen/src/driver.rs CHANGED
@@ -545,6 +545,23 @@ impl<'a> Setup<'a> {
545
545
  let f = module.addFunction(t, &b);
546
546
  module.nameFunction(f, &format!("unbox.{name}"));
547
547
  withGen(|s| s.value_helpers.insert(format!("unbox:{name}"), f));
548
+ // rebox: the leaves written into an existing box (an in-place update's unique field)
549
+ let mut b = vec![0u8];
550
+ for i in 0..leaves.len() as u32 {
551
+ Instruction::LocalGet(0).encode(&mut b);
552
+ Instruction::LocalGet(1 + i).encode(&mut b);
553
+ Instruction::StructSet {
554
+ struct_type_index: box_idx,
555
+ field_index: i,
556
+ }
557
+ .encode(&mut b);
558
+ }
559
+ Instruction::End.encode(&mut b);
560
+ let params: Vec<ValType> = std::iter::once(gcRef(box_idx)).chain(leaves.iter().copied()).collect();
561
+ let t = module.addType(&params, &[]);
562
+ let f = module.addFunction(t, &b);
563
+ module.nameFunction(f, &format!("rebox.{name}"));
564
+ withGen(|s| s.value_helpers.insert(format!("rebox:{name}"), f));
548
565
  // eq
549
566
  let mut b = vec![0u8];
550
567
  let n = leaves.len() as u32;
compiler/wasm-codegen/src/expr.rs CHANGED
@@ -556,7 +556,20 @@ pub(crate) fn compileExpr(
556
556
  };
557
557
  compileExpr(src, body, ctx, state)?;
558
558
  Instruction::RefCastNonNull(HeapType::Concrete(variant_idx)).encode(body);
559
+ // A value struct in a field no other object shares goes into the box it
560
+ // had, read before the value runs, instead of a new one.
561
+ let fty = &field_tys[field_idx];
562
+ if call.reboxed.contains(&fa.name) && isValueTy(fty) && inferLocalType(&fa.value, ctx) == *fty {
563
+ Instruction::StructGet {
564
+ struct_type_index: variant_idx,
565
+ field_index: field_idx as u32,
566
+ }
567
+ .encode(body);
568
+ compileExprInto(&fa.value, fty, body, ctx, state)?;
569
+ Instruction::Call(valueHelper(&format!("rebox:{}", plum_checker::nominalName(fty).unwrap_or_default()))).encode(body);
570
+ continue;
571
+ }
559
- compileExprIntoHeap(&fa.value, &field_tys[field_idx], body, ctx, state)?;
572
+ compileExprIntoHeap(&fa.value, fty, body, ctx, state)?;
560
573
  Instruction::StructSet {
561
574
  struct_type_index: variant_idx,
562
575
  field_index: field_idx as u32,
compiler/wasm-codegen/tests/wasm_codegen/fusion_alloc_test.rs CHANGED
@@ -755,9 +755,10 @@ fun main() -> Int =
755
755
  }
756
756
 
757
757
  /// The scene walk's shape: each node's actor is stepped through the trait and the node rebuilt.
758
+ /// A match binder is not proved unique (the tree may be held elsewhere: here `old` is read after
758
- /// The actors are written in place (no allocation per node per tick); `--no-fbip` copies them.
759
+ /// the walks), so each step copies its actor, and the kept tree is unchanged.
759
760
  #[test]
760
- fn stepping_a_tree_of_trait_objects_is_in_place() {
761
+ fn stepping_a_tree_of_trait_objects_copies_each_actor() {
761
762
  let body = "enum Line =
762
763
  | Node(a: Actor, rest: Line)
763
764
  | End
@@ -774,15 +775,18 @@ fun total(xs: Line) -> Int = match xs
774
775
  Node(a, rest) => a.key() + total(rest)
775
776
  End => 0
776
777
 
778
+ fun main() -> Int =
777
- fun main() -> Int = total(run(Node(a: rock(), rest: build(10)), 100))
779
+ old := Node(a: rock(), rest: build(10))
780
+ new := run(old, 100)
781
+ total(new) * 1000 + total(old)
778
782
  ";
779
783
  let src = load("trait_tree_step", &format!("{PRE}{ACTORS}{body}"));
780
784
  let wasm = compileFbip(&src, true);
781
- assert_eq!(newsIn(&wasm, "Ship.step"), 0);
785
+ assert_eq!(newsIn(&wasm, "Ship.step"), 1);
782
- assert_eq!(runInt(&engine(false), &wasm).0, 1058);
786
+ assert_eq!(runInt(&engine(false), &wasm).0, 1058058);
783
787
  let copying = compileFbip(&src, false);
784
788
  assert_eq!(newsIn(&copying, "Ship.step"), 1);
785
- assert_eq!(runInt(&engine(false), &copying).0, 1058);
789
+ assert_eq!(runInt(&engine(false), &copying).0, 1058058);
786
790
  }
787
791
 
788
792
  /// A downcast whose match is not the result still moves the subject when the subject is
@@ -825,3 +829,134 @@ fun main() -> Int =
825
829
  assert!(newsIn(&wasm, "still") >= 1, "the subject is read after the match: a copy");
826
830
  assert_eq!(runInt(&engine(false), &wasm).0, 711);
827
831
  }
832
+
833
+ /// A trait object stepped and then read again in the same call's arguments is not handed over:
834
+ /// the step must copy, or the later read sees the stepped actor (`a.key()` after `a.step()`).
835
+ #[test]
836
+ fn trait_object_read_after_its_step_is_not_handed_over() {
837
+ let body = "fun spin(a: Actor, n: Int, acc: Int) -> Int = if n == 0 then acc else spin(a.step(), n - 1, acc + a.key())
838
+
839
+ fun main() -> Int = spin(Ship(label: \"a\", x: 0, y: 0), 10, 0) + spin(rock(), 3, 0)
840
+ ";
841
+ let src = load("trait_read_after_step", &format!("{PRE}{ACTORS}{body}"));
842
+ let wasm = compileFbip(&src, true);
843
+ assert_eq!(newsIn(&wasm, "Ship.step"), 1, "the step copies: `a` is read after it");
844
+ assert_eq!(runInt(&engine(false), &wasm).0, 54);
845
+ }
846
+
847
+ // ---- a spread of a field inside a spread of its owner ----
848
+
849
+ /// A trait with a place, and an actor that is never stepped. `Place` is a value struct (its fields
850
+ /// are scalars: held in a box inside a heap object) unless `tag` makes it a heap struct.
851
+ fn placed(tag: bool) -> String {
852
+ let field = if tag { ", tag: Str" } else { "" };
853
+ let rockTag = if tag { ", tag: \"r\"" } else { "" };
854
+ format!(
855
+ "struct Place(x: Int, y: Int, r: Int{field}) =
856
+ fun moveTo(self, x: Int, y: Int) -> Place = Place(..self, x: x, y: y)
857
+ fun sum(self) -> Int = self.x + self.y
858
+
859
+ trait Actor =
860
+ fun key(self) -> Int
861
+ fun place(self) -> Place
862
+ fun step(self) -> Self = self
863
+
864
+ struct Rock(n: Int) is Actor =
865
+ fun key(self) -> Int = self.n
866
+ fun place(self) -> Place = Place(x: self.n, y: 0, r: 0{rockTag})
867
+
868
+ "
869
+ )
870
+ }
871
+
872
+ /// The scene's actor shape: `Ship(..self, at: self.at.moveTo(..))` with the new position read
873
+ /// off `self.at` before, and the place read through a getter (`a.place().sum()`).
874
+ fn movedShip(tag: bool) -> String {
875
+ let t = if tag { ", tag: \"p\"" } else { "" };
876
+ format!(
877
+ "struct Ship(label: Str, at: Place, vx: Int) is Actor =
878
+ fun key(self) -> Int = self.at.x
879
+ fun place(self) -> Place = self.at
880
+ fun step(self) -> Ship =
881
+ nx := self.at.x + self.vx
882
+ vx := if nx > 50 || nx < 0 then 0 - self.vx else self.vx
883
+ Ship(..self, at: self.at.moveTo(nx, self.at.y + 1), vx: vx)
884
+
885
+ fun spin(a: Actor, n: Int, acc: Int) -> Int =
886
+ t := acc + a.place().sum()
887
+ if n == 0 then t else spin(a.step(), n - 1, t)
888
+
889
+ fun main() -> Int =
890
+ r: Actor := Rock(n: 2)
891
+ spin(Ship(label: \"s\", at: Place(x: 0, y: 7, r: 0{t}), vx: 3), 1000, 0) + spin(r, 3, 0)
892
+ "
893
+ )
894
+ }
895
+
896
+ /// The ship is unique, so its `at` is too: the place's spread writes it in place, as the ship's
897
+ /// does. No allocation per step; with `--no-fbip` both copy.
898
+ #[test]
899
+ fn nested_spread_of_a_moved_field_is_in_place() {
900
+ let src = load("nested_spread_moved_field", &format!("{PRE}{}{}", placed(true), movedShip(true)));
901
+ let wasm = compileFbip(&src, true);
902
+ assert_eq!(newsIn(&wasm, "Ship.step"), 0, "the ship is written in place");
903
+ assert_eq!(newsIn(&wasm, "Place.moveTo"), 0, "its place is written in place");
904
+ assert_eq!(runInt(&engine(false), &wasm).0, 531665);
905
+ let copying = compileFbip(&src, false);
906
+ assert_eq!(newsIn(&copying, "Ship.step"), 1, "--no-fbip: the ship copies");
907
+ assert_eq!(newsIn(&copying, "Place.moveTo"), 1, "--no-fbip: the place copies");
908
+ assert_eq!(runInt(&engine(false), &copying).0, 531665);
909
+ }
910
+
911
+ /// The same with `Place` a value struct: no spread of it allocates, but storing one in the ship
912
+ /// takes a box. The ship's `at` is unique, so the new place goes into the old box.
913
+ #[test]
914
+ fn value_struct_in_a_unique_field_reuses_its_box() {
915
+ let src = load("nested_spread_value_field", &format!("{PRE}{}{}", placed(false), movedShip(false)));
916
+ let wasm = compileFbip(&src, true);
917
+ assert_eq!(newsIn(&wasm, "Ship.step"), 0, "the ship and its place's box are written in place");
918
+ assert_eq!(runInt(&engine(false), &wasm).0, 531665);
919
+ let copying = compileFbip(&src, false);
920
+ assert_eq!(newsIn(&copying, "Ship.step"), 2, "--no-fbip: a new ship and a new box");
921
+ assert_eq!(runInt(&engine(false), &copying).0, 531665);
922
+ }
923
+
924
+ /// A read of the moved field after the call that may write it in place (`.moveTo(self.at.x + 1, ..)`
925
+ /// runs after the first `moveTo`) keeps the inner spread a copy, and so does a getter whose result
926
+ /// is kept.
927
+ #[test]
928
+ fn nested_spread_read_after_the_move_is_a_copy() {
929
+ let body = "struct Ship(label: Str, at: Place, vx: Int) is Actor =
930
+ fun key(self) -> Int = self.at.x
931
+ fun place(self) -> Place = self.at
932
+ fun step(self) -> Ship = Ship(..self, at: self.at.moveTo(self.vx, 0).moveTo(self.at.x + 1, 0))
933
+
934
+ fun spin(a: Actor, n: Int, acc: Int) -> Int = if n == 0 then acc else spin(a.step(), n - 1, acc + 1)
935
+
936
+ fun main() -> Int =
937
+ r: Actor := Rock(n: 2)
938
+ s := spin(Ship(label: \"s\", at: Place(x: 5, y: 7, r: 0, tag: \"p\"), vx: 3), 1, 0)
939
+ p: Actor := Ship(label: \"s\", at: Place(x: 5, y: 7, r: 0, tag: \"p\"), vx: 3)
940
+ q := p.step()
941
+ q.key() * 100 + s + spin(r, 3, 0)
942
+ ";
943
+ let src = load("nested_spread_read_after", &format!("{PRE}{}{body}", placed(true)));
944
+ let wasm = compileFbip(&src, true);
945
+ assert_eq!(runInt(&engine(false), &wasm).0, 604);
946
+ let kept = "struct Ship(label: Str, at: Place, vx: Int) is Actor =
947
+ fun key(self) -> Int = self.at.x
948
+ fun place(self) -> Place = self.at
949
+ fun step(self) -> Ship = Ship(..self, at: self.at.moveTo(self.at.x + self.vx, 0))
950
+
951
+ fun spin(a: Actor, n: Int, acc: Int) -> Int =
952
+ p := a.place()
953
+ b := a.step()
954
+ if n == 0 then acc + p.x else spin(b, n - 1, acc + p.x)
955
+
956
+ fun main() -> Int = spin(Ship(label: \"s\", at: Place(x: 0, y: 0, r: 0, tag: \"p\"), vx: 1), 10, 0) + spin(Rock(n: 2), 0, 0)
957
+ ";
958
+ let src = load("nested_spread_getter_kept", &format!("{PRE}{}{kept}", placed(true)));
959
+ let wasm = compileFbip(&src, true);
960
+ assert!(newsIn(&wasm, "Place.moveTo") >= 1, "the getter's result is kept: the place copies");
961
+ assert_eq!(runInt(&engine(false), &wasm).0, 57);
962
+ }