plum

#treesitter#compiler#wasm

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

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


4c05ed8 — Peter John 2026-11-10T14:07:31+05:30
In-place updates apply to generic types
compiler/core/src/uniqueness.rs CHANGED
@@ -513,8 +513,9 @@ struct An {
513
513
  fieldTy: HashMap<String, Option<String>>,
514
514
  /// Per unit, what is known of each local and parameter's type.
515
515
  varTy: Vec<HashMap<String, Option<String>>>,
516
- /// Types whose spreads codegen always copies, with the reason: a generic type, and one variant of
516
+ /// Types whose spreads codegen always copies, with the reason: one variant of an enum (the
517
- /// an enum (the source's type is the enum, not the variant).
517
+ /// source's type is the enum, not the variant). A generic type is not one: codegen writes
518
+ /// in place when the spread keeps the type arguments (`wasm-codegen`'s `spreadInPlace`).
518
519
  copyTypes: HashMap<String, String>,
519
520
  /// Types and variants with a `mut` field.
520
521
  mutTypes: HashSet<String>,
@@ -1842,9 +1843,6 @@ fn build(src: &Source) -> An {
1842
1843
  let mut copyTypes: HashMap<String, String> = HashMap::new();
1843
1844
  for item in &src.items {
1844
1845
  let Item::Enum(e) = item else { continue };
1845
- if !e.generics.is_empty() {
1846
- copyTypes.insert(e.name.clone(), format!("`{}` is generic: its spreads copy", e.name));
1847
- }
1848
1846
  for v in e.variants.iter().filter(|v| v.name != e.name) {
1849
1847
  copyTypes.insert(v.name.clone(), format!("`{}` is one variant of `{}`: its spreads copy", v.name, e.name));
1850
1848
  }
compiler/core/tests/core/uniqueness_moves_test.rs CHANGED
@@ -242,12 +242,13 @@ fn a_hazard_is_reported_as_a_copy_and_not_marked() {
242
242
  assert!(!anyMarked(&r), "{r:?}");
243
243
  }
244
244
 
245
+ /// A generic type's spread is proved like any other's (it was always reported as a copy):
246
+ /// codegen writes in place when the spread keeps the type arguments.
245
247
  #[test]
246
- fn a_generic_spread_is_reported_as_a_copy() {
248
+ fn a_generic_spread_is_proved_in_place() {
247
249
  let r = run("struct B[T](v: T, n: Int) =\n fun bump(self) -> B[T] = B(..self, n: self.n + 1)\n\
248
250
  fun go() -> B[Int] = B(v: 1, n: 0).bump()\n");
249
- assert!(!provedFn(&r, "B.bump"), "{r:?}");
251
+ assert!(provedFn(&r, "B.bump"), "{r:?}");
250
- assert!(why(&r, "B.bump").contains("generic"), "{r:?}");
251
252
  }
252
253
 
253
254
  #[test]
compiler/driver/tests/driver_tests.rs CHANGED
@@ -177,6 +177,38 @@ fun run() -> Int =
177
177
  fun main() -> Int = run()
178
178
  ";
179
179
 
180
+ const GENERIC_TYPES: &str = "\
181
+ import std/Int
182
+ import std/Str
183
+
184
+ struct Ship[T](cargo: T, n: Int) =
185
+ fun update(self) -> Ship[T] = Ship(..self, n: self.n + 1)
186
+
187
+ struct Orb[T](cargo: T, n: Int) =
188
+ fun update(self) -> Orb[T] = Orb(..self, n: self.n + 2)
189
+
190
+ fun both(o: Orb[Str]) -> Int =
191
+ p := o.update()
192
+ o.n + p.n
193
+
194
+ fun run() -> Int =
195
+ t := Ship(cargo: \"s\", n: 0).update()
196
+ o := Orb(cargo: \"o\", n: 0)
197
+ t.n + both(o)
198
+
199
+ fun main() -> Int = run()
200
+ ";
201
+
202
+ /// A generic type's spread is marked in place like any other (codegen writes the cell when
203
+ /// the spread keeps the type arguments): it used to copy always. A shared receiver still copies.
204
+ #[test]
205
+ fn aGenericTypesSpreadIsProvedInPlace() {
206
+ let src = load("drv_generic_inplace", GENERIC_TYPES);
207
+ let info = check(&src, &PassOptions::default()).expect("checks");
208
+ assert!(spreadInPlace(&info, "Ship", "update"), "Ship[T].update is only called on fresh values");
209
+ assert!(!spreadInPlace(&info, "Orb", "update"), "Orb[T].update's receiver is read after the call");
210
+ }
211
+
180
212
  /// `Orb.update` is called with a value its caller reads afterwards; `Ship.update` is only ever
181
213
  /// called on a fresh one. Same method name, different types: only `Orb.update` copies.
182
214
  #[test]
compiler/wasm-codegen/src/expr.rs CHANGED
@@ -587,7 +587,7 @@ fn compileExprNode(
587
587
  )
588
588
  })?;
589
589
  let field_names = info.field_names.clone();
590
- if spreadInPlace(call, ctx) {
590
+ if spreadInPlace(call, &ety, ctx) {
591
591
  let src = call.spread.as_deref().expect("spreadInPlace checked");
592
592
  for fa in &call.fields {
593
593
  let Some(field_idx) = field_names.iter().position(|n| *n == fa.name) else {
@@ -688,11 +688,18 @@ fn compileExprNode(
688
688
  call.type_name, field_name
689
689
  )
690
690
  })?;
691
+ // The source's own struct: a spread that changes the type arguments
692
+ // (`Box(..self, value: v)` from a `Box[T]` to a `Box[B]`) reads the
693
+ // kept fields from another instance's struct than the one it builds.
694
+ let src_idx = ctx
695
+ .gc_types
696
+ .variantIdx(&inferLocalType(spread, ctx), &call.type_name)
697
+ .unwrap_or(variant_idx);
691
698
  compileExpr(spread, body, ctx, state)?;
692
- Instruction::RefCastNonNull(HeapType::Concrete(variant_idx)).encode(body);
699
+ Instruction::RefCastNonNull(HeapType::Concrete(src_idx)).encode(body);
693
700
  Instruction::StructGet {
694
- struct_type_index: variant_idx,
701
+ struct_type_index: src_idx,
695
- field_index: field_idx as u32 + ctx.gc_types.fieldBase(variant_idx),
702
+ field_index: field_idx as u32 + ctx.gc_types.fieldBase(src_idx),
696
703
  }
697
704
  .encode(body);
698
705
  }
compiler/wasm-codegen/src/units.rs CHANGED
@@ -158,6 +158,7 @@ impl<'a> TypeCollector<'a> {
158
158
  /// safely ordered (see `plum_core::uniqueness::inPlaceHazard`), in which case the copy path runs.
159
159
  pub(crate) fn spreadInPlace(
160
160
  call: &ast::ClassCall,
161
+ result: &PlumType,
161
162
  ctx: &LocalCtx,
162
163
  ) -> bool {
163
164
  let Some(sp) = call.spread.as_deref() else {
@@ -171,8 +172,14 @@ pub(crate) fn spreadInPlace(
171
172
  if !call.unique {
172
173
  return false;
173
174
  }
175
+ // The same record type, type arguments included: a generic type's copy for these
176
+ // arguments has one struct, so a spread that keeps them writes the cell it read; one
177
+ // that changes them (`Box(..b, value: f(b.value))` from a `Box[A]` to a `Box[B]`)
178
+ // builds another struct and copies. `result` is the spread's own type.
179
+ match inferLocalType(sp, ctx) {
174
- if !matches!(inferLocalType(sp, ctx), PlumType::TNamed(ref n) if *n == call.type_name) {
180
+ PlumType::TNamed(ref n) if *n == call.type_name => {}
181
+ ref src @ PlumType::TApp(ref n, _) if *n == call.type_name && canonTy(src) == canonTy(result) => {}
175
- return false;
182
+ _ => return false,
176
183
  }
177
184
  !plum_core::uniqueness::inPlaceHazard(name, &call.fields)
178
185
  }
tests/fbip/generic_types.plum ADDED
@@ -0,0 +1,61 @@
1
+ # Spreads of generic types (`Box[T]`, `Pair2[A, B]`) are updated in place when the old value
2
+ # is not used again, like any other type's; codegen used to copy every one. A spread that
3
+ # changes the type arguments builds another struct, and a value someone else still holds is
4
+ # copied: the results are the same with and without `--no-fbip`.
5
+ import std/Int
6
+ import std/Str
7
+ import std/List
8
+
9
+ struct Box[T](value: T, n: Int) =
10
+ fun bump(self) -> Box[T] = Box(..self, n: self.n + 1)
11
+ fun with[B](self, v: B) -> Box[B] = Box(..self, value: v)
12
+ fun set(self, v: T) -> Box[T] = Box(..self, value: v)
13
+
14
+ struct Pair2[A, B](a: A, b: B, hits: Int) =
15
+ fun hit(self) -> Pair2[A, B] = Pair2(..self, hits: self.hits + 1)
16
+
17
+ struct Holder[T](box: Box[T], tag: Str) =
18
+ fun step(self) -> Holder[T] = Holder(..self, box: self.box.bump())
19
+
20
+ fun spin[T](b: Box[T], k: Int) -> Box[T] = if k == 0 then b else spin(b.bump(), k - 1)
21
+
22
+ fun bumpAll[T](xs: List[Box[T]]) -> List[Box[T]] = xs.map(|b| b.bump())
23
+
24
+ test "a fresh generic value is updated through a chain"
25
+ b := Box(value: "x", n: 0).bump().bump().set("y")
26
+ assert b.n == 2
27
+ assert b.value == "y"
28
+ assert spin(Box(value: 1, n: 0), 5).n == 5
29
+
30
+ test "a generic value that is still held keeps its fields"
31
+ a := Box(value: 7, n: 1)
32
+ b := a.bump()
33
+ c := a.set(9)
34
+ assert a.n == 1
35
+ assert a.value == 7
36
+ assert b.n == 2
37
+ assert c.value == 9
38
+ assert c.n == 1
39
+
40
+ test "a spread that changes the type arguments builds a new value"
41
+ a := Box(value: 7, n: 3)
42
+ s := a.with("seven")
43
+ t := Box(value: 1, n: 4).with("one").bump()
44
+ assert a.value == 7
45
+ assert s.value == "seven"
46
+ assert s.n == 3
47
+ assert t.value == "one"
48
+ assert t.n == 5
49
+
50
+ test "two type parameters, a nested generic field and a list of them"
51
+ p := Pair2(a: 1, b: "b", hits: 0).hit().hit()
52
+ assert p.hits == 2
53
+ assert p.b == "b"
54
+ h := Holder(box: Box(value: 2, n: 0), tag: "h")
55
+ h2 := h.step().step()
56
+ assert h2.box.n == 2
57
+ assert h.box.n == 0
58
+ xs := [Box(value: 1, n: 0), Box(value: 2, n: 10)]
59
+ ys := bumpAll(xs)
60
+ assert ys.at(1).n == 11
61
+ assert xs.at(1).n == 10