plum

#treesitter#compiler#wasm

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

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


3c69edb — Peter John 2026-11-16T15:59:13+05:30
body perf: a variant struct holds value fields of at most 4 leaves in line (`Vec2`, `Color`, `Aabb`: `Body`'s `pos`/`vel`/`push`, a sprite's tint, `Bounce(box)`), every value field of a variant or none (`INLINE_MAX_LEAVES`; `Place`, 8, stays boxed, as a spread that keeps it copies one reference), not in generic types, variants with a `mut` field or enums with shared fields; per-field `get.`/`set.` helpers read and write the leaves (construction, `.field`, spreads, in-place spreads, cell reuse, patterns through the leaf map, `@copy`); `optimize::inlineLeaves` spills the nullable reference parameters of an accessor (only parameter and field reads and writes), so `unbox.*` and those helpers are copied into callers; `if c then a else b` of plain numbers is a `select`, so `Float.max`/`min` are copied in; `Body.step` builds its `Landing` in one match and the body once (`landed` gone). Cause: `Body` is boxed and held its three `Vec2`s as boxes, so a step allocated four structs where `Motion` (flat) took two, and every `pos.x` called `unbox.Vec2`. Orbit Runner, native, medians of 9 (head and before-bodies measured in the same run; the machine was loaded, before-bodies at 14.77 against the 13.85 of the last commit): update 16.83 to 15.24 ms (before bodies 14.77: +3.2%, was +13.9%; that run also has 182 more game-over ticks, which step nothing), paint 151.3 to 144.7 ms (before bodies 150.3: -3.7%); checksum 166413027 kept; scale, medians of 5 (11 for update): update view 29.2 to 28.4, paint view 389 to 380, hand 266 to 264, spread 388 to 385 ms, checksum 502378645 kept; in-place spreads unchanged (game_in_place_test); fusion_alloc_test's value-field `--no-fbip` copy now makes one struct, the place in line; tests: e2e_records/inline_value_fields.rs, optimize_test (unbox copied in, select); docs/performance.md
compiler/wasm-codegen/src/calls.rs CHANGED
@@ -222,12 +222,7 @@ pub(crate) fn compileFieldRead(
222
222
  })?;
223
223
  compileExpr(object, body, ctx, state)?;
224
224
  Instruction::RefCastNonNull(HeapType::Concrete(variant_type_idx)).encode(body);
225
- Instruction::StructGet {
226
- struct_type_index: variant_type_idx,
227
- field_index: field_idx as u32 + ctx.gc_types.fieldBase(variant_type_idx),
225
+ emitFieldGet(variant_type_idx, field_idx, want, body);
228
- }
229
- .encode(body);
230
- unboxIfValue(want, body);
231
226
  Ok(())
232
227
  }
233
228
 
compiler/wasm-codegen/src/construct.rs CHANGED
@@ -144,7 +144,7 @@ pub(crate) fn compileVariantConstruction(
144
144
  ast::Arg::Keyword { value, .. } => value,
145
145
  };
146
146
  match field_tys.get(i) {
147
- Some(d) => compileExprIntoHeap(arg_expr, d, body, ctx, state)?,
147
+ Some(d) => compileFieldInto(arg_expr, d, variant_type_idx, i, body, ctx, state)?,
148
148
  None => compileExpr(arg_expr, body, ctx, state)?,
149
149
  }
150
150
  }
compiler/wasm-codegen/src/driver.rs CHANGED
@@ -608,6 +608,38 @@ impl<'a> Setup<'a> {
608
608
  withGen(|s| s.value_helpers.insert(format!("proj:{name}.{fname}"), f));
609
609
  }
610
610
  }
611
+ // A value struct a variant struct holds in line: reading its leaves out of a reference
612
+ // and writing them into one (small enough for `optimize::inlineLeaves` to copy in).
613
+ let mut inl: Vec<(u32, InlineFields)> = gc_types.inline_fields.iter().map(|(k, v)| (*k, v.clone())).collect();
614
+ inl.sort_by_key(|(k, _)| *k);
615
+ for (idx, plan) in inl {
616
+ for (i, (at, vty)) in plan.fields.iter().enumerate() {
617
+ let Some(vty) = vty else { continue };
618
+ let leaves = flatValtypes(vty, &gc_types);
619
+ let mut b = vec![0u8];
620
+ for j in 0..leaves.len() as u32 {
621
+ Instruction::LocalGet(0).encode(&mut b);
622
+ Instruction::StructGet { struct_type_index: idx, field_index: at + j }.encode(&mut b);
623
+ }
624
+ Instruction::End.encode(&mut b);
625
+ let t = module.addType(&[gcRef(idx)], &leaves);
626
+ let f = module.addFunction(t, &b);
627
+ module.nameFunction(f, &format!("get.{}.{i}", plan.label));
628
+ withGen(|s| s.value_helpers.insert(fieldGetKey(idx, i), f));
629
+ let mut b = vec![0u8];
630
+ for j in 0..leaves.len() as u32 {
631
+ Instruction::LocalGet(0).encode(&mut b);
632
+ Instruction::LocalGet(1 + j).encode(&mut b);
633
+ Instruction::StructSet { struct_type_index: idx, field_index: at + j }.encode(&mut b);
634
+ }
635
+ Instruction::End.encode(&mut b);
636
+ let params: Vec<ValType> = std::iter::once(gcRef(idx)).chain(leaves.iter().copied()).collect();
637
+ let t = module.addType(&params, &[]);
638
+ let f = module.addFunction(t, &b);
639
+ module.nameFunction(f, &format!("set.{}.{i}", plan.label));
640
+ withGen(|s| s.value_helpers.insert(fieldSetKey(idx, i), f));
641
+ }
642
+ }
611
643
  }
612
644
 
613
645
  /// Pre-allocate one instance of every payload-free variant of every enum instance.
compiler/wasm-codegen/src/expr.rs CHANGED
@@ -40,6 +40,62 @@ pub(crate) fn compileExprIntoHeap(
40
40
  Ok(())
41
41
  }
42
42
 
