plum

#treesitter#compiler#wasm

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

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


b29f849 — Peter John 2026-11-07T02:24:39+05:30
Simpler language: key the proof and purity by receiver type
compiler/checker/src/callcheck.rs CHANGED
@@ -457,6 +457,7 @@ pub(crate) fn inferOperatorCall(
457
457
  line: 0,
458
458
  column: 0,
459
459
  tail: ast::TailKind::NotTail,
460
+ recv: None,
460
461
  })
461
462
  })
462
463
  .clone()
compiler/core/src/ast.rs CHANGED
@@ -961,6 +961,11 @@ pub struct FnCall {
961
961
  pub column: usize,
962
962
  /// Set by `tail::markTailCalls`: whether (and how) this call is in tail position.
963
963
  pub tail: TailKind,
964
+ /// The type name of a method call's receiver, as the checker saw it, when it is one named
965
+ /// type at every instance of the call (`Ship` for `ship.update(dt)`). Set by
966
+ /// `closure_spec::stampReceivers` before the optimisation passes; the stamp travels with the
967
+ /// call when a pass copies or inlines it. `None` when unknown (or not a method call).
968
+ pub recv: Option<String>,
964
969
  }
965
970
 
966
971
  /// How a call in tail position is made (see `tail.rs`). `NotTail` is the default.
compiler/core/src/closure_spec.rs CHANGED
@@ -48,6 +48,33 @@ pub fn methodSites(src: &Source) -> Vec<((String, usize, usize, String), NodeId)
48
48
  out
49
49
  }
50
50
 
51
+ /// Records on each method call the receiver type the checker saw (`FnCall.recv`), so the
52
+ /// analyses after it resolve `x.m()` to `Type.m` instead of to every method named `m`. A call
53
+ /// the hints do not cover (several receiver types, a synthetic call with no position) stays
54
+ /// unstamped and keeps resolving by name.
55
+ pub fn stampReceivers(src: &mut Source, hints: &Hints) {
56
+ for item in &mut src.items {
57
+ let Item::Fn(f) = item else { continue };
58
+ let file = f.file.clone();
59
+ let mut cb = |e: &mut Expr| {
60
+ if let ExprKind::Attribute(a) = &mut e.kind {
61
+ if let AttrKind::Method(c) = &mut a.attr {
62
+ if c.line == 0 {
63
+ return;
64
+ }
65
+ let key = (file.clone(), c.line, c.column, baseName(&c.name).to_string());
66
+ c.recv = hints.get(&key).cloned();
67
+ }
68
+ }
69
+ };
70
+ match &mut f.body {
71
+ FnBody::Expr(e) => visitExpr(e, &mut cb),
72
+ FnBody::Block(b) => visitBlock(b, &mut cb),
73
+ FnBody::Extern => {}
74
+ }
75
+ }
76
+ }
77
+
51
78
  fn baseName(n: &str) -> &str {
52
79
  n.split('$').next().unwrap_or(n)
53
80
  }
compiler/core/src/ctors.rs CHANGED
@@ -332,6 +332,7 @@ pub fn lowerCtors(source: &mut Source) -> Vec<String> {
332
332
  line: line,
333
333
  column: column,
334
334
  tail: TailKind::NotTail,
335
+ recv: None,
335
336
  }),
336
337
  })),
337
338
  0,
@@ -444,6 +445,7 @@ fn rewriteCall(e: &mut Expr, plans: &HashMap<String, Plan>, errors: &mut Vec<Str
444
445
  line: 0,
445
446
  column: 0,
446
447
  tail: TailKind::NotTail,
448
+ recv: None,
447
449
  })
448
450
  .at(e);
449
451
  }
compiler/core/src/drive.rs CHANGED
@@ -367,6 +367,7 @@ impl Tcx {
367
367
  line: 0,
368
368
  column: 0,
369
369
  tail: TailKind::NotTail,
370
+ recv: None,
370
371
  }),
371
372
  }))
372
373
  } else if let Some(t) = &self.callee.type_param {
@@ -378,6 +379,7 @@ impl Tcx {
378
379
  line: 0,
379
380
  column: 0,
380
381
  tail: TailKind::NotTail,
382
+ recv: None,
381
383
  }),
382
384
  }))
383
385
  } else {
@@ -387,6 +389,7 @@ impl Tcx {
387
389
  line: 0,
388
390
  column: 0,
389
391
  tail: TailKind::NotTail,
392
+ recv: None,
390
393
  })
391
394
  }
392
395
  }
@@ -1101,6 +1104,7 @@ impl Driver {
1101
1104
  line: 0,
1102
1105
  column: 0,
1103
1106
  tail: TailKind::NotTail,
1107
+ recv: None,
1104
1108
  });
1105
1109
  return true;
1106
1110
  }
@@ -1886,6 +1890,7 @@ impl Driver {
1886
1890
  line: 0,
1887
1891
  column: 0,
1888
1892
  tail: TailKind::NotTail,
1893
+ recv: None,
1889
1894
  }));
1890
1895
  self.origins.insert(name.clone(), anc);
1891
1896
  self.fused.push(f);
compiler/core/src/forms.rs CHANGED
@@ -181,7 +181,7 @@ pub fn forStmt(binders: Vec<String>, source: Expr, sourceText: String, body: Blo
181
181
 
182
182
  fn loopStmt(name: &str, rest: Vec<Expr>, line: usize, column: usize) -> Stmt {
183
183
  let args = std::iter::once(Expr::Int(0)).chain(rest).map(Arg::Positional).collect();
184
- Stmt::Expr(Expr::FnCall(FnCall { name: name.to_string(), args, line, column, tail: TailKind::NotTail }), line, column)
184
+ Stmt::Expr(Expr::FnCall(FnCall { name: name.to_string(), args, line, column, tail: TailKind::NotTail, recv: None }), line, column)
185
185
  }
186
186
 
187
187
  /// The loop a statement is, if it is one.
@@ -300,6 +300,7 @@ fn method(obj: &str, name: &str, args: Vec<Expr>) -> Expr {
300
300
  line: 0,
301
301
  column: 0,
302
302
  tail: TailKind::NotTail,
303
+ recv: None,
303
304
  }),
304
305
  }))
305
306
  }
@@ -501,6 +502,7 @@ fn callOf(name: &str, args: Vec<Expr>, line: usize, column: usize) -> Stmt {
501
502
  line: 0,
502
503
  column: 0,
503
504
  tail: TailKind::NotTail,
505
+ recv: None,
504
506
  }),
505
507
  line,
506
508
  column,
compiler/core/src/parser.rs CHANGED
@@ -1422,6 +1422,7 @@ impl<'a> AstParser<'a> {
1422
1422
  line: pos.row + 1,
1423
1423
  column: pos.column + 1,
1424
1424
  tail: TailKind::NotTail,
1425
+ recv: None,
1425
1426
  })
1426
1427
  }
1427
1428
  None => AttrKind::Field(member),
@@ -1454,6 +1455,7 @@ impl<'a> AstParser<'a> {
1454
1455
  line,
1455
1456
  column,
1456
1457
  tail: TailKind::NotTail,
1458
+ recv: None,
1457
1459
  }),
1458
1460
  }))
1459
1461
  };
@@ -1534,6 +1536,7 @@ impl<'a> AstParser<'a> {
1534
1536
  line: pos.row + 1,
1535
1537
  column: pos.column + 1,
1536
1538
  tail: TailKind::NotTail,
1539
+ recv: None,
1537
1540
  }
1538
1541
  }
1539
1542
 
@@ -1571,6 +1574,7 @@ impl<'a> AstParser<'a> {
1571
1574
  line: pos.row + 1,
1572
1575
  column: pos.column + 1,
1573
1576
  tail: TailKind::NotTail,
1577
+ recv: None,
1574
1578
  }))
1575
1579
  }