43
+ /// `Int`, `Float`, `Bool` or `Byte`: one number on the wasm stack.
44
+ fn isScalarTy(t: &PlumType) -> bool {
45
+ matches!(t, PlumType::TInt | PlumType::TFloat | PlumType::TBool | PlumType::TByte)
46
+ }
47
+
48
+ /// Is `e` a number worked out with no effect, no trap and next to no work: a literal, a
49
+ /// local or `self` holding a number, or (to `depth` levels) `-`, `+`, `-` or `*` of such?
50
+ /// (An integer division can trap; a call, a field read or a closure's capture is not plain.)
51
+ fn plainOperand(e: &ast::Expr, ctx: &LocalCtx, depth: u32) -> bool {
52
+ match &e.kind {
53
+ ast::ExprKind::Int(_) | ast::ExprKind::Float(_) | ast::ExprKind::BoolLit(_) => true,
54
+ ast::ExprKind::Var(n) => ctx.locals.contains_key(n) && isScalarTy(&inferLocalType(e, ctx)),
55
+ ast::ExprKind::Self_ => ctx.locals.contains_key("self") && isScalarTy(&inferLocalType(e, ctx)),
56
+ ast::ExprKind::Unary(u) => depth > 0 && matches!(u.op, ast::UnOp::Neg) && plainOperand(&u.operand, ctx, depth - 1),
57
+ ast::ExprKind::Binary(b) => {
58
+ depth > 0
59
+ && matches!(b.op, ast::BinOp::Add | ast::BinOp::Sub | ast::BinOp::Mul)
60
+ && matches!(inferLocalType(e, ctx), PlumType::TInt | PlumType::TFloat)
61
+ && plainOperand(&b.left, ctx, depth - 1)
62
+ && plainOperand(&b.right, ctx, depth - 1)
63
+ }
64
+ _ => false,
65
+ }
66
+ }
67
+
68
+ /// A hoisted constructor argument (of type `ty`, as its local holds it) made what field slot
69
+ /// `decl` takes: in line, a value's leaves (a box is opened); else a value is boxed.
70
+ pub(crate) fn fitHoisted(ty: &PlumType, decl: &PlumType, inline: bool, body: &mut Vec<u8>) {
71
+ if !inline {
72
+ boxIfValue(ty, body);
73
+ } else if !isValueTy(ty) {
74
+ emitUnbox(decl, body);
75
+ }
76
+ }
77
+
78
+ /// `compileExprIntoHeap` for field `i` of variant struct `idx`: an in-line value struct
79
+ /// field takes the value's leaves, not a box.
80
+ pub(crate) fn compileFieldInto(
81
+ expr: &ast::Expr,
82
+ decl: &PlumType,
83
+ idx: u32,
84
+ i: usize,
85
+ body: &mut Vec<u8>,
86
+ ctx: &LocalCtx,
87
+ state: &mut ModuleState,
88
+ ) -> Result<(), String> {
89
+ if !fieldInline(idx, i) {
90
+ return compileExprIntoHeap(expr, decl, body, ctx, state);
91
+ }
92
+ compileExprInto(expr, decl, body, ctx, state)?;
93
+ if !isValueTy(&inferLocalType(expr, ctx)) {
94
+ emitUnbox(decl, body);
95
+ }
96
+ Ok(())
97
+ }
98
+
43
99
  pub(crate) fn compileExpr(
44
100
  expr: &ast::Expr,
45
101
  body: &mut Vec<u8>,
@@ -310,6 +366,21 @@ fn compileExprNode(
310
366
  }
311
367
  Instruction::End.encode(body);
312
368
  }