1576
1580
  _ => {
compiler/core/src/purity.rs CHANGED
@@ -8,7 +8,8 @@
8
8
  //! So is `x.f(..)` where `f` may be an fn-typed field. A method call on `self`, on a
9
9
  //! parameter of a named type (never rebound or shadowed) or on a field read of one
10
10
  //! resolves by that type (`io.clear(..)` is `Io.clear`, not `Slice.clear`): to the type's
11
+ //! method. The checker's receiver type, when the driver stamped it on the call (`FnCall.recv`),
11
- //! method.
12
+ //! wins over this syntactic guess and covers every receiver, not just those three shapes.
12
13
  //! A method call whose receiver type is unknown is pure only if every method of that name
13
14
  //! is. Solved as a greatest fixpoint, so (mutual) recursion with no impure effect stays pure.
14
15
  use crate::ast::*;
@@ -501,7 +502,7 @@ impl<'a> Walker<'a> {
501
502
  match &a.object.kind {
502
503
  // `Color.White.withAlpha(..)`: a method on a constant, not a static call
503
504
  ExprKind::TypeName(t) if !t.contains('.') => self.calls.push(Call::Static(format!("{}.{}", t, c.name))),
504
- _ => match self.receiverType(&a.object).map(str::to_string) {
505
+ _ => match c.recv.clone().or_else(|| self.receiverType(&a.object).map(str::to_string)) {
505
506
  // `x.f(..)` where no method of the receiver's type wins over an
506
507
  // fn-typed field `f`: a closure call
507
508
  t if self.receivers.fnFields.contains(c.name.as_str())
compiler/core/src/reuse.rs CHANGED
@@ -73,8 +73,12 @@ struct Cand {
73
73
  pub fn markReuse(src: &mut Source) -> Vec<String> {
74
74
  let mut nameCount: HashMap<String, usize> = HashMap::new();
75
75
  for it in &src.items {
76
+ // Only free fns count: a method of any type with the same name is never what `f(..)` calls,
77
+ // and a method call is told apart below by the receiver type the checker saw.
76
78
  if let Item::Fn(f) = it {
79
+ if f.type_param.is_none() {
77
- *nameCount.entry(f.name.clone()).or_default() += 1;
80
+ *nameCount.entry(f.name.clone()).or_default() += 1;
81
+ }
78
82
  }
79
83
  }
80
84
  // Candidate fns.
@@ -149,7 +153,10 @@ pub fn markReuse(src: &mut Source) -> Vec<String> {
149
153
  ExprKind::Var(n) if *n == fname => ok[ci] = false,
150
154
  ExprKind::Attribute(a) => {
151
155
  if let AttrKind::Method(mc) = &a.attr {
156
+ // A method call on a receiver of known type is never a call of the free fn
157
+ // (a `Type.f(..)` call has a type name as its object and is not told apart).
158
+ let typed = mc.recv.is_some() && !matches!(a.object.kind, ExprKind::TypeName(_));
152
- if mc.name == fname {
159
+ if mc.name == fname && !typed {
153
160
  ok[ci] = false;
154
161
  }
155
162
  }
compiler/core/src/uniqueness.rs CHANGED
@@ -351,6 +351,8 @@ struct Unit {
351
351
  method: bool,
352
352
  hasSelf: bool,
353
353
  name: String,
354
+ /// The type a method is declared under.
355
+ ty: Option<String>,
354
356
  params: Vec<UParam>,
355
357
  block: Block,
356
358
  }
@@ -460,7 +462,7 @@ impl An {
460
462
  ExprKind::FnCall(c) => self.isFree(&c.name).is_some_and(|g| self.fresh_ret.borrow().contains(&g)),
461
463
  ExprKind::Attribute(a) => match &a.attr {
462
464
  AttrKind::Method(c) => {
463
- let cands = self.cands(&c.name);
465
+ let cands = self.cands(c);
464
466
  !cands.is_empty() && cands.iter().all(|g| self.fresh_ret.borrow().contains(g))
465
467
  }
466
468
  _ => false,
@@ -469,8 +471,16 @@ impl An {
469
471
  }
470
472
  }
471
473
 
474
+ /// The methods a call `x.m(..)` may run. With the receiver's type known (`FnCall.recv`, set
475
+ /// from the checker's types) that is `Type.m` alone, and nothing when the type declares no
476
+ /// such method (a builtin: the call is not a direct call of known fns). Otherwise every
477
+ /// method named `m`.
472
- fn cands(&self, name: &str) -> &[usize] {
478
+ fn cands(&self, c: &FnCall) -> Vec<usize> {
473
- self.methodIdx.get(name).map(|v| v.as_slice()).unwrap_or(&[])
479
+ let all = self.methodIdx.get(&c.name).map(|v| v.as_slice()).unwrap_or(&[]);
480
+ match &c.recv {
481
+ Some(t) => all.iter().copied().filter(|&g| self.units[g].ty.as_deref() == Some(t.as_str())).collect(),
482
+ None => all.to_vec(),
483
+ }
474
484
  }
475
485
 
476
486
  /// The arguments of a call of `g`, one per parameter (`None` = defaulted or missing).
@@ -511,7 +521,7 @@ impl An {
511
521
  ExprKind::Attribute(a) => {
512
522
  let AttrKind::Method(c) = &a.attr else { return None };
513
523
  let isType = matches!(a.object.kind, ExprKind::TypeName(_));
514
- let cands = self.cands(&c.name);
524
+ let cands = self.cands(c);
515
525
  if cands.is_empty() || cands.iter().any(|&g| self.units[g].hasSelf == isType) {
516
526
  return None;
517
527
  }
@@ -877,7 +887,7 @@ impl<'a> Scan<'a> {
877
887
  /// to every method named `m`, so all of them must take that parameter uniquely.
878
888
  fn methodCall(&mut self, a: &AttributeExpr, c: &FnCall, tail: bool, ab: bool) {
879
889
  let v = self.v.to_string();
880
- let cands: Vec<usize> = self.an.cands(&c.name).to_vec();
890
+ let cands: Vec<usize> = self.an.cands(c);
881
891
  let recvBare = self.bare(&a.object);
882
892
  let bareCount = recvBare as usize + c.args.iter().filter(|x| self.bare(argExpr(x))).count();
883
893
  let handOver = |s: &Scan, k: Option<usize>| -> bool {
@@ -1134,6 +1144,7 @@ fn build(src: &Source) -> An {
1134
1144
  method: f.type_param.is_some() && !f.is_export,
1135
1145
  hasSelf: f.has_self,
1136
1146
  name: f.name.clone(),
1147
+ ty: f.type_param.clone(),
1137
1148
  params: f
1138
1149
  .has_self
1139
1150
  .then(|| UParam { name: "self".into(), plain: true, default: None })
@@ -1155,6 +1166,7 @@ fn build(src: &Source) -> An {
1155
1166
  method: false,
1156
1167
  hasSelf: false,
1157
1168
  name: String::new(),
1169
+ ty: None,
1158
1170
  params: vec![],
1159
1171
  block: t.body.clone(),
1160
1172
  }),
@@ -1166,6 +1178,7 @@ fn build(src: &Source) -> An {
1166
1178
  method: false,
1167
1179
  hasSelf: false,
1168
1180
  name: String::new(),
1181
+ ty: None,
1169
1182
  params: vec![],
1170
1183
  block: Block { stmts: vec![Stmt::Expr(c.value.clone(), 0, 0)] },
1171
1184
  }),
@@ -1371,7 +1384,7 @@ fn readOnlySelf(an: &An) -> HashSet<usize> {
1371
1384
  allowed.insert(a.object.id);
1372
1385
  }
1373
1386
  AttrKind::Method(c) => {
1374
- let cands = an.cands(&c.name);
1387
+ let cands = an.cands(c);
1375
1388
  if !cands.is_empty() && cands.iter().all(|x| ro.contains(x)) {
1376
1389
  allowed.insert(a.object.id);
1377
1390
  }
@@ -1586,7 +1599,7 @@ fn collectFacts(an: &mut An) {
1586
1599
  ExprKind::Attribute(x) => {
1587
1600
  if let AttrKind::Method(c) = &x.attr {
1588
1601
  let isType = matches!(x.object.kind, ExprKind::TypeName(_));
1589
- for &g in a.cands(&c.name) {
1602
+ for g in a.cands(c) {
1590
1603
  let u = &a.units[g];
1591
1604
  if u.hasSelf == isType {
1592
1605
  escaped.insert(g);
@@ -1634,7 +1647,7 @@ fn collectFacts(an: &mut An) {
1634
1647
  }
1635
1648
  // `x.f.m(..)` with every `m` reading its receiver only: `x.f` is not shared.
1636
1649
  if let ExprKind::Attribute(i) = &x.object.kind {
1637
- let cands = a.cands(&c.name);
1650
+ let cands = a.cands(c);
1638
1651
  if matches!(i.attr, AttrKind::Field(_))
1639
1652
  && !cands.is_empty()
1640
1653
  && cands.iter().all(|g| a.ro.contains(g))
compiler/driver/src/lib.rs CHANGED
@@ -95,6 +95,10 @@ pub fn fusionRun(copy: &mut Source, fbip: bool) -> (Vec<String>, Vec<Diagnostic>
95
95
  }
96
96
 
97
97
  fn fusion(copy: &mut Source, env: &Env) -> bool {
98
+ // The checker's receiver types go onto the method calls first: purity and the uniqueness
99
+ // proof then resolve `x.m()` to `Type.m`, and the stamp travels with the call when drive
100
+ // inlines or copies it.
101
+ plum_core::closure_spec::stampReceivers(copy, env.hints);
98
102
  let (notes, errors) = fusionRun(copy, env.fbip);
99
103
  env.errors.borrow_mut().extend(errors);
100
104
  if env.explain {
@@ -114,7 +118,7 @@ fn trmc(copy: &mut Source, _: &Env) -> bool {
114
118
  /// program) run last and need no re-check.
115
119
  pub const PASSES: [Pass; 3] = [
116
120
  Pass { name: "closure specialisation", target: Target::Pre, needsHints: true, enabled: |o| o.closureSpec, rewrite: closureSpec },
117
- Pass { name: "fusion", target: Target::Pre, needsHints: false, enabled: |o| o.fusion, rewrite: fusion },
121
+ Pass { name: "fusion", target: Target::Pre, needsHints: true, enabled: |o| o.fusion, rewrite: fusion },
118
122
  Pass { name: "trmc", target: Target::Lowered, needsHints: false, enabled: |o| o.trmc, rewrite: trmc },
119
123
  ];
120
124
 
compiler/driver/tests/driver_tests.rs CHANGED
@@ -125,3 +125,116 @@ fn aTypeErrorInAForSourceIsReportedNotAHiddenLoop() {
125
125
  assert!(errs.iter().any(|e| e.message.contains("undefined name 'undefinedThing'")), "{errs:?}");
126
126
  assert!(!errs.iter().any(|e| e.message.contains("cannot turn this loop")), "{errs:?}");
127
127
  }
128
+
129
+ // ---- proof by receiver type ----
130
+
131
+ /// Is the spread in `Type.method` (or free fn `method` when `ty` is empty) marked in place?
132
+ fn spreadInPlace(info: &plum_checker::TypedInfo, ty: &str, method: &str) -> bool {
133
+ use plum_core::ast::{ExprKind, FnBody};
134
+ let lowered = info.lowered.as_ref().expect("lowered");
135
+ let mut found = false;
136
+ for item in &lowered.items {
137
+ let Item::Fn(f) = item else { continue };
138
+ if f.name != method || f.type_param.as_deref().unwrap_or("") != ty {
139
+ continue;
140
+ }
141
+ let mut cb = |e: &plum_core::ast::Expr| {
142
+ if let ExprKind::ClassCall(c) = &e.kind {
143
+ if c.spread.is_some() && c.unique {
144
+ found = true;
145
+ }
146
+ }
147
+ };
148
+ match &f.body {
149
+ FnBody::Expr(e) => plum_core::visit::walkRef(e, &mut cb),
150
+ FnBody::Block(b) => plum_core::visit::walkBlockRef(b, &mut cb),
151
+ FnBody::Extern => {}
152
+ }
153
+ }
154
+ found
155
+ }
156
+
157
+ const TWO_TYPES: &str = "\
158
+ import std/Int
159
+ import std/Str
160
+
161
+ struct Ship(label: Str, n: Int) =
162
+ fun update(self) -> Ship = Ship(..self, n: self.n + 1)
163
+
164
+ struct Orb(label: Str, n: Int) =
165
+ fun update(self) -> Orb = Orb(..self, n: self.n + 2)
166
+
167
+ fun both(o: Orb) -> Int =
168
+ p := o.update()
169
+ o.n + p.n
170
+
171
+ fun run() -> Int =
172
+ t := Ship(label: \"s\", n: 0).update()
173
+ o := Orb(label: \"o\", n: 0)
174
+ t.n + both(o)
175
+
176
+ fun main() -> Int = run()
177
+ ";
178
+
179
+ /// `Orb.update` is called with a value its caller reads afterwards; `Ship.update` is only ever
180
+ /// called on a fresh one. Same method name, different types: only `Orb.update` copies.
181
+ #[test]
182
+ fn sameNamedMethodsOfTwoTypesAreProvedSeparately() {
183
+ let src = load("drv_two_types", TWO_TYPES);
184
+ let info = check(&src, &PassOptions::default()).expect("checks");
185
+ assert!(spreadInPlace(&info, "Ship", "update"), "Ship.update is only called on fresh values");
186
+ assert!(!spreadInPlace(&info, "Orb", "update"), "Orb.update's receiver is read after the call");
187
+ }
188
+
189
+ /// With the fusion passes off nothing stamps receiver types, and nothing is marked.
190
+ #[test]
191
+ fn noFusionMarksNothing() {
192
+ let src = load("drv_two_types_off", TWO_TYPES);
193
+ let opts = PassOptions { fusion: false, ..PassOptions::default() };
194
+ let info = check(&src, &opts).expect("checks");
195
+ assert!(!spreadInPlace(&info, "Ship", "update"));
196
+ }
197
+
198
+ /// The block-bodied hostile: the shared call is in another type's method of the same name,
199
+ /// reached through a field. It must not make `Ship.update` copy, and must not be proved itself.
200
+ #[test]
201
+ fn aSharedReceiverOfAnotherTypeDoesNotProveItsOwnMethod() {
202
+ let src = load(
203
+ "drv_hostile_names",
204
+ "import std/Int\nimport std/Str\n\
205
+ struct Ship(label: Str, n: Int) =\n fun update(self) -> Ship = Ship(..self, n: self.n + 1)\n\
206
+ struct Orb(label: Str, n: Int) =\n fun update(self) -> Orb = Orb(..self, n: self.n + 2)\n\
207
+ struct Pair2(a: Orb, b: Orb)\n\
208
+ fun twice(o: Orb) -> Pair2 = Pair2(a: o.update(), b: o)\n\
209
+ fun main() -> Int =\n s := Ship(label: \"s\", n: 0).update()\n p := twice(Orb(label: \"o\", n: 0))\n s.n + p.a.n + p.b.n\n",
210
+ );
211
+ let info = check(&src, &PassOptions::default()).expect("checks");
212
+ assert!(spreadInPlace(&info, "Ship", "update"));
213
+ assert!(!spreadInPlace(&info, "Orb", "update"), "`o` is stored in `b` as well");
214
+ }
215
+
216
+ /// Purity keys a method by the receiver's type: `Orb.bump` writes a field of its argument, so it
217
+ /// is impure, but `Ship.bump` is pure and `viaShip`, which only calls `Ship.bump` on a constructed receiver
218
+ /// (no parameter to read its type from), stays pure.
219
+ #[test]
220
+ fn purityResolvesAMethodByItsReceiverType() {
221
+ let src = load(
222
+ "drv_purity_types",
223
+ "import std/Int\n\
224
+ struct Ship(x: Int) =\n fun bump(self, k: Int) -> Int = self.x + k\n\
225
+ struct Orb(mut x: Int) =\n fun bump(self, k: Int) -> Int =\n self.x = self.x + k\n self.x\n\
226
+ fun viaShip(k: Int) -> Int = Ship(x: k).bump(1)\n\
227
+ fun viaOrb(k: Int) -> Int = Orb(x: k).bump(1)\n\
228
+ fun main() -> Int = viaShip(1) + viaOrb(1)\n",
229
+ );
230
+ let opts = PassOptions { closureSpec: false, fusion: false, trmc: false, fbip: false, explain: false };
231
+ let info = check(&src, &opts).expect("checks");
232
+ let mut lowered = (**info.lowered.as_ref().expect("lowered")).clone();
233
+ let hints = plum_checker::closureHints(&lowered, &info);
234
+ plum_core::closure_spec::stampReceivers(&mut lowered, &hints);
235
+ let pure = plum_core::purity::pureFns(&lowered);
236
+ assert!(pure.contains("Ship.bump"), "{pure:?}");
237
+ assert!(!pure.contains("Orb.bump"), "{pure:?}");
238
+ assert!(pure.contains("viaShip"), "{pure:?}");
239
+ assert!(!pure.contains("viaOrb"), "{pure:?}");
240
+ }
compiler/wasm-codegen/src/construct.rs CHANGED
@@ -248,6 +248,7 @@ pub(crate) fn compileInterpolatedString(
248
248
  line: 0,
249
249
  column: 0,
250
250
  tail: ast::TailKind::NotTail,
251
+ recv: None,
251
252
  };
252
253
  if plum_checker::nominalName(&other)
253
254
  .is_some_and(|n| ctx.func_ids.contains_key(&format!("{}::toStr", n)))
compiler/wasm-codegen/src/expr.rs CHANGED
@@ -462,6 +462,7 @@ pub(crate) fn compileExpr(
462
462
  line: 0,
463
463
  column: 0,
464
464
  tail: ast::TailKind::NotTail,
465
+ recv: None,
465
466
  };
466
467
  compileMethodCall(
467
468
  &object,
docs/plans/2026-11-06-simpler-language.md CHANGED
@@ -191,7 +191,7 @@ e.g. a struct with a method named `push` no longer blocks another type's `push`
191
191
  **Consumes:** the proof and purity key methods by the checker's receiver type, so `Ship.update` and `Orb.update` are separate; struct and enum spreads and reuse prove in the shapes the pilot failed on (T11)
192
192
  **Produces:** a local moved into a field or returned counts as handed over, so `S(..s, ship: s.ship.update(dt))` reuses both when `s` is unique
193
193
  e.g. `--explain-fusion` shows `S(..s, ship: s.ship.update(dt))` in place
194
- **Notes:** With loops gone, these are the shapes that replace `v = v.f()`, and the proof must cover them, found in T9: a rebinding `w := v.f()` where `v` isn't used again; a `fold` accumulator (`xs.fold(s, |acc, x| acc.bump(x))`, including after closure specialisation); a tail-recursive argument (`loop(s.bump(), i + 1)`). At T9 they all copy: `tests/fbip_probes/struct_spread.plum` went from 1 to 8 ms, `slice_shapes` s10 was lost, and some `tests/fbip` aliasing programs now reject by default. Restore them, and record those timings. Last use is flow-sensitive across `if` and `match` branches. A closure capture or a read after the move stays shared.
194
+ **Notes:** With loops gone, these are the shapes that replace `v = v.f()`, and the proof must cover them, found in T9: a rebinding `w := v.f()` where `v` isn't used again; a `fold` accumulator (`xs.fold(s, |acc, x| acc.bump(x))`, including after closure specialisation); a tail-recursive argument (`loop(s.bump(), i + 1)`). At T9 they all copy: `tests/fbip_probes/struct_spread.plum` went from 1 to 8 ms, `slice_shapes` s10 was lost, and some `tests/fbip` aliasing programs now reject by default. Restore them, and record those timings. Also from T11: `State(..s, ship.x: 1)` lowers to `__paN := s.ship`, a non-fresh binding reported as "may be shared", so it copies: when `s` is unique and proved, its field is too, so prove it here. Spreads inside block values are the same case. Non-tail `spin(v.bumped(), i + 1)` isn't proved either. Last use is flow-sensitive across `if` and `match` branches. A closure capture or a read after the move stays shared.
195
195
  **Test code:** hostile programs: read after the move in one branch; move in a nested spread; capture before the move; the same value moved into two fields.
196
196
 
197
197
  ### T13 shared and unique callers · Complexity 7 · Est. context 90k
tests/fbip/receiver_stamps.plum ADDED
@@ -0,0 +1,66 @@
1
+ import std/Int
2
+ import std/List
3
+
4
+ # Same-named methods on two types, reached through generics, closures, fields and loops. The
5
+ # receiver type stamped on a call (by the checker) must never send a call to the wrong type's
6
+ # method: a duck-typed generic receiver varies per instantiation and is left unstamped. The
7
+ # sweep runs this file with the default and with `--no-fbip` / `--no-fusion`.
8
+
9
+ struct Ship(n: Int) =
10
+ fun inplace(self) -> Ship = Ship(..self, n: self.n + 1)
11
+
12
+ struct Orb(n: Int) =
13
+ fun inplace(self) -> Orb = Orb(..self, n: self.n + 2)
14
+
15
+ fun bump[T](x: T) -> T = x.inplace()
16
+ fun via[U](u: U) -> U = bump(u)
17
+ fun keep[T](x: T) -> Pair[T, T] = Pair(x.inplace(), x)
18
+ fun loopAll[T](xs: List[T]) -> List[T] = xs.map(|x| x.inplace())
19
+
20
+ fun both[T](x: T, f: fn(T) -> T) -> Pair[T, T] = Pair(f(x), x)
21
+
22
+ fun viaClosureShip(s: Ship) -> Int =
23
+ p := both(s, |a: Ship| a.inplace())
24
+ p.first.n * 100 + p.second.n
25
+
26
+ fun viaClosureOrb(o: Orb) -> Int =
27
+ p := both(o, |a: Orb| a.inplace())
28
+ p.first.n * 100 + p.second.n
29
+
30
+ struct Holder[T](v: T)
31
+
32
+ fun upd(h: Holder[Ship]) -> Int =
33
+ a := h.v.inplace()
34
+ a.n * 100 + h.v.n
35
+
36
+ fun updO(h: Holder[Orb]) -> Int =
37
+ a := h.v.inplace()
38
+ a.n * 100 + h.v.n
39
+
40
+ fun loopy(s: Ship, o: Orb) -> Int =
41
+ 0.until(3).fold(0, |t, i|
42
+ q := s.inplace()
43
+ r := o.inplace()
44
+ t + q.n + r.n + s.n + o.n + i)
45
+
46
+ test "a duck-typed generic receiver is told apart per instantiation"
47
+ s := Ship(n: 1)
48
+ o := Orb(n: 1)
49
+ assert via(s).n + s.n == 3
50
+ assert via(o).n + o.n == 4
51
+ k := keep(o)
52
+ assert k.first.n * 100 + k.second.n == 301
53
+ ks := keep(s)
54
+ assert ks.first.n * 100 + ks.second.n == 201
55
+ l := loopAll([s, s])
56
+ assert l.fold(0, |a, x| a + x.n) + s.n == 5
57
+
58
+ test "closures and fields keep the shared receiver intact"
59
+ s := Ship(n: 1)
60
+ o := Orb(n: 1)
61
+ assert viaClosureShip(s) == 201
62
+ assert viaClosureOrb(o) == 301
63
+ assert upd(Holder(v: s)) == 201
64
+ assert updO(Holder(v: o)) == 301
65
+ assert loopy(s, o) == 24
66
+ assert s.n + o.n == 2
tests/fbip/reuse_same_name.plum ADDED
@@ -0,0 +1,39 @@
1
+ # A reuse candidate `inc` shares its name with methods of two types, called on typed receivers.
2
+ # A typed method call is never a call of the free fn; the shared list is never written.
3
+ import std/Int
4
+ import std/Str
5
+
6
+ enum Link =
7
+ | Nil
8
+ | Cons(head: Int, tail: Link)
9
+
10
+ fun inc(xs: Link) -> Link = match xs
11
+ Nil => Nil
12
+ Cons(h, t) => Cons(head: h + 1, tail: inc(t))
13
+
14
+ fun sum(xs: Link) -> Int = match xs
15
+ Nil => 0
16
+ Cons(h, t) => h + sum(t)
17
+
18
+ struct Box(l: Link) =
19
+ fun inc(self) -> Link = self.l
20
+
21
+ enum Other =
22
+ | Alpha
23
+ | Beta(x: Link)
24
+
25
+ fun inc(self) -> Link = match self
26
+ Alpha => Nil
27
+ Beta(x) => x
28
+
29
+ fun go() -> Int =
30
+ shared := Cons(head: 1, tail: Cons(head: 2, tail: Nil))
31
+ b := Box(l: shared)
32
+ a1 := b.inc()
33
+ fresh := inc(Cons(head: 10, tail: Cons(head: 20, tail: Nil)))
34
+ o := Beta(shared)
35
+ k := o.inc()
36
+ sum(a1) * 1000 + sum(fresh) * 100 + sum(shared) * 10 + sum(k)
37
+
38
+ test "a free fn shared in name with methods is still rebuilt in place only when fresh"
39
+ assert go() == 6233
tests/fbip/same_named_methods.plum ADDED
@@ -0,0 +1,66 @@
1
+ import std/Int
2
+ import std/Str
3
+
4
+ # Methods with the same name on different types are proved apart (receiver type by the
5
+ # checker). Each program would give a different answer if the proof of one type's method
6
+ # were taken from another's, or a shared receiver were written in place. The sweep runs this
7
+ # file with the default and with `--no-fbip`.
8
+
9
+ struct Ship(label: Str, n: Int) =
10
+ fun update(self) -> Ship = Ship(..self, n: self.n + 1)
11
+ fun same(self) -> Ship = self
12
+
13
+ struct Orb(label: Str, n: Int) =
14
+ fun update(self) -> Orb = Orb(..self, n: self.n + 2)
15
+ fun same(self) -> Orb = self
16
+
17
+ struct Both(ship: Ship, orb: Orb)
18
+
19
+ # `Ship.update` only ever sees fresh receivers; `Orb.update` is handed one that is read again.
20
+ fun readsAfter(o: Orb) -> Int =
21
+ p := o.update()
22
+ o.n + p.n
23
+
24
+ fun stored(o: Orb) -> Both = Both(ship: Ship(label: "s", n: 0).update(), orb: o.update())
25
+
26
+ fun keeps(o: Orb) -> Pair[Orb, Orb] = Pair(o.update(), o)
27
+
28
+ # The same name on a receiver reached through a field.
29
+ fun viaField(b: Both) -> Int =
30
+ s := b.ship.update()
31
+ o := b.orb.update()
32
+ s.n + o.n + b.ship.n + b.orb.n
33
+
34
+ # A method returning its receiver, called on both types.
35
+ fun passThrough(s: Ship, o: Orb) -> Int =
36
+ a := s.same().update()
37
+ b := o.same().update()
38
+ a.n + b.n + s.n + o.n
39
+
40
+ test "a shared Orb is not updated in place"
41
+ o := Orb(label: "o", n: 10)
42
+ assert readsAfter(o) == 10 + 12
43
+ assert o.n == 10
44
+
45
+ test "a receiver stored next to its update"
46
+ o := Orb(label: "o", n: 1)
47
+ b := stored(o)
48
+ assert b.orb.n == 3
49
+ assert b.ship.n == 1
50
+ assert o.n == 1
51
+ k := keeps(o)
52
+ assert k.first.n == 3
53
+ assert k.second.n == 1
54
+
55
+ test "receivers reached through a field"
56
+ b := Both(ship: Ship(label: "s", n: 5), orb: Orb(label: "o", n: 7))
57
+ assert viaField(b) == 6 + 9 + 5 + 7
58
+ assert b.ship.n == 5
59
+ assert b.orb.n == 7
60
+
61
+ test "pass-through methods"
62
+ s := Ship(label: "s", n: 1)
63
+ o := Orb(label: "o", n: 1)
64
+ assert passThrough(s, o) == 2 + 3 + 1 + 1
65
+ assert s.n == 1
66
+ assert o.n == 1