369
+ // Both branches are cheap and can neither trap nor have an effect: both are worked
370
+ // out and `select` keeps one, with no branch (`Float.max` becomes small and straight
371
+ // enough for `optimize::inlineLeaves` to copy into its callers). Not when the
372
+ // condition binds a pattern (`if Some(v) := o then v else 0`): the branch reads it.
373
+ ast::Expr { kind: ast::ExprKind::InlineIf(t), .. }
374
+ if isScalarTy(&inferLocalType(expr, ctx))
375
+ && plainOperand(&t.then, ctx, 2)
376
+ && plainOperand(&t.else_, ctx, 2)
377
+ && !plum_core::visit::anyExpr(&t.condition, &mut |e| matches!(e.kind, ast::ExprKind::Bind(_))) =>
378
+ {
379
+ compileExpr(&t.then, body, ctx, state)?;
380
+ compileExpr(&t.else_, body, ctx, state)?;
381
+ compileBoolConditionAsI32(&t.condition, body, ctx, state)?;
382
+ Instruction::Select.encode(body);
383
+ }
313
384
  ast::Expr { kind: ast::ExprKind::InlineIf(t), .. } => {
314
385
  let result_vt = plumTypeToValtype(&inferLocalType(expr, ctx));
315
386
  compileBoolConditionAsI32(&t.condition, body, ctx, state)?;
@@ -598,13 +669,19 @@ fn compileExprNode(
598
669
  };
599
670
  compileExpr(src, body, ctx, state)?;
600
671
  Instruction::RefCastNonNull(HeapType::Concrete(variant_idx)).encode(body);
672
+ let fty = &field_tys[field_idx];
673
+ // A value struct held in line: its leaves written over the old ones.
674
+ if fieldInline(variant_idx, field_idx) {
675
+ compileFieldInto(&fa.value, fty, variant_idx, field_idx, body, ctx, state)?;
676
+ Instruction::Call(valueHelper(&fieldSetKey(variant_idx, field_idx))).encode(body);
677
+ continue;
678
+ }
601
679
  // A value struct in a field no other object shares goes into the box it
602
680
  // had, read before the value runs, instead of a new one.
603
- let fty = &field_tys[field_idx];
604
681
  if call.reboxed.contains(&fa.name) && isValueTy(fty) && inferLocalType(&fa.value, ctx) == *fty {
605
682
  Instruction::StructGet {
606
683
  struct_type_index: variant_idx,
607
- field_index: field_idx as u32 + ctx.gc_types.fieldBase(variant_idx),
684
+ field_index: ctx.gc_types.fieldAt(variant_idx, field_idx).0,
608
685
  }
609
686
  .encode(body);
610
687
  compileExprInto(&fa.value, fty, body, ctx, state)?;
@@ -614,7 +691,7 @@ fn compileExprNode(
614
691
  compileExprIntoHeap(&fa.value, fty, body, ctx, state)?;
615
692
  Instruction::StructSet {
616
693
  struct_type_index: variant_idx,
617
- field_index: field_idx as u32 + ctx.gc_types.fieldBase(variant_idx),
694
+ field_index: ctx.gc_types.fieldAt(variant_idx, field_idx).0,
618
695
  }
619
696
  .encode(body);
620
697
  }
@@ -652,17 +729,22 @@ fn compileExprNode(
652
729
  .expect("checked above");
653
730
  compileExpr(&rv, body, ctx, state)?;
654
731
  Instruction::RefCastNonNull(HeapType::Concrete(variant_idx)).encode(body);
732
+ let inline = fieldInline(variant_idx, field_idx);
655
733
  if hoisted.contains(&i) {
656
734
  getHoistedCtorArg(expr, i, body, ctx)?;
657
- boxIfValue(&inferLocalType(&call.fields[i].value, ctx), body);
735
+ fitHoisted(&inferLocalType(&call.fields[i].value, ctx), &field_tys[field_idx], inline, body);
658
736
  } else {
659
- compileExprIntoHeap(&call.fields[i].value, &field_tys[field_idx], body, ctx, state)?;
737
+ compileFieldInto(&call.fields[i].value, &field_tys[field_idx], variant_idx, field_idx, body, ctx, state)?;
660
738
  }
739
+ if inline {
740
+ Instruction::Call(valueHelper(&fieldSetKey(variant_idx, field_idx))).encode(body);
741
+ } else {
661
- Instruction::StructSet {
742
+ Instruction::StructSet {
662
- struct_type_index: variant_idx,
743
+ struct_type_index: variant_idx,
663
- field_index: field_idx as u32 + ctx.gc_types.fieldBase(variant_idx),
744
+ field_index: ctx.gc_types.fieldAt(variant_idx, field_idx).0,
745
+ }
746
+ .encode(body);
664
747
  }
665
- .encode(body);
666
748
  }
667
749
  compileExpr(&rv, body, ctx, state)?;
668
750
  Instruction::RefCastNonNull(HeapType::Concrete(variant_idx)).encode(body);
@@ -674,10 +756,10 @@ fn compileExprNode(
674
756
  match call.fields.iter().position(|fa| &fa.name == field_name) {
675
757
  Some(i) if hoisted.contains(&i) => {
676
758
  getHoistedCtorArg(expr, i, body, ctx)?;
677
- boxIfValue(&inferLocalType(&call.fields[i].value, ctx), body);
759
+ fitHoisted(&inferLocalType(&call.fields[i].value, ctx), &field_tys[field_idx], fieldInline(variant_idx, field_idx), body);
678
760
  }
679
761
  Some(i) => {
680
- compileExprIntoHeap(&call.fields[i].value, &field_tys[field_idx], body, ctx, state)?
762
+ compileFieldInto(&call.fields[i].value, &field_tys[field_idx], variant_idx, field_idx, body, ctx, state)?
681
763
  }
682
764
  // `Circle(..c, radius: 10)` — a field not overridden is read
683
765
  // straight off the spread source instead (checker only proved
@@ -704,11 +786,10 @@ fn compileExprNode(
704
786
  .unwrap_or(variant_idx);
705
787
  compileExpr(spread, body, ctx, state)?;
706
788
  Instruction::RefCastNonNull(HeapType::Concrete(src_idx)).encode(body);
707
- Instruction::StructGet {
789
+ // As the new struct holds it: the leaves of a value it holds in line,
708
- struct_type_index: src_idx,
790
+ // else the one wasm field (a value's box).
791
+ let want = if fieldInline(variant_idx, field_idx) { field_tys[field_idx].clone() } else { PlumType::TVar("_".to_string()) };
709
- field_index: field_idx as u32 + ctx.gc_types.fieldBase(src_idx),
792
+ emitFieldGet(src_idx, field_idx, &want, body);
710
- }
711
- .encode(body);
712
793
  }
713
794
  }
714
795
  }
compiler/wasm-codegen/src/gctypes.rs CHANGED
@@ -118,6 +118,54 @@ pub struct GcTypeRegistry {
118
118
  /// Struct type index of a tagged type (its supertype and each variant) -> its tag: these
119
119
  /// structs start with the tag field, so their own fields start at index 1.
120
120
  pub tagged: HashMap<u32, i32>,
121
+ /// Variant struct index -> where each of its fields is, when it holds a value struct
122
+ /// in line (see `inlinePlan`): `(first wasm field, the value type if in line)` per field.
123
+ pub inline_fields: HashMap<u32, InlineFields>,
124
+ }
125
+
126
+ /// The fields of a variant struct that holds value structs in line: each field's first
127
+ /// wasm field and, for one held in line, its value type (its leaves are that many
128
+ /// consecutive wasm fields), with the variant's name for the helpers' names.
129
+ #[derive(Clone, Debug)]
130
+ pub struct InlineFields {
131
+ pub label: String,
132
+ pub fields: Vec<(u32, Option<PlumType>)>,
133
+ }
134
+
135
+ /// The most leaves a value struct a variant struct holds in line may have (`Vec2` 2,
136
+ /// `Color` and `Aabb` 4). A struct copied with the value unchanged (`Dot(..self, clock: t)`)
137
+ /// copies each leaf where a box is one reference: a bigger value (`Place`, 8) stays boxed.
138
+ pub const INLINE_MAX_LEAVES: u32 = 4;
139
+
140
+ /// The fields of variant `info` (of a type whose struct starts with `base` fields, the tag)
141
+ /// as its struct holds them, when it holds value structs in line: a field whose declared
142
+ /// type is a value struct (`Vec2`) is its leaves, so making, reading or copying it allocates
143
+ /// no box. Every value field of the variant or none (a pattern's leaf map takes each value
144
+ /// field as leaves), so none when one has more than `INLINE_MAX_LEAVES`. Only in a variant
145
+ /// of a non-generic type with no `mut` field (a `mut` field is assigned through its box)
146
+ /// and no shared enum fields (they are the supertype's, which every variant's struct must
147
+ /// start with); a value enum's own box is its leaves already.
148
+ pub(crate) fn inlinePlan(info: &EnumVariantInfo, base: u32, sharedFields: bool) -> Option<Vec<(u32, Option<PlumType>)>> {
149
+ if !info.generics.is_empty() || sharedFields || info.mut_fields.iter().any(|m| *m) {
150
+ return None;
151
+ }
152
+ if !info.field_types.iter().any(|t| isValueTy(t) && leafCount(t) > 0)
153
+ || info.field_types.iter().any(|t| isValueTy(t) && leafCount(t) > INLINE_MAX_LEAVES)
154
+ {
155
+ return None;
156
+ }
157
+ let mut at = base;
158
+ let mut out = Vec::new();
159
+ for t in &info.field_types {
160
+ if isValueTy(t) {
161
+ out.push((at, Some(t.clone())));
162
+ at += leafCount(t);
163
+ } else {
164
+ out.push((at, None));
165
+ at += 1;
166
+ }
167
+ }
168
+ Some(out)
121
169
  }
122
170
 
123
171
  impl GcTypeRegistry {
@@ -141,6 +189,19 @@ impl GcTypeRegistry {
141
189
  _ => None,
142
190
  }
143
191
  }
192
+ /// Field `i` of variant struct `idx`: its first wasm field, and its value type when the
193
+ /// struct holds it in line (its leaves), else `None` (one wasm field).
194
+ pub fn fieldAt(&self, idx: u32, i: usize) -> (u32, Option<&PlumType>) {
195
+ match self.inline_fields.get(&idx) {
196
+ Some(f) => (f.fields[i].0, f.fields[i].1.as_ref()),
197
+ None => (self.fieldBase(idx) + i as u32, None),
198
+ }
199
+ }
200
+ /// The first wasm field of each field of variant struct `idx`, when it holds value
201
+ /// structs in line (a pattern's leaf map).
202
+ pub fn leafMap(&self, idx: u32) -> Option<Vec<u32>> {
203
+ self.inline_fields.get(&idx).map(|f| f.fields.iter().map(|(at, _)| *at).collect())
204
+ }
144
205
  /// Index of a struct type's first own field: 1 when it starts with the type tag.
145
206
  pub fn fieldBase(&self, struct_idx: u32) -> u32 {
146
207
  u32::from(self.tagged.contains_key(&struct_idx))
@@ -290,6 +351,7 @@ pub(crate) fn buildGcTypeRegistry(
290
351
  trait_names: HashSet::new(),
291
352
  tags: HashMap::new(),
292
353
  tagged: HashMap::new(),
354
+ inline_fields: HashMap::new(),
293
355
  };
294
356
  for item in &source.items {
295
357
  if let ast::Item::Trait(t) = item {
@@ -455,9 +517,23 @@ pub(crate) fn buildGcTypeRegistry(
455
517
  _ => Default::default(),
456
518
  }
457
519
  };
520
+ // The variants that hold value structs in line.
521
+ for (idx, slot) in slots.iter().enumerate() {
522
+ let Slot::Variant(ty, vname) = slot else { continue };
523
+ if valueFieldsOf(ty).is_some() {
524
+ continue;
525
+ }
526
+ let Some(info) = enum_variants.get(vname) else { continue };
527
+ let shared = enum_params.get(&info.enum_name).is_some_and(|p| !p.is_empty());
528
+ let base = u32::from(reg.tags.contains_key(ty));
529
+ if let Some(fields) = inlinePlan(info, base, shared) {
530
+ reg.inline_fields.insert(idx as u32, InlineFields { label: vname.clone(), fields });
531
+ }
532
+ }
458
533
  let subtypes: Vec<SubType> = slots
459
534
  .iter()
535
+ .enumerate()
460
- .map(|slot| match slot {
536
+ .map(|(slot_idx, slot)| match slot {
461
537
  Slot::Str => SubType {
462
538
  is_final: true,
463
539
  supertype_idx: None,
@@ -522,6 +598,12 @@ pub(crate) fn buildGcTypeRegistry(
522
598
  element_type: StorageType::Val(vt),
523
599
  mutable: true,
524
600
  }));
601
+ } else if reg.inline_fields.contains_key(&(slot_idx as u32)) {
602
+ // Value struct fields in line: their leaves.
603
+ for fty in plum_checker::variantFields(info, ty).iter() {
604
+ let vts = if isValueTy(fty) { flatValtypes(fty, &reg) } else { vec![plumTypeToGcValtype(fty, &reg)] };
605
+ field_types.extend(vts.into_iter().map(|vt| FieldType { element_type: StorageType::Val(vt), mutable: true }));
606
+ }
525
607
  } else {
526
608
  field_types.extend(plum_checker::variantFields(info, ty).iter().map(|fty| {
527
609
  FieldType {
compiler/wasm-codegen/src/intrinsics.rs CHANGED
@@ -101,8 +101,13 @@ pub(crate) fn compileCopyFnBody(subst: &Subst, variants: &plum_checker::EnumVari
101
101
  return Err(format!("@copy copies a struct, and {t} is not one"));
102
102
  }
103
103
  let base = g.fieldBase(idx);
104
+ // Every wasm field: an in-line value struct's leaves are several.
105
+ let n = match g.inline_fields.get(&idx) {
106
+ Some(f) => f.fields.iter().map(|(_, t)| t.as_ref().map_or(1, leafCount)).sum(),
107
+ None => info.field_types.len() as u32,
108
+ };
104
109
  g.emitTag(idx, &mut body);
105
- for i in 0..info.field_types.len() as u32 {
110
+ for i in 0..n {
106
111
  Instruction::LocalGet(0).encode(&mut body);
107
112
  Instruction::RefCastNonNull(HeapType::Concrete(idx)).encode(&mut body);
108
113
  Instruction::StructGet { struct_type_index: idx, field_index: base + i }.encode(&mut body);
compiler/wasm-codegen/src/matching.rs CHANGED
@@ -645,11 +645,14 @@ pub(crate) fn compileVariantConstructorArm(
645
645
  let field_types = inst_types.clone();
646
646
  // A value enum's box struct holds its fields FLATTENED into leaves, so field `i`
647
647
  // of the pattern lives at leaf `value_leaf_map[i]` (nested value fields span several).
648
+ // A variant struct holding value structs in line is laid out the same way.
648
- let value_leaf_map: Option<Vec<u32>> = valueFieldsOf(&sty).map(|fs| {
649
+ let value_leaf_map: Option<Vec<u32>> = valueFieldsOf(&sty)
650
+ .map(|fs| {
649
- fs.iter()
651
+ fs.iter()
650
- .map(|(n, _)| valueFieldRange(&sty, n).map(|(o, _)| o).unwrap_or(0))
652
+ .map(|(n, _)| valueFieldRange(&sty, n).map(|(o, _)| o).unwrap_or(0))
651
- .collect()
653
+ .collect()
652
- });
654
+ })
655
+ .or_else(|| ctx.gc_types.leafMap(variant_idx));
653
656
 
654
657
  // This pattern's own narrowly-typed scratch local (declared with variant's exact
655
658
  // concrete ref type — see `nested_class_scratch_types`), distinct from
@@ -1174,6 +1177,7 @@ pub(crate) fn compileFieldPatterns(
1174
1177
  );
1175
1178
  Instruction::RefCastNonNull(HeapType::Concrete(inner_variant_idx)).encode(body);
1176
1179
  Instruction::LocalSet(nested_local).encode(body);
1180
+ let inner_leaf_map = ctx.gc_types.leafMap(inner_variant_idx);
1177
1181
  let mut onNested = |body: &mut Vec<u8>, state: &mut ModuleState| {
1178
1182
  compileFieldPatterns(
1179
1183
  fields,
@@ -1200,7 +1204,7 @@ pub(crate) fn compileFieldPatterns(
1200
1204
  0,
1201
1205
  nested_local,
1202
1206
  inner_variant_idx,
1203
- None,
1207
+ inner_leaf_map.as_deref(),
1204
1208
  rest,
1205
1209
  all_subjects,
1206
1210
  result_vt,
compiler/wasm-codegen/src/optimize.rs CHANGED
@@ -8,6 +8,7 @@
8
8
  //! whole instructions never needs any offset fixed up.
9
9
 
10
10
  use crate::module::WasmModule;
11
+ use std::collections::HashMap;
11
12
  use wasmparser::{FuncValidator, Operator, Parser, ValidPayload, Validator, ValidatorResources, WasmFeatures, WasmModuleResources};
12
13
 
13
14
  /// Replace body bytes `start..end` (relative to the function's body bytes, as stored in
@@ -215,24 +216,56 @@ pub(crate) fn removeDeadFunctions(module: &mut WasmModule) -> Result<usize, Stri
215
216
  /// Largest body (in bytes, after its parameter loads) `inlineLeaves` copies into a caller.
216
217
  pub(crate) const INLINE_LIMIT: usize = 20;
217
218
 
218
- /// Largest body `inlineLeaves` copies into a caller when it reads its (number) parameters out of
219
+ /// Largest body `inlineLeaves` copies into a caller when it reads its parameters out of
219
- /// order or more than once (`Int.compare`): the caller stores the arguments in locals of its own.
220
+ /// order or more than once (`Int.compare`; with a reference parameter only an accessor,
221
+ /// which reads and writes fields and nothing else: a value struct's `unbox`): the caller
222
+ /// stores the arguments in locals of its own.
220
223
  pub(crate) const SPILL_INLINE_LIMIT: usize = 32;
221
224
 
222
- /// The one-byte encoding of a number value type, the only kind a spilled parameter may have
225
+ /// May a spilled parameter have type `t`? A local of it must need no initialiser: a number
223
- /// (a local of it needs no initialiser).
226
+ /// or a nullable reference.
224
- fn numberValType(t: wasmparser::ValType) -> Option<u8> {
227
+ fn spillable(t: wasmparser::ValType) -> bool {
225
228
  match t {
229
+ wasmparser::ValType::I32 | wasmparser::ValType::I64 | wasmparser::ValType::F32 | wasmparser::ValType::F64 => true,
230
+ wasmparser::ValType::Ref(r) => r.is_nullable(),
226
- wasmparser::ValType::I32 => Some(0x7F),
231
+ wasmparser::ValType::V128 => false,
227
- wasmparser::ValType::I64 => Some(0x7E),
228
- wasmparser::ValType::F32 => Some(0x7D),
229
- wasmparser::ValType::F64 => Some(0x7C),
230
- _ => None,
231
232
  }
232
233
  }
233
234
 
235
+ /// The encoded parameter types of each defined function, from its declared type.
236
+ fn paramTypes(module: &WasmModule) -> Vec<Vec<Vec<u8>>> {
237
+ let mut byIdx: HashMap<u32, &wasm_encoder::FuncType> = HashMap::new();
238
+ let mut idx = 0;
239
+ for t in &module.types {
240
+ match t {
241
+ crate::module::TypeEntry::Func(ft) => {
242
+ byIdx.insert(idx, ft);
243
+ idx += 1;
244
+ }
245
+ crate::module::TypeEntry::Rec(subs) => idx += subs.len() as u32,
246
+ }
247
+ }
248
+ module
249
+ .functions
250
+ .iter()
251
+ .map(|(t, _)| {
252
+ byIdx.get(t).map_or_else(Vec::new, |ft| {
253
+ ft.params()
254
+ .iter()
255
+ .map(|vt| {
256
+ let mut b = Vec::new();
257
+ wasm_encoder::Encode::encode(vt, &mut b);
258
+ b
259
+ })
260
+ .collect()
261
+ })
262
+ })
263
+ .collect()
264
+ }
265
+
234
- /// `body` with `extra` more locals declared after its own, one group per local.
266
+ /// `body` with `extra` more locals declared after its own, one group per local (each an
267
+ /// encoded value type).
235
- fn addLocals(body: &[u8], extra: &[u8]) -> Result<Vec<u8>, String> {
268
+ fn addLocals(body: &[u8], extra: &[Vec<u8>]) -> Result<Vec<u8>, String> {
236
269
  let mut r = wasmparser::BinaryReader::new(body, 0);
237
270
  let groups = r.read_var_u32().map_err(|e| e.to_string())?;
238
271
  let from = r.original_position();
@@ -246,7 +279,7 @@ fn addLocals(body: &[u8], extra: &[u8]) -> Result<Vec<u8>, String> {
246
279
  out.extend_from_slice(&body[from..to]);
247
280
  for t in extra {
248
281
  out.push(1);
249
- out.push(*t);
282
+ out.extend_from_slice(t);
250
283
  }
251
284
  out.extend_from_slice(&body[to..]);
252
285
  Ok(out)
@@ -271,8 +304,9 @@ fn leb(mut v: u32, out: &mut Vec<u8>) {
271
304
  /// the bytes after the loads, put where the `call` was, do the same work on the same
272
305
  /// stack (a `return_call` becomes those bytes and a `return`). Accessors such as
273
306
  /// `Str.length` or `Array.at` go this way. A body whose number parameters are read in
274
- /// another order or more than once (`Int.compare` reads both twice), of at most
307
+ /// another order or more than once (`Int.compare` reads both twice), or an accessor that
308
+ /// reads a reference parameter more than once (`unbox.Vec2`: only parameter reads and field
275
- /// `SPILL_INLINE_LIMIT` bytes, is copied too: the caller first stores the arguments in
309
+ /// reads and writes), of at most `SPILL_INLINE_LIMIT` bytes, is copied too: the caller first stores the arguments in
276
310
  /// locals it adds for that callee's parameter types (one set per caller and signature, as
277
311
  /// each copy uses them up at once), and the copy reads those. Returns the number of call
278
312
  /// sites inlined.
@@ -286,20 +320,26 @@ pub(crate) fn inlineLeaves(module: &mut WasmModule) -> Result<usize, String> {
286
320
  rest: Option<usize>,
287
321
  end: Option<usize>,
288
322
  ok: bool,
289
- /// The spilling form: every parameter a number, no other local touched, no control.
323
+ /// The spilling form: every parameter a number or (in an accessor) a nullable
324
+ /// reference, no other local touched, no control.
290
325
  spill: bool,
326
+ /// A reference parameter: the body must be an accessor to spill.
327
+ refs: bool,
328
+ /// Only parameter reads and field reads and writes (`unbox.Vec2`, a field's `get.`).
329
+ access: bool,
291
- tys: Vec<u8>,
330
+ tys: Vec<Vec<u8>>,
292
331
  first: Option<usize>,
293
332
  /// `(start, end, parameter)` of each `local.get`.
294
333
  gets: Vec<(usize, usize, u32)>,
295
334
  }
296
335
  let mut scans: Vec<Scan> = (0..n)
297
- .map(|_| Scan { params: 0, loaded: 0, rest: None, end: None, ok: false, spill: false, tys: vec![], first: None, gets: vec![] })
336
+ .map(|_| Scan { params: 0, loaded: 0, rest: None, end: None, ok: false, spill: false, refs: false, access: true, tys: vec![], first: None, gets: vec![] })
298
337
  .collect();
299
338
  // Every local a function has (parameters included), for the locals a spilled copy adds.
300
339
  let mut localCount: Vec<u32> = vec![0; n];
301
340
  // Per defined function: (callee, op start, op end, is a return_call).
302
341
  let mut calls: Vec<Vec<(u32, usize, usize, bool)>> = vec![Vec::new(); n];
342
+ let declared = paramTypes(module);
303
343
  let mut cur = usize::MAX;
304
344
  walk(&bytes, |fn_i, v, op, start, end| {
305
345
  match op {
@@ -316,16 +356,19 @@ pub(crate) fn inlineLeaves(module: &mut WasmModule) -> Result<usize, String> {
316
356
  sc.params = v.len_locals();
317
357
  sc.spill = sc.ok;
318
358
  sc.first = Some(start);
319
- for k in 0..sc.params {
359
+ let tys = &declared[fn_i];
360
+ sc.spill &= tys.len() == sc.params as usize && (0..sc.params).all(|k| v.get_local_type(k).is_some_and(spillable));
320
- match v.get_local_type(k).and_then(numberValType) {
361
+ sc.refs = (0..sc.params).any(|k| matches!(v.get_local_type(k), Some(wasmparser::ValType::Ref(_))));
362
+ if sc.spill {
321
- Some(t) => sc.tys.push(t),
363
+ sc.tys = tys.clone();
322
- None => sc.spill = false,
323
- }
324
364
  }
325
365
  }
326
366
  if sc.end.is_some() {
327
367
  return;
328
368
  }
369
+ if !matches!(op, Operator::LocalGet { .. } | Operator::StructGet { .. } | Operator::StructSet { .. } | Operator::End) {
370
+ sc.access = false;
371
+ }
329
372
  let control = matches!(
330
373
  op,
331
374
  Operator::LocalSet { .. }
@@ -384,7 +427,7 @@ pub(crate) fn inlineLeaves(module: &mut WasmModule) -> Result<usize, String> {
384
427
  struct Copy {
385
428
  code: Vec<u8>,
386
429
  gets: Vec<(usize, usize, u32)>,
387
- tys: Vec<u8>,
430
+ tys: Vec<Vec<u8>>,
388
431
  }
389
432
  let inline: Vec<Option<Copy>> = scans
390
433
  .iter()
@@ -393,7 +436,7 @@ pub(crate) fn inlineLeaves(module: &mut WasmModule) -> Result<usize, String> {
393
436
  (true, Some(r), Some(e), _, _) if e - r <= INLINE_LIMIT => {
394
437
  Some(Copy { code: module.functions[d].1[r..e].to_vec(), gets: vec![], tys: vec![] })
395
438
  }
396
- (_, _, Some(e), true, Some(f)) if e - f <= SPILL_INLINE_LIMIT && sc.params > 0 => Some(Copy {
439
+ (_, _, Some(e), true, Some(f)) if e - f <= SPILL_INLINE_LIMIT && sc.params > 0 && (!sc.refs || sc.access) => Some(Copy {
397
440
  code: module.functions[d].1[f..e].to_vec(),
398
441
  gets: sc.gets.iter().map(|&(s, t, k)| (s - f, t - f, k)).collect(),
399
442
  tys: sc.tys.clone(),
@@ -403,8 +446,8 @@ pub(crate) fn inlineLeaves(module: &mut WasmModule) -> Result<usize, String> {
403
446
  .collect();
404
447
  let mut edits: Vec<Vec<Edit>> = (0..n).map(|_| Vec::new()).collect();
405
448
  // Per caller: the locals it adds, and the first of them for each signature spilled.
406
- let mut added: Vec<Vec<u8>> = vec![Vec::new(); n];
449
+ let mut added: Vec<Vec<Vec<u8>>> = vec![Vec::new(); n];
407
- let mut spillBase: Vec<std::collections::BTreeMap<Vec<u8>, u32>> = vec![Default::default(); n];
450
+ let mut spillBase: Vec<std::collections::BTreeMap<Vec<Vec<u8>>, u32>> = vec![Default::default(); n];
408
451
  for (d, cs) in calls.iter().enumerate() {
409
452
  for &(f, start, end, tail) in cs {
410
453
  let Some(callee) = f.checked_sub(imports).map(|c| c as usize) else { continue };
compiler/wasm-codegen/src/stmts.rs CHANGED
@@ -333,7 +333,7 @@ pub(crate) fn compileFieldStore(
333
333
  boxIfValue(&src.ty, body);
334
334
  Instruction::StructSet {
335
335
  struct_type_index: variant_type_idx,
336
- field_index: field_idx as u32 + ctx.gc_types.fieldBase(variant_type_idx),
336
+ field_index: ctx.gc_types.fieldAt(variant_type_idx, field_idx).0,
337
337
  }
338
338
  .encode(body);
339
339
  }
compiler/wasm-codegen/src/values.rs CHANGED
@@ -164,6 +164,43 @@ pub(crate) fn emitBox(ty: &PlumType, body: &mut Vec<u8>) {
164
164
  Instruction::StructNew(idx).encode(body);
165
165
  }
166
166
 
167
+ /// The `value_helpers` key of the reader of in-line value field `i` of variant struct `idx`
168
+ /// (`(ref) -> leaves`).
169
+ pub(crate) fn fieldGetKey(idx: u32, i: usize) -> String {
170
+ format!("get:{idx}.{i}")
171
+ }
172
+
173
+ /// The `value_helpers` key of the writer of in-line value field `i` of variant struct `idx`
174
+ /// (`(ref, leaves) -> ()`).
175
+ pub(crate) fn fieldSetKey(idx: u32, i: usize) -> String {
176
+ format!("set:{idx}.{i}")
177
+ }
178
+
179
+ /// With a reference to variant struct `idx` on the stack: pushes field `i` as its struct
180
+ /// holds it (one wasm field, or an in-line value struct's leaves), then boxes an in-line
181
+ /// value when `want` is not a value type.
182
+ pub(crate) fn emitFieldGet(idx: u32, i: usize, want: &PlumType, body: &mut Vec<u8>) {
183
+ let g = gcTypes();
184
+ match g.fieldAt(idx, i) {
185
+ (_, Some(vty)) => {
186
+ let vty = vty.clone();
187
+ Instruction::Call(valueHelper(&fieldGetKey(idx, i))).encode(body);
188
+ if !isValueTy(want) {
189
+ emitBox(&vty, body);
190
+ }
191
+ }
192
+ (at, None) => {
193
+ Instruction::StructGet { struct_type_index: idx, field_index: at }.encode(body);
194
+ unboxIfValue(want, body);
195
+ }
196
+ }
197
+ }
198
+
199
+ /// Is field `i` of variant struct `idx` a value struct held in line?
200
+ pub(crate) fn fieldInline(idx: u32, i: usize) -> bool {
201
+ gcTypes().fieldAt(idx, i).1.is_some()
202
+ }
203
+
167
204
  pub(crate) fn valueHelper(key: &str) -> u32 {
168
205
  withGen(|s| {
169
206
  *s.value_helpers
compiler/wasm-codegen/tests/wasm_codegen/e2e_records/inline_value_fields.rs ADDED
@@ -0,0 +1,177 @@
1
+ //! A variant struct holds a small value struct field (`Vec2`-like, at most
2
+ //! `INLINE_MAX_LEAVES` leaves) in line, as its leaves: making, reading, copying, matching
3
+ //! and updating it in place allocate no box for the value.
4
+ use plum_test_support::*;
5
+ use wasmparser::{Parser, Payload};
6
+
7
+ const HEAD: &str = "\
8
+ import std/Str
9
+ import std/Int
10
+ import std/App
11
+ ";
12
+
13
+ /// Every operator of each named function, with no fusion (which may fold small calls
14
+ /// away and leave nothing to look at).
15
+ fn bodies(name: &str, src: &str) -> Vec<(String, Vec<String>)> {
16
+ let source = load(name, src).expect("loads");
17
+ let opts = plum_wasm_codegen::CompileOptions { passes: plum_driver::PassOptions { fusion: false, ..Default::default() }, ..Default::default() };
18
+ let bytes = plum_wasm_codegen::compile(&source, &opts).expect("compiles").wasm;
19
+ let mut names: std::collections::HashMap<u32, String> = Default::default();
20
+ let mut imports = 0u32;
21
+ let mut out = Vec::new();
22
+ for p in Parser::new(0).parse_all(&bytes) {
23
+ match p.unwrap() {
24
+ Payload::ImportSection(s) => imports = s.count(),
25
+ Payload::CustomSection(c) => {
26
+ if let wasmparser::KnownCustom::Name(r) = c.as_known() {
27
+ for n in r {
28
+ if let wasmparser::Name::Function(m) = n.unwrap() {
29
+ for e in m {
30
+ let e = e.unwrap();
31
+ names.insert(e.index, e.name.to_string());
32
+ }
33
+ }
34
+ }
35
+ }
36
+ }
37
+ Payload::CodeSectionEntry(b) => {
38
+ let mut ops = Vec::new();
39
+ let mut r = b.get_operators_reader().unwrap();
40
+ while !r.eof() {
41
+ ops.push(format!("{:?}", r.read().unwrap()));
42
+ }
43
+ out.push(ops);
44
+ }
45
+ _ => {}
46
+ }
47
+ }
48
+ out.into_iter().enumerate().map(|(i, ops)| (names.get(&(imports + i as u32)).cloned().unwrap_or_default(), ops)).collect()
49
+ }
50
+
51
+ fn ops<'a>(all: &'a [(String, Vec<String>)], name: &str) -> &'a [String] {
52
+ &all.iter().find(|(n, _)| n == name).unwrap_or_else(|| panic!("no function {name}: {:?}", all.iter().map(|b| &b.0).collect::<Vec<_>>())).1
53
+ }
54
+
55
+ fn count(ops: &[String], prefix: &str) -> usize {
56
+ ops.iter().filter(|o| o.starts_with(prefix)).count()
57
+ }
58
+
59
+ const MOVER: &str = "
60
+ struct P2(x: Int, y: Int)
61
+
62
+ struct Mover(pos: P2, vel: P2, name: Str) =
63
+ fun step(self) -> Mover = Mover(..self, pos: P2(x: self.pos.x + self.vel.x, y: self.pos.y + self.vel.y))
64
+
65
+ fun speed(self) -> Int = match self
66
+ Mover(P2(x, y), v, n) => v.x + v.y + n.length() + x * 0 + y * 0
67
+
68
+ enum Wall =
69
+ | Free
70
+ | Bounce(box: P2)
71
+
72
+ primitive Main[App] =
73
+ fun run(m: Mover, n: Int) -> Mover = if n == 0 then m else Main.run(m.step(), n - 1)
74
+
75
+ fun limit(w: Wall) -> Int = match w
76
+ Free => 0
77
+ Bounce(b) => b.x + b.y
78
+
79
+ fun main() -> Int =
80
+ m := Main.run(Mover(pos: P2(x: 1, y: 2), vel: P2(x: 3, y: 4), name: \"mo\"), 5)
81
+ m.pos.x * 1000 + m.pos.y + Main.limit(Bounce(box: P2(x: 10, y: 20))) * 100000 + m.speed() * 10000000
82
+ ";
83
+
84
+ /// Made, stepped with a spread, read through `.pos.x`, matched with a nested value pattern,
85
+ /// and a variant's value payload: the same answers as with boxes.
86
+ #[test]
87
+ fn valueFieldsInLineRun() {
88
+ let src = format!("{HEAD}{MOVER}");
89
+ // pos (1, 2) + 5 * (3, 4) = (16, 22); Bounce's box 30; speed 3 + 4 + 2 = 9.
90
+ assert_eq!(runInt("inline_run", &src), 9 * 10000000 + 30 * 100000 + 16 * 1000 + 22);
91
+ }
92
+
93
+ /// A step makes one struct, the mover: the new `pos` is its leaves, and the `vel` it keeps
94
+ /// is copied leaf by leaf, not a `P2` box.
95
+ #[test]
96
+ fn aSpreadOfAValueFieldMakesOneStruct() {
97
+ let src = format!("{HEAD}{MOVER}");
98
+ let all = bodies("inline_step", &src);
99
+ let step = ops(&all, "Mover.step");
100
+ assert_eq!(count(step, "StructNew"), 1, "{step:?}");
101
+ assert!(!all.iter().any(|(n, _)| n.starts_with("unbox.P2")), "{:?}", all.iter().map(|b| &b.0).collect::<Vec<_>>());
102
+ }
103
+
104
+ /// A value of more than `INLINE_MAX_LEAVES` leaves stays boxed, and so do the small ones
105
+ /// beside it (every value field of a variant is in line or none is): a spread that keeps it
106
+ /// copies one reference.
107
+ #[test]
108
+ fn aBigValueFieldStaysBoxed() {
109
+ let src = format!(
110
+ "{HEAD}
111
+ struct Big(a: Int, b: Int, c: Int, d: Int, e: Int)
112
+ struct P2(x: Int, y: Int)
113
+
114
+ struct Hold(big: Big, at: P2, n: Int, label: Str) =
115
+ fun bumpN(self, k: Int) -> Hold = if k == 0 then self else Hold(..self, n: self.n + 1).bumpN(k - 1)
116
+
117
+ primitive Main[App] =
118
+ fun main() -> Int =
119
+ h := Hold(big: Big(a: 1, b: 2, c: 3, d: 4, e: 5), at: P2(x: 6, y: 7), n: 0, label: \"h\").bumpN(2)
120
+ h.big.e * 100 + h.at.y * 10 + h.n
121
+ "
122
+ );
123
+ let all = bodies("inline_big", &src);
124
+ let bump = ops(&all, "Hold.bumpN");
125
+ // big, at and label one reference each, and n.
126
+ assert_eq!(count(bump, "StructGet"), 4, "{bump:?}");
127
+ assert_eq!(runInt("inline_big_run", &src), 572);
128
+ }
129
+
130
+ /// A type that implements a trait starts its struct with the tag: its value fields come
131
+ /// after it, and a call through the trait reads them.
132
+ #[test]
133
+ fn aTaggedStructHoldsValuesInLine() {
134
+ let src = format!(
135
+ "{HEAD}
136
+ struct P2(x: Int, y: Int)
137
+
138
+ trait Spot =
139
+ fun weight(self) -> Int
140
+
141
+ struct Dot[Spot](at: P2, w: Int) =
142
+ fun weight(self) -> Int = self.at.x * self.w + self.at.y
143
+
144
+ struct Line[Spot](a: P2, b: P2) =
145
+ fun weight(self) -> Int = self.b.x - self.a.x + self.b.y - self.a.y
146
+
147
+ primitive Main[App] =
148
+ fun total(xs: List<Spot>) -> Int = xs.fold(0, |acc, s| acc + s.weight())
149
+
150
+ fun main() -> Int =
151
+ Main.total([Dot(at: P2(x: 2, y: 3), w: 10), Line(a: P2(x: 1, y: 1), b: P2(x: 4, y: 6))])
152
+ "
153
+ );
154
+ assert_eq!(runInt("inline_tagged", &src), 23 + 8);
155
+ }
156
+
157
+ /// A spread of a struct nobody else holds writes the value's new leaves over the old ones.
158
+ #[test]
159
+ fn aUniqueSpreadWritesTheLeavesInPlace() {
160
+ let src = format!(
161
+ "{HEAD}
162
+ struct P2(x: Int, y: Int)
163
+
164
+ struct Ship(pos: P2, name: Str)
165
+
166
+ primitive Fly =
167
+ fun adv(s: Ship) -> Ship = Ship(..s, pos: P2(x: s.pos.x + 1, y: s.pos.y * 2))
168
+
169
+ primitive Main[App] =
170
+ fun main() -> Int =
171
+ s := Ship(pos: P2(x: 1, y: 7), name: \"s\")
172
+ t := Fly.adv(Fly.adv(s))
173
+ t.pos.x * 100 + t.pos.y
174
+ "
175
+ );
176
+ assert_eq!(runInt("inline_inplace", &src), 3 * 100 + 28);
177
+ }
compiler/wasm-codegen/tests/wasm_codegen/e2e_records/mod.rs CHANGED
@@ -1,5 +1,6 @@
1
1
  #![allow(non_snake_case)]
2
2
  mod enum_init;
3
+ mod inline_value_fields;
3
4
  mod inline_variants;
4
5
  mod record_init;
5
6
  mod unboxed_variants;
compiler/wasm-codegen/tests/wasm_codegen/fusion_alloc_test.rs CHANGED
@@ -975,16 +975,17 @@ fn nested_spread_of_a_moved_field_is_in_place() {
975
975
  assert_eq!(runInt(&engine(false), &copying).0, 531665);
976
976
  }
977
977
 
978
- /// The same with `Place` a value struct: no spread of it allocates, but storing one in the ship
978
+ /// The same with `Place` a value struct (three leaves): no spread of it allocates, and the ship
979
- /// takes a box. The ship's `at` is unique, so the new place goes into the old box.
979
+ /// holds it in line, so storing one takes no box. The ship is unique: the new place's leaves are
980
+ /// written over the old ones.
980
981
  #[test]
981
982
  fn value_struct_in_a_unique_field_reuses_its_box() {
982
983
  let src = load("nested_spread_value_field", &format!("{PRE}{}{}", placed(false), movedShip(false)));
983
984
  let wasm = compileFbip(&src, true);
984
- assert_eq!(newsIn(&wasm, "Ship.step"), 0, "the ship and its place's box are written in place");
985
+ assert_eq!(newsIn(&wasm, "Ship.step"), 0, "the ship and its place are written in place");
985
986
  assert_eq!(runInt(&engine(false), &wasm).0, 531665);
986
987
  let copying = compileFbip(&src, false);
987
- assert_eq!(newsIn(&copying, "Ship.step"), 2, "--no-fbip: a new ship and a new box");
988
+ assert_eq!(newsIn(&copying, "Ship.step"), 1, "--no-fbip: a new ship, its place in line");
988
989
  assert_eq!(runInt(&engine(false), &copying).0, 531665);
989
990
  }
990
991
 
compiler/wasm-codegen/tests/wasm_codegen/optimize_test.rs CHANGED
@@ -141,6 +141,43 @@ fun main() -> Int =\n Main.rank(1, 2) * 100 + Main.rank(3, 3) * 10 + Main.ran
141
141
  assert_eq!(runInt("cmp", src), (-10 + 1) * 100 + (10 - 1));
142
142
  }
143
143
 
144
+ /// A boxed value struct's `unbox` reads its reference parameter once per leaf: each caller
145
+ /// stores the reference in a local it adds (a nullable reference needs no initial value)
146
+ /// and copies the reads in. (`P2` is boxed in `Hold` as `Big` is too big to hold in line.)
147
+ #[test]
148
+ fn unboxIsCopiedIntoItsCallers() {
149
+ let src = "import std/Int\nimport std/Str\nimport std/App\n\
150
+ struct Big(a: Int, b: Int, c: Int, d: Int, e: Int)\nstruct P2(x: Int, y: Int)\n\
151
+ struct Hold(big: Big, at: P2, label: Str)\n\n\
152
+ primitive Main[App] =\n fun spot(h: Hold, n: Int) -> Int = if n == 0 then h.at.x * 10 + h.at.y else spot(h, n - 1)\n\n \
153
+ fun main() -> Int =\n Main.spot(Hold(big: Big(a: 1, b: 2, c: 3, d: 4, e: 5), at: P2(x: 6, y: 7), label: \"h\"), 2)\n";
154
+ let all = bodies(&compile("unboxcopy", src));
155
+ let names: Vec<&str> = all.iter().map(|b| b.0.as_str()).collect();
156
+ assert!(!names.iter().any(|n| n.starts_with("unbox.P2")), "{names:?}");
157
+ let spot = body(&all, "Main.spot");
158
+ assert!(!spot.iter().any(|op| op.starts_with("Call")), "{spot:?}");
159
+ assert_eq!(runInt("unboxcopy", src), 67);
160
+ }
161
+
162
+ /// `if c then a else b` of numbers whose branches are plain (locals, literals, `+ - *` of
163
+ /// them) is a `select`: no block, so `big` (and `Float.max` and the like) is copied into its
164
+ /// callers. A condition that binds a pattern keeps its branches after it.
165
+ #[test]
166
+ fn aPlainIfIsASelectCopiedIntoItsCallers() {
167
+ let src = "import std/Int\nimport std/Option\nimport std/App\n\
168
+ primitive Main[App] =\n fun big(a: Int, b: Int) -> Int = if a > b then a else b\n\n \
169
+ fun pick(o: Option<Int>) -> Int = if Some(v) := o then v + 1 else 0\n\n \
170
+ fun main() -> Int =\n Main.big(3, 9) * 100 + Main.big(7, -2) * 10 + Main.pick(Some(4)) + Main.pick(None)\n";
171
+ let source = plum_test_support::load("select", src).expect("loads");
172
+ let opts = plum_wasm_codegen::CompileOptions { passes: plum_driver::PassOptions { fusion: false, ..Default::default() }, ..Default::default() };
173
+ let all = bodies(&plum_wasm_codegen::compile(&source, &opts).expect("compiles").wasm);
174
+ let names: Vec<&str> = all.iter().map(|b| b.0.as_str()).collect();
175
+ assert!(!names.contains(&"Main.big"), "{names:?}");
176
+ let main = body(&all, "main");
177
+ assert_eq!(main.iter().filter(|op| op.starts_with("Select")).count(), 2, "{main:?}");
178
+ assert_eq!(runInt("select", src), 900 + 70 + 5);
179
+ }
180
+
144
181
  /// A static (`Tool.digit(..)`, a fn in a type's body without `self`) takes its arguments alone:
145
182
  /// no receiver stand-in is pushed, so a small one is copied into its callers, and a struct's
146
183
  /// static loop compiles to the same code as a `primitive`'s (benchmarks/static_calls; free fns,
docs/performance.md CHANGED
@@ -25,6 +25,8 @@ struct Cell(x: Float) =
25
25
 
26
26
  **Reuses memory.** Rebuilding a value of the same shape can reuse the old one. A `match` that takes apart a value nothing else holds may build the same variant into its cell, in generic types and methods too: `m.with(k, v)` on such a `Map` writes the new path into the old one's cells instead of allocating it. A value something else can still reach (a snapshot, a field, a closure, a second call) is never written. This is decided for a type's fields over the whole program, so while any code keeps old versions of a `Map` around, every `Map` update copies its path.
27
27
 
28
+ **Holds small values in line.** A struct of numbers (`Vec2`, `Color`, `Aabb`) is a value: it is passed and returned as its numbers, and a struct that holds one of at most four numbers (`Body(pos: Vec2, vel: Vec2, ..)`, a sprite's `tint: Color`) keeps those numbers in its own object, so making or changing it allocates no second object and reading `body.pos.x` is one load. A bigger one (`Place`, eight numbers) stays in an object of its own, which a copy that keeps it shares. Small functions are copied into their callers, and an `if` that picks between plain numbers (`x.max(y)`) has no branch.
29
+
28
30
  **Inlines closures.** A closure passed straight to a function that only calls it becomes a direct copy of the code, with no allocation.
29
31
 
30
32
  **Skips trees built only to be walked.** A call that builds a tree and hands it straight to a function that walks it once, such as `draw(io, picture(x))`, draws as it goes, without building the tree in memory.
std/game/Body.plum CHANGED
@@ -31,34 +31,33 @@ struct Body(
31
31
  pos: Vec2, vel: Vec2 = Vec2.Zero, push: Vec2 = Vec2.Zero, drag: Float = 0.0, edge: Walls = Free,
32
32
  angle: Float = 0.0, turn: Float = 0.0, faceAbove: Option<Float> = None) =
33
33
 
34
- # `dt` seconds later: pushed, slowed by the drag, moved, held to its edges, then turned.
34
+ # `dt` seconds later: pushed, slowed by the drag, moved, held to its edges, then turned:
35
+ # the way it moves when it faces its motion and is fast enough, else turned by `turn`.
35
36
  fun step(self, dt: Float) -> Body =
36
37
  keep := {1.0 - self.drag * dt}.max(0.0)
37
38
  vx := {self.vel.x + self.push.x * dt} * keep
38
39
  vy := {self.vel.y + self.push.y * dt} * keep
39
40
  x := self.pos.x + vx * dt
40
41
  y := self.pos.y + vy * dt
41
- match self.edge
42
+ at := match self.edge
42
- Free => self.landed(x, y, vx, vy, dt)
43
+ Free => Landing(x: x, y: y, vx: vx, vy: vy)
43
44
  Halt(box) =>
44
45
  hx := x.max(box.min.x).min(box.max.x)
45
46
  hy := y.max(box.min.y).min(box.max.y)
46
- self.landed(hx, hy, if hx != x then 0.0 else vx, if hy != y then 0.0 else vy, dt)
47
+ Landing(x: hx, y: hy, vx: if hx != x then 0.0 else vx, vy: if hy != y then 0.0 else vy)
47
48
  Bounce(box) =>
48
49
  outX := x < box.min.x || x > box.max.x
49
50
  outY := y < box.min.y || y > box.max.y
50
- self.landed(
51
+ Landing(
51
- if outX then x.max(box.min.x).min(box.max.x) else x, if outY then y.max(box.min.y).min(box.max.y) else y,
52
+ x: if outX then x.max(box.min.x).min(box.max.x) else x, y: if outY then y.max(box.min.y).min(box.max.y) else y,
52
- if outX then 0.0 - vx else vx, if outY then 0.0 - vy else vy, dt)
53
+ vx: if outX then 0.0 - vx else vx, vy: if outY then 0.0 - vy else vy)
53
- Wrap(box) => self.landed(Body.wrap(x, box.min.x, box.max.x), Body.wrap(y, box.min.y, box.max.y), vx, vy, dt)
54
+ Wrap(box) => Landing(x: Body.wrap(x, box.min.x, box.max.x), y: Body.wrap(y, box.min.y, box.max.y), vx: vx, vy: vy)
54
-
55
- # At (x, y) moving at (vx, vy), its angle turned for `dt`: the way it moves when it faces
56
- # its motion and is fast enough, else turned by `turn`.
57
- fun landed(self, x: Float, y: Float, vx: Float, vy: Float, dt: Float) -> Body =
58
55
  fast := match self.faceAbove
59
- Some(s) => vx * vx + vy * vy > s * s
56
+ Some(s) => at.vx * at.vx + at.vy * at.vy > s * s
60
57
  None => false
58
+ Body(
59
+ ..self, pos: Vec2(x: at.x, y: at.y), vel: Vec2(x: at.vx, y: at.vy),
61
- Body(..self, pos: Vec2(x: x, y: y), vel: Vec2(x: vx, y: vy), angle: if fast then Math.atan2(vx, 0.0 - vy) else self.angle + self.turn * dt)
60
+ angle: if fast then Math.atan2(at.vx, 0.0 - at.vy) else self.angle + self.turn * dt)
62
61
 
63
62
  # Where to draw it: turned by its angle about `origin` (in the drawing's own
64
63
  # coordinates), which lands on `pos`.
@@ -69,3 +68,6 @@ struct Body(
69
68
  fun wrap(v: Float, lo: Float, hi: Float) -> Float =
70
69
  span := hi - lo
71
70
  if v >= lo && v < hi then v else v - span * {{v - lo} / span}.floor()
71
+
72
+ # Where a body's step leaves it: at (x, y), moving at (vx, vy).
73
+ struct Landing(x: Float, y: Float, vx: Float, vy: Float)