plum

#treesitter#compiler#wasm

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

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


43aa43c — Peter John 2026-11-07T08:43:30+05:30
Simpler language: write ..self in place, and fix what that exposed
compiler/checker/tests/checker/fip_test.rs CHANGED
@@ -157,3 +157,35 @@ fn not_enforced_without_the_proof() {
157
157
  run("fip_nofusion", body, &PassOptions { fusion: false, ..PassOptions::default() }).expect("--no-fusion: not enforced");
158
158
  assert_eq!(errs("fip_on", body).len(), 1);
159
159
  }
160
+
161
+ // ---- closures that were specialised away ----
162
+
163
+ const FOLD_HEAD: &str = "struct Cl(label: Str, n: Int)\n";
164
+
165
+ /// The fold's closure calls `stepCl`: after specialisation the copy calls it, and the literal left as
166
+ /// an argument never runs.
167
+ #[test]
168
+ fn a_fip_fun_called_from_a_specialised_closure_compiles() {
169
+ let body = format!("{FOLD_HEAD}fip fun stepCl(c: Cl, i: Int) -> Cl = Cl(..c, n: c.n + i)\nfun run(k: Int) -> Cl = 0.until(k).fold(Cl(label: \"a\", n: 0), |acc, i| stepCl(acc, i))\n");
170
+ run("fip_fold_named", &body, &PassOptions::default()).expect("compiles");
171
+ }
172
+
173
+ #[test]
174
+ fn a_spread_in_a_specialised_closure_of_a_fip_fun_compiles() {
175
+ let body = format!("{FOLD_HEAD}fip fun run(k: Int) -> Cl = 0.until(k).fold(Cl(label: \"a\", n: 0), |acc, i| Cl(..acc, n: acc.n + i))\n");
176
+ run("fip_fold_spread", &body, &PassOptions::default()).expect("compiles");
177
+ }
178
+
179
+ /// The value folded over is read after the fold: its spread in the copy can't be in place.
180
+ #[test]
181
+ fn a_spread_in_a_specialised_closure_with_a_shared_seed_is_an_error() {
182
+ let body = format!("{FOLD_HEAD}fip fun run(k: Int, s: Cl) -> Int =\n r := 0.until(k).fold(s, |acc, i| Cl(..acc, n: acc.n + i))\n r.n + s.n\n");
183
+ assert_eq!(errs("fip_fold_shared", &body).len(), 1);
184
+ }
185
+
186
+ /// A closure that stays a real closure (it is stored) is not dead: its call still counts.
187
+ #[test]
188
+ fn a_fip_fun_called_from_a_real_closure_is_an_error() {
189
+ let body = format!("{FOLD_HEAD}fip fun stepCl(c: Cl, i: Int) -> Cl = Cl(..c, n: c.n + i)\nfun run() -> Int =\n f := |acc: Cl, i: Int| stepCl(acc, i)\n a := Cl(label: \"a\", n: 0)\n r := f(a, 1)\n r.n + a.n\n");
190
+ assert_eq!(errs("fip_real_closure", &body).len(), 1);
191
+ }
compiler/cli/tests/cli/no_fbip_test.rs CHANGED
@@ -11,7 +11,7 @@ fn plumBin() -> std::path::PathBuf {
11
11
  path
12
12
  }
13
13
 
14
- const SRC: &str = "import std/Int\nimport std/Str\nimport std/Io\n\nstruct Cell(label: Str, n: Int)\n\nfun bump(c: Cell) -> Cell = Cell(..c, n: c.n + 1)\n\nfun main(io: Io) =\n c := bump(bump(bump(bump(bump(bump(bump(bump(bump(bump(Cell(label: \"c\", n: 0)))))))))))\n io.printLn(\"{c.n}\")\n";
14
+ const SRC: &str = "import std/Int\nimport std/Str\nimport std/Io\n\nstruct Cell(label: Str, n: Int)\n\nfun bump(c: Cell) -> Cell = Cell(..c, n: c.n + 1)\n\nfun main(io: Io) =\n c := 0.until(10).fold(Cell(label: \"c\", n: 0), |cur, i| bump(cur))\n io.printLn(\"{c.n}\")\n";
15
15
 
16
16
  fn run(src: &std::path::Path, flags: &[&str]) -> (String, String) {
17
17
  let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).ancestors().nth(2).unwrap();
compiler/core/src/uniqueness.rs CHANGED
@@ -11,7 +11,8 @@
11
11
  //! is unique when the fn is only ever called directly and
12
12
  //! every call site passes a unique value: a fresh expression, a unique local/param
13
13
  //! handed over as above, or `x.f` in `x.f = g(x.f)` when field `f` is itself unique.
14
+ //! * A field `f` of a type (see `An.ownerOf`: when the owner is not known, of every type that has one)
14
- //! * A field `f` is unique when every write to it is fresh, every read of it is `x.f.h`,
15
+ //! is unique when every write to it is fresh, every read of it is `x.f.h`,
15
16
  //! `x.f.h = ..` or the assign-back argument above, no pattern binds it, and no spread
16
17
  //! that is not itself proved copies it.
17
18
  //!
@@ -325,6 +326,36 @@ pub(crate) fn mutExpr(e: &mut Expr, f: &mut dyn FnMut(&mut Expr)) {
325
326
  }
326
327
  }
327
328
 
329
+ /// True when some field value, evaluated after an earlier overwrite, could observe the overwritten
330
+ /// field of the spread source `src` (a variable, or `self`): any use of `src` other than a read of a
331
+ /// field no earlier named field overwrote. Conservative on purpose (a method call on `src`, passing it
332
+ /// along or capturing it in a closure all count). Such a spread stays a copy.
333
+ pub fn inPlaceHazard(src: &str, fields: &[FieldArg]) -> bool {
334
+ for (i, f) in fields.iter().enumerate().skip(1) {
335
+ let written: Vec<&str> = fields[..i].iter().map(|e| e.name.as_str()).collect();
336
+ let mut uses = 0usize;
337
+ let mut safeReads = 0usize;
338
+ walkExpr(&f.value, &mut |n| {
339
+ if let Node::E(e) = n {
340
+ if isVar(e, src) {
341
+ uses += 1;
342
+ } else if let ExprKind::Attribute(a) = &e.kind {
343
+ if let AttrKind::Field(fname) = &a.attr {
344
+ if isVar(&a.object, src) && !written.contains(&fname.as_str()) {
345
+ safeReads += 1;
346
+ }
347
+ }
348
+ }
349
+ }
350
+ true
351
+ });
352
+ if uses != safeReads {
353
+ return true;
354
+ }
355
+ }
356
+ false
357
+ }
358
+
328
359
  // ---------- units ----------
329
360
 
330
361
  struct UParam {
@@ -332,6 +363,8 @@ struct UParam {
332
363
  /// An ordinary `name: Type` parameter (not fn-typed).
333
364
  plain: bool,
334
365
  default: Option<Expr>,
366
+ /// The declared type's name, unless it is a type parameter.
367
+ ty: Option<String>,
335
368
  }
336
369
 
337
370
  #[derive(PartialEq)]
@@ -401,9 +434,10 @@ struct An {
401
434
  passes: HashMap<usize, Vec<usize>>,
402
435
  /// Field writes `o.f = g(..)` of a returning fn: the `(fn, parameter)` pairs that must stay
403
436
  /// unique and unstored for field `f` to stay unique.
404
- passWrites: Vec<(String, Vec<(usize, usize)>)>,
437
+ passWrites: Vec<(Vec<String>, Vec<(usize, usize)>)>,
405
438
  up: RefCell<HashSet<(usize, usize)>>,
406
439
  upWhy: RefCell<HashMap<(usize, usize), String>>,
440
+ /// Unique fields, as `fieldKey`s.
407
441
  uf: RefCell<HashSet<String>>,
408
442
  cache: RefCell<HashMap<(usize, String, bool, bool), Result<(), String>>>,
409
443
  // static field facts
@@ -414,24 +448,52 @@ struct An {
414
448
  /// Methods whose `self` is only read: used as the object of field reads and field writes, or
415
449
  /// as the receiver of other such methods, never returned, stored, passed on or captured.
416
450
  ro: HashSet<usize>,
451
+ /// Per unit, the spreads of closures passed to a parameter that is never called (see
452
+ /// `stripDeadFnArgs`): each runs only as a spread of its type in the specialised copies given.
453
+ deadSpreads: Vec<Vec<DeadSpread>>,
417
454
  /// `Array` methods that always return a new array.
418
455
  arrayFresh: HashSet<usize>,
419
456
  /// Reads `o.f` that move field `f` out of `o` while `o`'s one spread overwrites `f` (see
420
457
  /// `collectMoves`), by node id.
421
- moveReads: HashSet<NodeId>,
458
+ moveReads: HashMap<NodeId, String>,
422
- /// `(field, unit, spread node)` per move: the field stays unique only while that spread is proved.
459
+ /// `(field key, unit, spread node)` per move: the field stays unique only while that spread is proved.
423
460
  moves: Vec<(String, usize, NodeId)>,
461
+ /// `(field key, unit, variable)` per `T(f: v)`: the field stays unique only while `v` is proved,
462
+ /// which also means this is `v`'s last use.
463
+ varWrites: Vec<(String, usize, String)>,
464
+ /// `(field key, unit, value)` per `T(f: e)` with any other value that is not plainly fresh: the
465
+ /// field stays unique only while `e` is a value no one else holds (see `freshArg`), such as a
466
+ /// pass-through call handed unique values.
467
+ valueWrites: Vec<(String, usize, Expr)>,
468
+ /// The declaring type of a type or variant name.
469
+ owner: HashMap<String, String>,
470
+ /// The declared type's name of a field, by `fieldKey`; `None` for a type parameter or when the
471
+ /// variants disagree.
472
+ fieldTy: HashMap<String, Option<String>>,
473
+ /// Per unit, what is known of each local and parameter's type.
474
+ varTy: Vec<HashMap<String, Option<String>>>,
475
+ /// Types whose spreads codegen always copies, with the reason: a generic type, and one variant of
476
+ /// an enum (the source's type is the enum, not the variant).
477
+ copyTypes: HashMap<String, String>,
424
478
  /// Variable checks in progress, and whether one of them has been answered by assuming it holds.
425
479
  active: RefCell<HashSet<(usize, String, bool, bool)>>,
426
480
  assumed: std::cell::Cell<bool>,
427
481
  }
428
482
 
483
+ struct DeadSpread {
484
+ span: Span,
485
+ typeName: String,
486
+ copies: Vec<usize>,
487
+ }
488
+
429
489
  struct SpreadSite {
430
490
  unit: usize,
431
491
  node: NodeId,
432
492
  typeName: String,
433
493
  var: Option<String>,
434
494
  given: Vec<String>,
495
+ /// Why the spread copies even with `var` proved (see `An.copyReason`).
496
+ copies: Option<String>,
435
497
  }
436
498
 
437
499
  pub(crate) fn collectTails<'a>(b: &'a Block, out: &mut Vec<&'a Expr>) -> bool {
@@ -458,7 +520,53 @@ pub(crate) fn collectTails<'a>(b: &'a Block, out: &mut Vec<&'a Expr>) -> bool {
458
520
  }
459
521
  }
460
522
 
523
+ /// A field of a declared type, in the tables keyed by field.
524
+ fn fieldKey(owner: &str, f: &str) -> String {
525
+ format!("{owner}.{f}")
526
+ }
527
+
461
528
  impl An {
529
+ /// The declared type of `e` in `unit`, when it can be read off the program: `self`, a parameter
530
+ /// or a local bound once to a constructor, a constructor, and a field of one of those. Anything
531
+ /// else (a call result, a generic field) is unknown, and then the field tables treat a read or
532
+ /// write as touching that field of every type that has one.
533
+ fn ownerOf(&self, unit: usize, e: &Expr) -> Option<String> {
534
+ let known = |t: &str| self.owner.get(t).cloned();
535
+ match &e.kind {
536
+ ExprKind::Self_ => known(self.units[unit].ty.as_deref()?),
537
+ ExprKind::Var(n) => known(self.varTy[unit].get(n)?.as_deref()?),
538
+ ExprKind::ClassCall(c) => known(&c.type_name),
539
+ ExprKind::Attribute(a) => match &a.attr {
540
+ AttrKind::Field(f) => {
541
+ let o = self.ownerOf(unit, &a.object)?;
542
+ known(self.fieldTy.get(&fieldKey(&o, f))?.as_deref()?)
543
+ }
544
+ _ => None,
545
+ },
546
+ _ => None,
547
+ }
548
+ }
549
+
550
+ /// The keys `o.f` may touch: of `o`'s type when known, otherwise of every type with a field `f`.
551
+ fn fieldKeys(&self, unit: usize, o: &Expr, f: &str) -> Vec<String> {
552
+ match self.ownerOf(unit, o) {
553
+ Some(t) => vec![fieldKey(&t, f)],
554
+ None => {
555
+ let mut types: Vec<&String> =
556
+ self.enums.iter().filter(|(k, names)| self.owner.get(*k) == Some(*k) && names.iter().any(|n| n == f)).map(|(k, _)| k).collect();
557
+ types.sort();
558
+ types.into_iter().map(|t| fieldKey(t, f)).collect()
559
+ }
560
+ }
561
+ }
562
+
563
+ /// Is `o.f` unique under every type it may belong to?
564
+ fn fieldUnique(&self, unit: usize, o: &Expr, f: &str) -> bool {
565
+ let keys = self.fieldKeys(unit, o, f);
566
+ let uf = self.uf.borrow();
567
+ !keys.is_empty() && keys.iter().all(|k| uf.contains(k))
568
+ }
569
+
462
570
  fn isFree(&self, name: &str) -> Option<usize> {
463
571
  self.freeIdx.get(name).copied()
464
572
  }
@@ -687,6 +795,15 @@ impl An {
687
795
  Ok(())
688
796
  }
689
797
 
798
+ /// Why a spread of a proved variable still copies, if it does: `--explain-fusion` and `fip fun`
799
+ /// must say what codegen will do.
800
+ fn copyReason(&self, cc: &ClassCall, v: &str) -> Option<String> {
801
+ if let Some(why) = self.copyTypes.get(&cc.type_name) {
802
+ return Some(why.clone());
803
+ }
804
+ inPlaceHazard(v, &cc.fields).then(|| format!("a field value reads `{v}` after an earlier field overwrote it"))
805
+ }
806
+
690
807
  fn spreadProved(&self, s: &SpreadSite) -> bool {
691
808
  match &s.var {
692
809
  Some(v) => self.varOk(s.unit, v).is_ok(),
@@ -706,10 +823,10 @@ impl An {
706
823
  if site.inClosure {
707
824
  return Err("an argument is passed from inside a closure".to_string());
708
825
  }
709
- if self.moveReads.contains(&e.id) {
826
+ if let Some(k) = self.moveReads.get(&e.id) {
710
827
  let ExprKind::Attribute(a) = &e.kind else { unreachable!() };
711
828
  let AttrKind::Field(f) = &a.attr else { unreachable!() };
712
- return if self.uf.borrow().contains(f) { Ok(()) } else { Err(format!("field `{f}` may be shared")) };
829
+ return if self.uf.borrow().contains(k) { Ok(()) } else { Err(format!("field `{f}` may be shared")) };
713
830
  }
714
831
  match &e.kind {
715
832
  ExprKind::Var(_) | ExprKind::Self_ => self.varOk(site.caller, varName(e).unwrap()),
@@ -728,7 +845,7 @@ impl An {
728
845
  if !ok {
729
846
  return Err(format!("field `{f}` is passed on without being written back"));
730
847
  }
731
- if self.uf.borrow().contains(f) {
848
+ if self.fieldUnique(site.caller, &a.object, f) {
732
849
  Ok(())
733
850
  } else {
734
851
  Err(format!("field `{f}` may be shared"))
@@ -750,7 +867,7 @@ impl An {
750
867
  /// the call is its last use (checked by the variable's own scan). `not`: the variable being
751
868
  /// scanned, which cannot vouch for itself here.
752
869
  fn freshArg(&self, unit: usize, e: &Expr, not: Option<&str>) -> bool {
753
- if self.fresh(e) {
870
+ if self.fresh(e) || self.movedField(e) {
754
871
  return true;
755
872
  }
756
873
  if let Some(n) = varName(e) {
@@ -765,10 +882,7 @@ impl An {
765
882
 
766
883
  /// A read `o.f` that moves the field out of `o` (see `collectMoves`), whose field is unique.
767
884
  fn movedField(&self, e: &Expr) -> bool {
768
- if !self.moveReads.contains(&e.id) {
769
- return false;
770
- }
771
- matches!(&e.kind, ExprKind::Attribute(a) if matches!(&a.attr, AttrKind::Field(f) if self.uf.borrow().contains(f)))
885
+ self.moveReads.get(&e.id).is_some_and(|k| self.uf.borrow().contains(k))
772
886
  }
773
887
  }
774
888
 
@@ -1068,7 +1182,15 @@ impl<'a> Scan<'a> {
1068
1182
  None => {}
1069
1183
  }
1070
1184
  for (k, fa) in cc.fields.iter().enumerate() {
1185
+ // A constructor runs its values in declaration order and an in-place spread in
1186
+ // written order, so any other value may run after this one.
1071
- let lv = live || spreadMentions || cc.fields[k + 1..].iter().any(|x| self.mentions(&x.value));
1187
+ let others = cc.fields.iter().enumerate().any(|(i, x)| i != k && self.mentions(&x.value));
1188
+ let lv = live || spreadMentions || others;
1189
+ // The last use of `v`, moved into the field: the object now holds it alone. Whether
1190
+ // that keeps the field unique is `varWrites`' business.
1191
+ if self.bare(&fa.value) && !lv && !self.strict {
1192
+ continue;
1193
+ }
1072
1194
  self.operand(&fa.value, lv, format!("`{v}` is stored in field `{}`", fa.name));
1073
1195
  }
1074
1196
  }
@@ -1150,7 +1272,7 @@ pub fn markUnique(src: &mut Source) -> UniqueReport {
1150
1272
  for s in an.spreads.iter().filter(|s| s.unit == ui) {
1151
1273
  let verdict = match &s.var {
1152
1274
  None => Err("the spread source is not a plain variable".to_string()),
1153
- Some(v) => an.varOk(ui, v),
1275
+ Some(v) => an.varOk(ui, v).and_then(|()| s.copies.clone().map_or(Ok(()), Err)),
1154
1276
  };
1155
1277
  match (&s.var, &verdict) {
1156
1278
  (Some(v), Ok(())) => {
@@ -1165,6 +1287,19 @@ pub fn markUnique(src: &mut Source) -> UniqueReport {
1165
1287
  }
1166
1288
  }
1167
1289
  }
1290
+ // A `fip fun`'s closures that became a specialised copy answer through that copy's spreads.
1291
+ let mut copied: Vec<(usize, Span, Result<(), String>)> = vec![];
1292
+ for (ui, dead) in an.deadSpreads.iter().enumerate().filter(|(ui, _)| isFip(*ui)) {
1293
+ for d in dead {
1294
+ let mut results = an.spreads.iter().filter(|s| d.copies.contains(&s.unit) && s.typeName == d.typeName).map(|s| {
1295
+ let v = s.var.as_deref().ok_or_else(|| "the spread source is not a plain variable".to_string())?;
1296
+ an.varOk(s.unit, v).and_then(|()| s.copies.clone().map_or(Ok(()), Err))
1297
+ });
1298
+ let first = results.next().unwrap_or_else(|| Err("the closure's specialised copy has no such spread".to_string()));
1299
+ let result = std::iter::once(first).chain(results).find(|r| r.is_err()).unwrap_or(Ok(()));
1300
+ copied.push((ui, d.span, result));
1301
+ }
1302
+ }
1168
1303
  // Mutable pass.
1169
1304
  for (ui, u) in an.units.iter().enumerate() {
1170
1305
  if u.kind == Kind::Const {
@@ -1177,7 +1312,7 @@ pub fn markUnique(src: &mut Source) -> UniqueReport {
1177
1312
  let ExprKind::ClassCall(c) = &mut e.kind else { return };
1178
1313
  if let Some(s) = &c.spread {
1179
1314
  if let Some(v) = varName(s) {
1180
- if ok.contains(v) && an.varOk(ui, v).is_ok() {
1315
+ if ok.contains(v) && an.varOk(ui, v).is_ok() && an.copyReason(c, v).is_none() {
1181
1316
  c.unique = true;
1182
1317
  }
1183
1318
  }
@@ -1196,6 +1331,9 @@ pub fn markUnique(src: &mut Source) -> UniqueReport {
1196
1331
  let span = spans.get(node).copied().unwrap_or_default();
1197
1332
  report.fipSites.push(SiteVerdict { itemIdx: u.itemIdx, span, what, result: result.clone() });
1198
1333
  }
1334
+ for (_, span, result) in copied.iter().filter(|c| c.0 == ui) {
1335
+ report.fipSites.push(SiteVerdict { itemIdx: u.itemIdx, span: *span, what: "spread", result: result.clone() });
1336
+ }
1199
1337
  }
1200
1338
  report
1201
1339
  }
@@ -1209,6 +1347,67 @@ fn lineOf(src: &Source, u: &Unit) -> usize {
1209
1347
  }
1210
1348
  }
1211
1349
 
1350
+ /// The names that mean a type parameter in `f`: its own, its type's, and any single letter.
1351
+ fn typeParams(f: &Fn, items: &[Item]) -> HashSet<String> {
1352
+ let mut out: HashSet<String> = f.generics.iter().cloned().collect();
1353
+ for item in items {
1354
+ if let Item::Enum(e) = item {
1355
+ if f.type_param.as_deref() == Some(e.name.as_str()) {
1356
+ out.extend(e.generics.iter().map(|g| g.name.clone()));
1357
+ }
1358
+ out.extend(e.variants.iter().flat_map(|v| v.fields.iter()).filter(|t| t.name.len() == 1).map(|t| t.name.clone()));
1359
+ }
1360
+ }
1361
+ out
1362
+ }
1363
+
1364
+ /// What is known of each local and parameter's type (see `An.ownerOf`). A name bound more than once,
1365
+ /// or by a pattern or a closure, is unknown: it may mean different values in different places.
1366
+ fn varTypes(u: &Unit) -> HashMap<String, Option<String>> {
1367
+ let mut out: HashMap<String, Option<String>> = HashMap::new();
1368
+ for p in &u.params {
1369
+ out.insert(p.name.clone(), if p.plain { p.ty.clone().filter(|t| t.len() > 1) } else { None });
1370
+ }
1371
+ walkBlock(&u.block, &mut |n| {
1372
+ match n {
1373
+ Node::S(Stmt { kind: StmtKind::Assign(a), .. }) => {
1374
+ let single = a.declare && a.targets.len() == 1 && a.values.len() == 1;
1375
+ for t in &a.targets {
1376
+ if let AssignTarget::Var(v) = t {
1377
+ let ty = match &a.values[0].kind {
1378
+ ExprKind::ClassCall(c) if single && !out.contains_key(v) => Some(c.type_name.clone()),
1379
+ _ => None,
1380
+ };
1381
+ out.insert(v.clone(), ty);
1382
+ }
1383
+ }
1384
+ }
1385
+ Node::S(Stmt { kind: StmtKind::Match(m), .. }) => {
1386
+ let mut names = vec![];
1387
+ m.cases.iter().flat_map(|c| &c.patterns).for_each(|p| crate::visit::patternBinders(p, &mut names));
1388
+ names.into_iter().for_each(|v| {
1389
+ out.insert(v, None);
1390
+ });
1391
+ }
1392
+ Node::E(Expr { kind: ExprKind::Bind(b), .. }) => {
1393
+ let mut names = vec![];
1394
+ b.case.patterns.iter().for_each(|p| crate::visit::patternBinders(p, &mut names));
1395
+ names.into_iter().for_each(|v| {
1396
+ out.insert(v, None);
1397
+ });
1398
+ }
1399
+ Node::E(Expr { kind: ExprKind::Closure(c), .. }) => {
1400
+ for v in &c.params {
1401
+ out.insert(v.clone(), None);
1402
+ }
1403
+ }
1404
+ _ => {}
1405
+ }
1406
+ true
1407
+ });
1408
+ out
1409
+ }
1410
+
1212
1411
  /// Appended to a name a fn-typed parameter shares with a free fn, in that fn's body only
1213
1412
  /// (see `build`): the renamed name is defined nowhere.
1214
1413
  const SHADOW_MARK: &str = "\u{0}shadow";
@@ -1262,12 +1461,16 @@ fn build(src: &Source) -> An {
1262
1461
  ty: f.type_param.clone(),
1263
1462
  params: f
1264
1463
  .has_self
1265
- .then(|| UParam { name: "self".into(), plain: true, default: None })
1464
+ .then(|| UParam { name: "self".into(), plain: true, default: None, ty: f.type_param.clone() })
1266
1465
  .into_iter()
1267
1466
  .chain(f.params.iter().map(|p| UParam {
1268
1467
  name: p.name.clone(),
1269
1468
  plain: matches!(p.ty, ParamType::Type(_)),
1270
1469
  default: p.default.clone(),
1470
+ ty: match &p.ty {
1471
+ ParamType::Type(t) if !typeParams(f, &src.items).contains(&t.name) => Some(t.name.clone()),
1472
+ _ => None,
1473
+ },
1271
1474
  }))
1272
1475
  .collect(),
1273
1476
  block,
@@ -1366,6 +1569,33 @@ fn build(src: &Source) -> An {
1366
1569
  methodIdx.entry(u.name.clone()).or_default().push(i);
1367
1570
  }
1368
1571
  }
1572
+ let mut copyTypes: HashMap<String, String> = HashMap::new();
1573
+ for item in &src.items {
1574
+ let Item::Enum(e) = item else { continue };
1575
+ if !e.generics.is_empty() {
1576
+ copyTypes.insert(e.name.clone(), format!("`{}` is generic: its spreads copy", e.name));
1577
+ }
1578
+ for v in e.variants.iter().filter(|v| v.name != e.name) {
1579
+ copyTypes.insert(v.name.clone(), format!("`{}` is one variant of `{}`: its spreads copy", v.name, e.name));
1580
+ }
1581
+ }
1582
+ let mut owner: HashMap<String, String> = HashMap::new();
1583
+ let mut fieldTy: HashMap<String, Option<String>> = HashMap::new();
1584
+ for item in &src.items {
1585
+ let Item::Enum(e) = item else { continue };
1586
+ owner.insert(e.name.clone(), e.name.clone());
1587
+ for v in &e.variants {
1588
+ owner.insert(v.name.clone(), e.name.clone());
1589
+ for (t, n) in v.fields.iter().zip(&v.field_names) {
1590
+ let generic = t.name.len() == 1 || e.generics.iter().any(|g| g.name == t.name);
1591
+ let ty = (!generic).then(|| t.name.clone());
1592
+ let key = fieldKey(&e.name, n);
1593
+ let same = fieldTy.get(&key).is_none_or(|old| *old == ty);
1594
+ fieldTy.insert(key, if same { ty } else { None });
1595
+ }
1596
+ }
1597
+ }
1598
+ let varTy: Vec<HashMap<String, Option<String>>> = units.iter().map(varTypes).collect();
1369
1599
  let mut an = An {
1370
1600
  units,
1371
1601
  freeIdx,
@@ -1385,12 +1615,20 @@ fn build(src: &Source) -> An {
1385
1615
  poisonAll: false,
1386
1616
  spreads: vec![],
1387
1617
  ro: HashSet::new(),
1618
+ deadSpreads: vec![],
1388
1619
  arrayFresh: HashSet::new(),
1389
- moveReads: HashSet::new(),
1620
+ moveReads: HashMap::new(),
1390
1621
  moves: vec![],
1622
+ varWrites: vec![],
1623
+ valueWrites: vec![],
1624
+ owner,
1625
+ fieldTy,
1626
+ varTy,
1627
+ copyTypes,
1391
1628
  active: RefCell::new(HashSet::new()),
1392
1629
  assumed: std::cell::Cell::new(false),
1393
1630
  };
1631
+ stripDeadFnArgs(&mut an);
1394
1632
  for (i, u) in an.units.iter().enumerate() {
1395
1633
  match u.label.as_str() {
1396
1634
  "Array.push" | "Array.resize" | "Array.init" | "Array.filled" => {
@@ -1453,8 +1691,19 @@ fn build(src: &Source) -> An {
1453
1691
  }
1454
1692
  true
1455
1693
  });
1694
+ // `if c then a else b` as a result: each branch is a result.
1695
+ let mut flat: Vec<&Expr> = vec![];
1696
+ while let Some(e) = tails.pop() {
1697
+ match &e.kind {
1698
+ ExprKind::InlineIf(i) => {
1699
+ tails.push(&i.then);
1700
+ tails.push(&i.else_);
1701
+ }
1702
+ _ => flat.push(e),
1703
+ }
1704
+ }
1456
1705
  let mut ps: Vec<usize> = vec![];
1457
- for e in tails {
1706
+ for e in flat {
1458
1707
  if an.fresh(e) {
1459
1708
  continue;
1460
1709
  }
@@ -1474,9 +1723,156 @@ fn build(src: &Source) -> An {
1474
1723
  }
1475
1724
  an.passes = passes;
1476
1725
  collectFacts(&mut an);
1726
+ let host = hostShared(&an, src);
1727
+ an.escaped.extend(host);
1477
1728
  an
1478
1729
  }
1479
1730
 
1731
+ /// The fn-typed parameters that do nothing: of specialised copies (`name$cN`, see `closure_spec`),
1732
+ /// never called, and handed on only to other such parameters. A greatest fixpoint, since a recursive
1733
+ /// copy hands the parameter to itself.
1734
+ fn deadFnParams(an: &An) -> HashSet<(usize, usize)> {
1735
+ let mut dead: HashSet<(usize, usize)> = HashSet::new();
1736
+ for (g, u) in an.units.iter().enumerate() {
1737
+ if u.kind == Kind::Fn && u.name.contains("$c") {
1738
+ dead.extend(u.params.iter().enumerate().filter(|(_, p)| !p.plain).map(|(j, _)| (g, j)));
1739
+ }
1740
+ }
1741
+ loop {
1742
+ let mut drop = vec![];
1743
+ for &(g, j) in &dead {
1744
+ let name = &an.units[g].params[j].name;
1745
+ let isP = |n: &str| n == name || n.strip_suffix(SHADOW_MARK) == Some(name.as_str());
1746
+ let (mut mentions, mut forwarded, mut called) = (0usize, 0usize, false);
1747
+ walkBlock(&an.units[g].block, &mut |n| {
1748
+ if let Node::E(e) = n {
1749
+ match &e.kind {
1750
+ ExprKind::Var(x) if isP(x) => mentions += 1,
1751
+ ExprKind::FnCall(c) => {
1752
+ called |= isP(&c.name);
1753
+ forwarded += positional(&c.args)
1754
+ .filter(|(k, x)| varName(x).is_some_and(|v| isP(v)) && argIsDead(an, &dead, e, *k))
1755
+ .count();
1756
+ }
1757
+ ExprKind::Attribute(a) => {
1758
+ if let AttrKind::Method(c) = &a.attr {
1759
+ forwarded += positional(&c.args)
1760
+ .filter(|(k, x)| varName(x).is_some_and(|v| isP(v)) && argIsDead(an, &dead, e, *k))
1761
+ .count();
1762
+ }
1763
+ }
1764
+ _ => {}
1765
+ }
1766
+ }
1767
+ true
1768
+ });
1769
+ if called || mentions != forwarded {
1770
+ drop.push((g, j));
1771
+ }
1772
+ }
1773
+ if drop.is_empty() {
1774
+ return dead;
1775
+ }
1776
+ drop.iter().for_each(|k| {
1777
+ dead.remove(k);
1778
+ });
1779
+ }
1780
+ }
1781
+
1782
+ /// The positional arguments of a call, numbered; a keyword argument ends them.
1783
+ fn positional(args: &[Arg]) -> impl Iterator<Item = (usize, &Expr)> {
1784
+ args.iter().map_while(|a| if let Arg::Positional(x) = a { Some(x) } else { None }).enumerate()
1785
+ }
1786
+
1787
+ /// Does positional argument `k` of call `e` bind a dead parameter of every fn the call may run?
1788
+ fn argIsDead(an: &An, dead: &HashSet<(usize, usize)>, e: &Expr, k: usize) -> bool {
1789
+ match &e.kind {
1790
+ ExprKind::FnCall(c) => an.isFree(&c.name).is_some_and(|g| dead.contains(&(g, k))),
1791
+ ExprKind::Attribute(a) => match &a.attr {
1792
+ AttrKind::Method(c) => {
1793
+ let cands = an.cands(c);
1794
+ !cands.is_empty() && cands.iter().all(|&g| an.units[g].hasSelf && dead.contains(&(g, k + 1)))
1795
+ }
1796
+ _ => false,
1797
+ },
1798
+ _ => false,
1799
+ }
1800
+ }
1801
+
1802
+ /// A specialised call keeps its closure literal as an argument although the copy never calls it. To
1803
+ /// the proof it would look like a real closure: capturing variables, calling fns from inside. The
1804
+ /// proof's own view of the program (`Unit.block`) drops such arguments; what the literal captures is
1805
+ /// passed to the copy as ordinary arguments anyway.
1806
+ fn stripDeadFnArgs(an: &mut An) {
1807
+ let dead = deadFnParams(an);
1808
+ let mut spreads: Vec<Vec<DeadSpread>> = an.units.iter().map(|_| vec![]).collect();
1809
+ let mut blocks: Vec<Block> = an.units.iter().map(|u| u.block.clone()).collect();
1810
+ for (ui, b) in blocks.iter_mut().enumerate() {
1811
+ let out = &mut spreads[ui];
1812
+ mutBlock(b, &mut |e| {
1813
+ let view = e.clone();
1814
+ let copies: Vec<usize> = match &view.kind {
1815
+ ExprKind::FnCall(c) => an.isFree(&c.name).into_iter().collect(),
1816
+ ExprKind::Attribute(a) => match &a.attr {
1817
+ AttrKind::Method(c) => an.cands(c),
1818
+ _ => vec![],
1819
+ },
1820
+ _ => vec![],
1821
+ };
1822
+ let args = match &mut e.kind {
1823
+ ExprKind::FnCall(c) => &mut c.args,
1824
+ ExprKind::Attribute(a) => match &mut a.attr {
1825
+ AttrKind::Method(c) => &mut c.args,
1826
+ _ => return,
1827
+ },
1828
+ _ => return,
1829
+ };
1830
+ for (k, arg) in args.iter_mut().enumerate() {
1831
+ let Arg::Positional(x) = arg else { break };
1832
+ if matches!(x.kind, ExprKind::BoolLit(_)) || !argIsDead(an, &dead, &view, k) {
1833
+ continue;
1834
+ }
1835
+ walkExpr(x, &mut |n| {
1836
+ if let Node::E(Expr { kind: ExprKind::ClassCall(c), span, .. }) = n {
1837
+ if c.spread.is_some() {
1838
+ out.push(DeadSpread { span: *span, typeName: c.type_name.clone(), copies: copies.clone() });
1839
+ }
1840
+ }
1841
+ true
1842
+ });
1843
+ x.kind = ExprKind::BoolLit(true);
1844
+ }
1845
+ });
1846
+ }
1847
+ for (u, b) in an.units.iter_mut().zip(blocks) {
1848
+ u.block = b;
1849
+ }
1850
+ an.deadSpreads = spreads;
1851
+ }
1852
+
1853
+ /// The frame entry points of a game have no call site: the host calls them, so their parameters
1854
+ /// look unique for want of a caller. `gameDraw`'s never is: the host keeps the state for the next
1855
+ /// frame. `gameUpdate`'s is unique only when each state the host can hold is unshared, since the
1856
+ /// host gives up the old state for `update`'s result: `main`'s result and every result of the game's
1857
+ /// `update` must be fresh, or `update`'s own `self`. Returns the entry points to treat as escaped.
1858
+ fn hostShared(an: &An, src: &Source) -> Vec<usize> {
1859
+ let find = |name: &str| an.units.iter().position(|u| u.kind == Kind::Fn && u.free && u.name == name);
1860
+ let mut out: Vec<usize> = find(crate::game_entry::GAME_DRAW).into_iter().collect();
1861
+ let Some(gu) = find(crate::game_entry::GAME_UPDATE) else { return out };
1862
+ let ty = match &src.items[an.units[gu].itemIdx] {
1863
+ Item::Fn(f) => f.returns.as_ref().map(|t| t.name.clone()),
1864
+ _ => None,
1865
+ };
1866
+ let update = an.units.iter().position(|u| u.method && u.name == "update" && u.ty == ty);
1867
+ let fresh = an.fresh_ret.borrow();
1868
+ let mainOk = find("main").is_some_and(|m| fresh.contains(&m));
1869
+ let updateOk = update.is_some_and(|g| fresh.contains(&g) || an.passes.get(&g).is_some_and(|ps| ps == &[0]));
1870
+ if !mainOk || !updateOk {
1871
+ out.push(gu);
1872
+ }
1873
+ out
1874
+ }
1875
+
1480
1876
  /// The key of a node in the analysis tables. Unnumbered (id 0) nodes would all collide.
1481
1877
  fn nodeKey(id: NodeId) -> NodeId {
1482
1878
  assert!(id != NodeId(0), "uniqueness: unnumbered node");
@@ -1497,8 +1893,8 @@ fn nodeKey(id: NodeId) -> NodeId {
1497
1893
  ///
1498
1894
  /// A move is valid while the owner's spread is proved (`solve` drops the field's uniqueness
1499
1895
  /// otherwise), and reading the field anywhere else still makes it shared.
1500
- fn collectMoves(a: &An, _spreads: &[SpreadSite]) -> (HashSet<NodeId>, Vec<(String, usize, NodeId)>) {
1896
+ fn collectMoves(a: &An, _spreads: &[SpreadSite]) -> (HashMap<NodeId, String>, Vec<(String, usize, NodeId)>) {
1501
- let mut reads: HashSet<NodeId> = HashSet::new();
1897
+ let mut reads: HashMap<NodeId, String> = HashMap::new();
1502
1898
  let mut moves: Vec<(String, usize, NodeId)> = vec![];
1503
1899
  for (ui, u) in a.units.iter().enumerate() {
1504
1900
  let mut order = 0usize;
@@ -1627,8 +2023,11 @@ fn collectMoves(a: &An, _spreads: &[SpreadSite]) -> (HashSet<NodeId>, Vec<(Strin
1627
2023
  true
1628
2024
  });
1629
2025
  if let Some(id) = found {
2026
+ // `o` is spread into `cc`, so `cc`'s type owns the field.
2027
+ let Some(t) = a.owner.get(&cc.type_name) else { continue };
2028
+ let key = fieldKey(t, &g);
1630
- reads.insert(id);
2029
+ reads.insert(id, key.clone());
1631
- moves.push((g, ui, *node));
2030
+ moves.push((key, ui, *node));
1632
2031
  }
1633
2032
  }
1634
2033
  }
@@ -1647,8 +2046,10 @@ fn collectMoves(a: &An, _spreads: &[SpreadSite]) -> (HashSet<NodeId>, Vec<(Strin
1647
2046
  if inside == 0 || varCount.get(w) != Some(&inside) {
1648
2047
  continue;
1649
2048
  }
2049
+ let Some(t) = a.owner.get(&cc.type_name) else { continue };
2050
+ let key = fieldKey(t, g);
1650
- reads.insert(*id);
2051
+ reads.insert(*id, key.clone());
1651
- moves.push((g.clone(), ui, *node));
2052
+ moves.push((key, ui, *node));
1652
2053
  }
1653
2054
  }
1654
2055
  (reads, moves)
@@ -1721,8 +2122,10 @@ fn collectFacts(an: &mut An) {
1721
2122
  let mut patternBound: HashSet<String> = HashSet::new();
1722
2123
  let mut poisonAll = false;
1723
2124
  let mut spreads: Vec<SpreadSite> = vec![];
1724
- let mut passWrites: Vec<(String, Vec<(usize, usize)>)> = vec![];
2125
+ let mut passWrites: Vec<(Vec<String>, Vec<(usize, usize)>)> = vec![];
2126
+ let mut varWrites: Vec<(String, usize, String)> = vec![];
2127
+ let mut valueWrites: Vec<(String, usize, Expr)> = vec![];
1725
- let mut reads: Vec<(NodeId, String)> = vec![];
2128
+ let mut reads: Vec<(NodeId, Vec<String>)> = vec![];
1726
2129
  let mut allowed: HashSet<NodeId> = HashSet::new();
1727
2130
  let a: &An = an;
1728
2131
  for (ui, u) in a.units.iter().enumerate() {
@@ -1770,7 +2173,8 @@ fn collectFacts(an: &mut An) {
1770
2173
  if matches!(fp, CasePattern::Name(_)) {
1771
2174
  match names.as_ref().and_then(|n| n.get(i)) {
1772
2175
  Some(f) => {
2176
+ // The pattern names its own type, unless it is unknown here.
1773
- bound.insert(f.clone());
2177
+ bound.insert(fieldKey(an.owner.get(name).map_or(name.as_str(), |t| t.as_str()), f));
1774
2178
  }
1775
2179
  None => {
1776
2180
  // unnamed field of a known type cannot be read as `.f`
@@ -1819,14 +2223,14 @@ fn collectFacts(an: &mut An) {
1819
2223
  + recv.is_some_and(|r| same(r)) as usize;
1820
2224
  if n <= 1 {
1821
2225
  if let Some(deps) = a.passDeps(&asg.values[0], &same) {
1822
- passWrites.push((f.clone(), deps));
2226
+ passWrites.push((a.fieldKeys(ui, o, f), deps));
1823
2227
  passOk = true;
1824
2228
  }
1825
2229
  }
1826
2230
  }
1827
2231
  }
1828
2232
  if !passOk && (!single || !a.fresh(&asg.values[k])) {
1829
- badField.insert(f.clone());
2233
+ badField.extend(a.fieldKeys(ui, o, f));
1830
2234
  }
1831
2235
  if matches!(&o.kind, ExprKind::Attribute(x) if matches!(x.attr, AttrKind::Field(_))) {
1832
2236
  allowed.insert(nodeKey(o.id));
@@ -1871,7 +2275,11 @@ fn collectFacts(an: &mut An) {
1871
2275
  };
1872
2276
  if let Some(nm) = name {
1873
2277
  if !a.fresh(&fa.value) {
2278
+ let key = fieldKey(a.owner.get(&cc.type_name).unwrap_or(&cc.type_name), &nm);
1874
- badField.insert(nm.clone());
2279
+ match varName(&fa.value) {
2280
+ Some(v) => varWrites.push((key, ui, v.to_string())),
2281
+ None => valueWrites.push((key, ui, fa.value.clone())),
2282
+ }
1875
2283
  }
1876
2284
  given.push(nm);
1877
2285
  }
@@ -1883,6 +2291,7 @@ fn collectFacts(an: &mut An) {
1883
2291
  typeName: cc.type_name.clone(),
1884
2292
  var: varName(s).map(|v| v.to_string()),
1885
2293
  given,
2294
+ copies: varName(s).and_then(|v| a.copyReason(cc, v)),
1886
2295
  });
1887
2296
  }
1888
2297
  }
@@ -1947,7 +2356,7 @@ fn collectFacts(an: &mut An) {
1947
2356
  }
1948
2357
  }
1949
2358
  if let AttrKind::Field(f) = &x.attr {
1950
- reads.push((nodeKey(e.id), f.clone()));
2359
+ reads.push((nodeKey(e.id), a.fieldKeys(ui, &x.object, f)));
1951
2360
  }
1952
2361
  // `x.f.h` reads a field of the object in `x.f`: `x.f` itself is not a plain read. (`x.f.m()`
1953
2362
  // hands the field to a method and stays a plain read, so it makes `f` shared.)
@@ -2022,9 +2431,9 @@ fn collectFacts(an: &mut An) {
2022
2431
  }
2023
2432
  }
2024
2433
  let (moveReads, moves) = collectMoves(a, &spreads);
2025
- allowed.extend(moveReads.iter().copied());
2434
+ allowed.extend(moveReads.keys().copied());
2026
2435
  let readsEscape: HashSet<String> =
2027
- reads.into_iter().filter(|(p, _)| !allowed.contains(p)).map(|(_, f)| f).collect();
2436
+ reads.into_iter().filter(|(p, _)| !allowed.contains(p)).flat_map(|(_, f)| f).collect();
2028
2437
  badField.extend(readsEscape);
2029
2438
  an.sites = sites;
2030
2439
  an.escaped = escaped;
@@ -2034,6 +2443,8 @@ fn collectFacts(an: &mut An) {
2034
2443
  an.spreads = spreads;
2035
2444
  an.passWrites = passWrites;
2036
2445
  an.moveReads = moveReads;
2446
+ an.varWrites = varWrites;
2447
+ an.valueWrites = valueWrites;
2037
2448
  an.moves = moves;
2038
2449
  }
2039
2450
 
@@ -2041,8 +2452,10 @@ fn solve(an: &An) {
2041
2452
  // Candidate parameters: plain params of free, non-escaping fns. Candidate fields: all
2042
2453
  // field names not already ruled out.
2043
2454
  let mut allFields: HashSet<String> = HashSet::new();
2044
- for names in an.enums.values() {
2455
+ for (t, names) in &an.enums {
2456
+ if let Some(o) = an.owner.get(t) {
2045
- allFields.extend(names.iter().cloned());
2457
+ allFields.extend(names.iter().map(|f| fieldKey(o, f)));
2458
+ }
2046
2459
  }
2047
2460
  {
2048
2461
  let mut up = an.up.borrow_mut();
@@ -2103,9 +2516,9 @@ fn solve(an: &An) {
2103
2516
  if an.spreadProved(s) {
2104
2517
  continue;
2105
2518
  }
2106
- match fieldsOf(&an.enums, &s.typeName) {
2519
+ match (fieldsOf(&an.enums, &s.typeName), an.owner.get(&s.typeName)) {
2107
- Some(all) => poisoned.extend(all.into_iter().filter(|f| !s.given.contains(f))),
2520
+ (Some(all), Some(o)) => poisoned.extend(all.into_iter().filter(|f| !s.given.contains(f)).map(|f| fieldKey(o, &f))),
2108
- None => {
2521
+ _ => {
2109
2522
  // unknown type: cannot tell which fields it copies
2110
2523
  poisoned.extend(an.uf.borrow().iter().cloned());
2111
2524
  }
@@ -2117,9 +2530,19 @@ fn solve(an: &An) {
2117
2530
  poisoned.insert(f.clone());
2118
2531
  }
2119
2532
  }
2533
+ for (key, ui, v) in &an.varWrites {
2534
+ if an.varOk(*ui, v).is_err() {
2535
+ poisoned.insert(key.clone());
2536
+ }
2537
+ }
2538
+ for (key, ui, e) in &an.valueWrites {
2539
+ if !an.freshArg(*ui, e, None) {
2540
+ poisoned.insert(key.clone());
2541
+ }
2542
+ }
2120
- for (f, deps) in &an.passWrites {
2543
+ for (keys, deps) in &an.passWrites {
2121
2544
  if !deps.iter().all(|&(g, j)| an.passParamOk(g, j)) {
2122
- poisoned.insert(f.clone());
2545
+ poisoned.extend(keys.iter().cloned());
2123
2546
  }
2124
2547
  }
2125
2548
  let removeUf: Vec<String> = an.uf.borrow().iter().filter(|f| poisoned.contains(*f)).cloned().collect();
compiler/core/tests/core/uniqueness_moves_test.rs CHANGED
@@ -208,3 +208,185 @@ fn explain_text_names_the_reason() {
208
208
  let r = run(&format!("{CELL}fun go() -> Int =\n c := mk()\n d := bump(c)\n c.n + d.n\n"));
209
209
  assert!(why(&r, "bump").contains("shared") || why(&r, "bump").contains("used"), "{r:?}");
210
210
  }
211
+
212
+ // ---- what is reported is what codegen does ----
213
+
214
+ #[test]
215
+ fn a_hazard_is_reported_as_a_copy_and_not_marked() {
216
+ let r = run("struct C(a: Int, b: Int) =\n fun peek(self) -> Int = self.a\n fun step(self) -> C = C(..self, a: 1, b: self.peek())\n\
217
+ fun go() -> C = C(a: 0, b: 0).step()\n");
218
+ assert!(!provedFn(&r, "C.step"), "{r:?}");
219
+ assert!(why(&r, "C.step").contains("overwrote"), "{r:?}");
220
+ assert!(!anyMarked(&r), "{r:?}");
221
+ }
222
+
223
+ #[test]
224
+ fn a_generic_spread_is_reported_as_a_copy() {
225
+ let r = run("struct B[T](v: T, n: Int) =\n fun bump(self) -> B[T] = B(..self, n: self.n + 1)\n\
226
+ fun go() -> B[Int] = B(v: 1, n: 0).bump()\n");
227
+ assert!(!provedFn(&r, "B.bump"), "{r:?}");
228
+ assert!(why(&r, "B.bump").contains("generic"), "{r:?}");
229
+ }
230
+
231
+ #[test]
232
+ fn a_variant_spread_is_reported_as_a_copy() {
233
+ let r = run("enum S =\n | Ci(label: Str, r: Int)\n | Sq(label: Str, w: Int)\n\
234
+ fun grow(c: S) -> S = Ci(..c, r: 1)\nfun go() -> S = grow(Ci(label: \"a\", r: 0))\n");
235
+ assert!(!provedFn(&r, "grow"), "{r:?}");
236
+ assert!(why(&r, "grow").contains("variant"), "{r:?}");
237
+ }
238
+
239
+ fn anyMarked(r: &UniqueReport) -> bool {
240
+ !r.proved.is_empty()
241
+ }
242
+
243
+ // ---- a field's proof belongs to its type ----
244
+
245
+ const TWO_OWNERS: &str = "struct Inner(label: Str, n: Int) =\n fun up(self) -> Inner = Inner(..self, n: self.n + 1)\n\
246
+ struct Aa(ship: Inner, k: Int)\nstruct Bb(ship: Inner, k: Int)\n";
247
+
248
+ /// `A.ship` is read as a plain value; `B.ship` is only ever moved. Only `A`'s field is shared.
249
+ #[test]
250
+ fn a_shared_field_of_one_type_leaves_the_same_name_on_another_alone() {
251
+ let body = "fun leak(a: Aa) -> Inner = a.ship\n\
252
+ fun upB(b: Bb) -> Bb = Bb(..b, ship: b.ship.up())\n\
253
+ fun go() -> Bb = upB(Bb(ship: Inner(label: \"x\", n: 0), k: 0))\n\
254
+ fun go2() -> Inner = leak(Aa(ship: Inner(label: \"y\", n: 0), k: 0))\n";
255
+ let r = run(&format!("{TWO_OWNERS}{body}"));
256
+ assert!(provedFn(&r, "upB"), "{r:?}");
257
+ assert!(provedFn(&r, "Inner.up"), "{r:?}");
258
+ }
259
+
260
+ /// A read whose object's type isn't known may be either type's: it poisons the name on both.
261
+ #[test]
262
+ fn a_read_through_an_unknown_type_poisons_every_owner() {
263
+ let body = "fun pick(b: Bb) -> Bb = b\n\
264
+ fun leak(b: Bb) -> Inner = pick(b).ship\n\
265
+ fun upB(b: Bb) -> Bb = Bb(..b, ship: b.ship.up())\n\
266
+ fun go() -> Bb = upB(Bb(ship: Inner(label: \"x\", n: 0), k: 0))\n\
267
+ fun go2() -> Inner = leak(Bb(ship: Inner(label: \"y\", n: 0), k: 0))\n";
268
+ let r = run(&format!("{TWO_OWNERS}{body}"));
269
+ assert!(!provedFn(&r, "Inner.up"), "{r:?}");
270
+ }
271
+
272
+ /// A name a pattern or closure rebinds is not the parameter any more: its type isn't trusted.
273
+ #[test]
274
+ fn a_shadowed_parameter_does_not_give_its_type_to_a_field_read() {
275
+ let body = "fun leak(a: Aa, xs: Bb) -> Inner =\n if a.k > 0\n a := xs\n a.ship\n else\n Inner(label: \"n\", n: 0)\n\
276
+ fun upB(b: Bb) -> Bb = Bb(..b, ship: b.ship.up())\n\
277
+ fun go() -> Bb = upB(Bb(ship: Inner(label: \"x\", n: 0), k: 0))\n";
278
+ let r = run(&format!("{TWO_OWNERS}{body}"));
279
+ assert!(!provedFn(&r, "Inner.up"), "{r:?}");
280
+ }
281
+
282
+ #[test]
283
+ fn a_field_write_of_another_type_does_not_block_this_one() {
284
+ let body = "struct Mc(mut ship: Inner)\nstruct Md(mut ship: Inner)\n\
285
+ fun set(m: Mc, i: Inner) =\n m.ship = i\n\
286
+ fun tick(m: Md) -> Md =\n m.ship = m.ship.up()\n m\n\
287
+ fun go() -> Md = tick(Md(ship: Inner(label: \"x\", n: 0)))\n\
288
+ fun go2() =\n set(Mc(ship: Inner(label: \"x\", n: 0)), Inner(label: \"y\", n: 1))\n";
289
+ let r = run(&format!("{TWO_OWNERS}{body}"));
290
+ assert!(provedFn(&r, "Inner.up"), "{r:?}");
291
+ }
292
+
293
+ // ---- a local moved into a field ----
294
+
295
+ const FIELD: &str = "struct In(label: Str, n: Int) =\n fun up(self) -> In = In(..self, n: self.n + 1)\n\
296
+ struct Out(mut p: In, k: Int)\n\
297
+ fun tick(o: Out) -> Out =\n o.p = o.p.up()\n o\n\
298
+ fun mk() -> In = In(label: \"a\", n: 0)\n";
299
+
300
+ #[test]
301
+ fn a_local_moved_into_a_field_keeps_the_field_unique() {
302
+ let r = run(&format!("{FIELD}fun go() -> Out =\n v := mk()\n tick(Out(p: v, k: 0))\n"));
303
+ assert!(provedFn(&r, "In.up"), "{r:?}");
304
+ }
305
+
306
+ #[test]
307
+ fn a_parameter_moved_into_a_field_needs_every_caller_unique() {
308
+ let r = run(&format!("{FIELD}fun wrap(v: In) -> Out = Out(p: v, k: 0)\nfun go() -> Out = tick(wrap(mk()))\n"));
309
+ assert!(provedFn(&r, "In.up"), "{r:?}");
310
+ let r = run(&format!("{FIELD}fun wrap(v: In) -> Out = Out(p: v, k: 0)\nfun go() -> Int =\n v := mk()\n o := tick(wrap(v))\n o.k + v.n\n"));
311
+ assert!(!provedFn(&r, "In.up"), "{r:?}");
312
+ }
313
+
314
+ #[test]
315
+ fn a_read_after_the_move_into_a_field_stays_shared() {
316
+ let r = run(&format!("{FIELD}fun go() -> Int =\n v := mk()\n o := tick(Out(p: v, k: 0))\n v.n + o.k\n"));
317
+ assert!(!provedFn(&r, "In.up"), "{r:?}");
318
+ }
319
+
320
+ #[test]
321
+ fn the_same_value_moved_into_two_fields_stays_shared() {
322
+ let r = run(&format!("{FIELD}struct Two(mut p: In, q: In)\nfun tock(t: Two) -> Two =\n t.p = t.p.up()\n t\n\
323
+ fun go() -> Two =\n v := mk()\n tock(Two(p: v, q: v))\n"));
324
+ assert!(!provedFn(&r, "In.up"), "{r:?}");
325
+ }
326
+
327
+ #[test]
328
+ fn a_capture_before_the_move_into_a_field_stays_shared() {
329
+ let r = run(&format!("{FIELD}fun go() -> Out =\n v := mk()\n f := || v.n\n o := tick(Out(p: v, k: f()))\n o\n"));
330
+ assert!(!provedFn(&r, "In.up"), "{r:?}");
331
+ }
332
+
333
+ #[test]
334
+ fn a_global_moved_into_a_field_stays_shared() {
335
+ let r = run(&format!("Start = In(label: \"s\", n: 0)\n{FIELD}fun go() -> Out = tick(Out(p: Start, k: 0))\n"));
336
+ assert!(!provedFn(&r, "In.up"), "{r:?}");
337
+ }
338
+
339
+ /// A constructor runs its values in declaration order: `b` first here, whichever is written first.
340
+ #[test]
341
+ fn a_field_written_earlier_may_still_run_after_the_move() {
342
+ let r = run("struct V(label: Str, y: Int)\nstruct Tt(b: V, a: Int)\nfun bump(v: V) -> V = V(..v, y: v.y + 1)\n\
343
+ fun go() -> Tt =\n v := V(label: \"x\", y: 1)\n Tt(a: v.y, b: bump(v))\n");
344
+ assert!(!provedFn(&r, "bump"), "{r:?}");
345
+ }
346
+
347
+ // ---- a pass-through result written into a field ----
348
+
349
+ const THROUGH: &str = "fun touch(c: In) -> In =\n c.label.length()\n c\nfun keep(a: In, b: In) -> In = if a.n > 0 then a else b\n";
350
+
351
+ #[test]
352
+ fn a_pass_through_result_keeps_the_field_unique() {
353
+ let r = run(&format!("{FIELD}{THROUGH}fun go() -> Out =\n v := mk()\n tick(Out(p: touch(v), k: 0))\n"));
354
+ assert!(provedFn(&r, "In.up"), "{r:?}");
355
+ }
356
+
357
+ #[test]
358
+ fn a_pass_through_of_a_value_read_later_stays_shared() {
359
+ let r = run(&format!("{FIELD}{THROUGH}fun go() -> Int =\n v := mk()\n o := tick(Out(p: touch(v), k: 0))\n o.k + v.n\n"));
360
+ assert!(!provedFn(&r, "In.up"), "{r:?}");
361
+ }
362
+
363
+ #[test]
364
+ fn a_pass_through_handed_one_value_twice_stays_shared() {
365
+ let r = run(&format!("{FIELD}{THROUGH}fun go() -> Out =\n v := mk()\n tick(Out(p: keep(v, v), k: 0))\n"));
366
+ assert!(!provedFn(&r, "In.up"), "{r:?}");
367
+ }
368
+
369
+ #[test]
370
+ fn a_pass_through_of_a_global_stays_shared() {
371
+ let r = run(&format!("Start = In(label: \"s\", n: 0)\n{FIELD}{THROUGH}fun go() -> Out = tick(Out(p: touch(Start), k: 0))\n"));
372
+ assert!(!provedFn(&r, "In.up"), "{r:?}");
373
+ }
374
+
375
+ /// `out` returns a field its argument goes on holding: not a pass-through.
376
+ #[test]
377
+ fn a_call_returning_a_field_of_an_argument_stays_shared() {
378
+ let r = run(&format!("{FIELD}struct Holder(i: In)\nfun out(h: Holder) -> In = h.i\nfun go() -> Int =\n h := Holder(i: mk())\n o := tick(Out(p: out(h), k: 0))\n o.k + h.i.n\n"));
379
+ assert!(!provedFn(&r, "In.up"), "{r:?}");
380
+ }
381
+
382
+ /// A struct holding an array, updated in a loop: the struct's own spread is in place (the array
383
+ /// inside it isn't touched, `Array` gets no in-place proof of its own).
384
+ #[test]
385
+ fn a_struct_with_an_array_field_updated_in_a_loop_proves() {
386
+ let vec = "struct Bag(cells: Array[Int], n: Int) =\n fun added(self) -> Bag = Bag(..self, n: self.n + 1)\n\
387
+ fun fill(b: Bag, k: Int) -> Bag = if k == 0 then b else fill(b.added(), k - 1)\n";
388
+ let r = run(&format!("{vec}fun go() -> Bag = fill(Bag(cells: Array.filled(4, 0), n: 0), 3)\n"));
389
+ assert!(provedFn(&r, "Bag.added"), "{r:?}");
390
+ let r = run(&format!("{vec}fun go() -> Int =\n b := Bag(cells: Array.filled(4, 0), n: 0)\n c := fill(b, 3)\n b.n + c.n\n"));
391
+ assert!(!provedFn(&r, "Bag.added"), "{r:?}");
392
+ }
compiler/core/tests/core/uniqueness_test.rs CHANGED
@@ -72,7 +72,7 @@ fn step_called_only_with_unique_args_is_unique() {
72
72
  let s = format!(
73
73
  "{PRE}fun step(s: Pt) -> Pt = Pt(..s, x: s.x + 1)\n\
74
74
  fun tick(w: World) -> World =\n w.s = step(w.s)\n w\n\
75
- fun go() -> Pt = step(step(Pt(x: 0, y: 0)))\n\
75
+ fun go() -> Pt =\n t := Pt(x: 0, y: 0)\n u := step(t)\n step(u)\n\
76
76
  fun mk() -> World = World(s: Pt(x: 0, y: 0), n: 0)\n"
77
77
  );
78
78
  let (src, r) = run(&s);
@@ -159,7 +159,7 @@ fn self_spread_in_method_unique() {
159
159
  let s = "struct Pt(x: Int, y: Int) =\n fun bump(self) -> Pt = Pt(..self, x: self.x + 1)\n\
160
160
  struct World(p: Pt, n: Int)\n\
161
161
  fun tick(w: World) -> World =\n w.p = w.p.bump()\n w\n\
162
- fun go() -> Pt = Pt(x: 0, y: 0).bump().bump()\n\
162
+ fun go() -> Pt =\n t := Pt(x: 0, y: 0)\n u := t.bump()\n u.bump()\n\
163
163
  fun mk() -> World = World(p: Pt(x: 0, y: 0), n: 0)\n";
164
164
  let (src, r) = run(s);
165
165
  assert!(proved(&r, "Pt.bump:2"), "{r:?}");
compiler/driver/tests/driver_tests.rs CHANGED
@@ -213,6 +213,66 @@ fn aSharedReceiverOfAnotherTypeDoesNotProveItsOwnMethod() {
213
213
  assert!(!spreadInPlace(&info, "Orb", "update"), "`o` is stored in `b` as well");
214
214
  }
215
215
 
216
+ // ---- a game's state: the host is the caller the proof cannot see ----
217
+
218
+ /// `Stress.update`'s spread is in place only when no state the host holds can be shared.
219
+ fn gameUpdateInPlace(name: &str, main: &str, update: &str, draw: &str) -> bool {
220
+ let text = format!(
221
+ "module {name}\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\n\
222
+ Start = Stress(label: \"s\", t: 0)\n\
223
+ struct Stress(label: Str, t: Int) =\n \
224
+ fun update(self, io: Io, dt: Float) -> Stress =\n {update}\n \
225
+ fun draw(self, io: Io) =\n {draw}\n\
226
+ fun main(io: Io) -> Stress = {main}\n"
227
+ );
228
+ let mut src = load(name, &text);
229
+ assert!(plum_core::game_entry::lowerGame(&mut src).expect("lowers"), "{name} is a game");
230
+ let info = check(&src, &PassOptions::default()).expect("checks");
231
+ spreadInPlace(&info, "Stress", "update")
232
+ }
233
+
234
+ const FRESH_MAIN: &str = "Stress(label: \"s\", t: 0)";
235
+ const SPREAD_T: &str = "Stress(..self, t: self.t + 1)";
236
+ const DRAW_T: &str = "io.printLn(\"{self.t}\")";
237
+
238
+ #[test]
239
+ fn gameStateFromAFreshMainUpdatesInPlace() {
240
+ assert!(gameUpdateInPlace("g_fresh", FRESH_MAIN, SPREAD_T, DRAW_T));
241
+ }
242
+
243
+ #[test]
244
+ fn gameUpdateReturningSelfStillUpdatesInPlace() {
245
+ assert!(gameUpdateInPlace("g_self", FRESH_MAIN, &format!("if self.t > 9 then self else {SPREAD_T}"), DRAW_T));
246
+ }
247
+
248
+ /// The host would hold the constant itself: writing the state in place would overwrite `Start`.
249
+ #[test]
250
+ fn gameStartingFromAConstantCopies() {
251
+ assert!(!gameUpdateInPlace("g_const", "Start", SPREAD_T, DRAW_T));
252
+ }
253
+
254
+ /// `update` may hand the host the constant on any frame, and the next frame would write into it.
255
+ #[test]
256
+ fn gameUpdateReturningAConstantCopies() {
257
+ assert!(!gameUpdateInPlace("g_reset", FRESH_MAIN, &format!("if self.t > 5 then Start else {SPREAD_T}"), DRAW_T));
258
+ }
259
+
260
+ /// The host reads the state again next frame, so `draw` must not write it, even when it is the
261
+ /// only caller of a method with a spread.
262
+ #[test]
263
+ fn gameDrawNeverWritesTheStateInPlace() {
264
+ let text = "module g_draw\nimport std/Int\nimport std/Float\nimport std/Str\nimport std/Io\n\
265
+ struct Stress(label: Str, t: Int) =\n \
266
+ fun update(self, io: Io, dt: Float) -> Stress = Stress(label: self.label, t: self.t + 1)\n \
267
+ fun later(self) -> Stress = Stress(..self, t: 99)\n \
268
+ fun draw(self, io: Io) =\n x := self.later()\n io.printLn(\"{x.t}\")\n\
269
+ fun main(io: Io) -> Stress = Stress(label: \"s\", t: 0)\n";
270
+ let mut src = load("g_draw", text);
271
+ assert!(plum_core::game_entry::lowerGame(&mut src).expect("lowers"));
272
+ let info = check(&src, &PassOptions::default()).expect("checks");
273
+ assert!(!spreadInPlace(&info, "Stress", "later"));
274
+ }
275
+
216
276
  /// Purity keys a method by the receiver's type: `Orb.bump` writes a field of its argument, so it
217
277
  /// is impure, but `Ship.bump` is pure and `viaShip`, which only calls `Ship.bump` on a constructed receiver
218
278
  /// (no parameter to read its type from), stays pure.
compiler/game/tests/fixtures/state_in_place.plum ADDED
@@ -0,0 +1,25 @@
1
+ module state_in_place
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Str
6
+ import std/game/Color
7
+ import std/game/gfx
8
+ import std/Io
9
+
10
+ struct Part(label: Str, x: Int) =
11
+ fun step(self) -> Part = Part(..self, x: self.x + 1)
12
+
13
+ # `update` writes the state and its field in place; `draw` updates a value of its own, which
14
+ # must not reach the state the host keeps for the next frame.
15
+ struct Run(part: Part, t: Int) =
16
+ fun update(self, io: Io, dt: Float) -> Run =
17
+ Run(..self, part: self.part.step(), t: self.t + 1)
18
+
19
+ fun drawn(self) -> Run = Run(..self, t: 99)
20
+
21
+ fun draw(self, io: Io) =
22
+ d := self.drawn()
23
+ gfx.drawText(io, "{d.t} {self.t} {self.part.x}", 0.0, 0.0, 8.0, Color.White)
24
+
25
+ fun main(io: Io) -> Run = Run(part: Part(label: "p", x: 0), t: 0)
compiler/game/tests/fixtures/state_reset.plum ADDED
@@ -0,0 +1,20 @@
1
+ module state_reset
2
+
3
+ import std/Int
4
+ import std/Float
5
+ import std/Str
6
+ import std/game/Color
7
+ import std/game/gfx
8
+ import std/Io
9
+
10
+ # The state goes back to a constant: writing the state in place would overwrite the constant.
11
+ Start = Run(label: "start", t: 0)
12
+
13
+ struct Run(label: Str, t: Int) =
14
+ fun update(self, io: Io, dt: Float) -> Run =
15
+ if self.t >= 2 then Start else Run(..self, t: self.t + 1)
16
+
17
+ fun draw(self, io: Io) =
18
+ gfx.drawText(io, "{self.t} {Start.t}", 0.0, 0.0, 8.0, Color.White)
19
+
20
+ fun main(io: Io) -> Run = Start
compiler/game/tests/host_test.rs CHANGED
@@ -64,6 +64,39 @@ fn stateSurvivesFrames() {
64
64
  assert_eq!(g.backend().calls.last().unwrap(), "drawText(\"frames 4\",0,0,8,1,1,1,1)");
65
65
  }
66
66
 
67
+ /// The text `draw` shows for each of `frames` frames of a fixture.
68
+ fn framesOf(fixtureFile: &str, frames: usize) -> Vec<String> {
69
+ let wasm = compile(&Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures").join(fixtureFile));
70
+ let mut g = PlumGame::load(&wasm, Recorder::new()).expect("load game");
71
+ g.init().expect("init");
72
+ let mut out = vec![];
73
+ for _ in 0..frames {
74
+ g.backend_mut().calls.clear();
75
+ g.draw().unwrap();
76
+ out.push(g.backend().calls.last().unwrap().split(',').next().unwrap().to_string());
77
+ g.update(0.016).unwrap();
78
+ }
79
+ out
80
+ }
81
+
82
+ /// The host holds whatever `main` and `update` return. A constant handed to it stays a constant.
83
+ #[test]
84
+ fn aStateFromAConstantIsNotWrittenInPlace() {
85
+ assert_eq!(
86
+ framesOf("state_reset.plum", 5),
87
+ ["drawText(\"0 0\"", "drawText(\"1 0\"", "drawText(\"2 0\"", "drawText(\"0 0\"", "drawText(\"1 0\""]
88
+ );
89
+ }
90
+
91
+ /// `update` may write the state; `draw` may not: the host reads the state again after it.
92
+ #[test]
93
+ fn drawLeavesTheStateAlone() {
94
+ assert_eq!(
95
+ framesOf("state_in_place.plum", 3),
96
+ ["drawText(\"99 0 0\"", "drawText(\"99 1 1\"", "drawText(\"99 2 2\""]
97
+ );
98
+ }
99
+
67
100
  #[test]
68
101
  fn missingExportErrors() {
69
102
  let dir = std::env::temp_dir().join(format!("plum_game_missing_{}", std::process::id()));
compiler/wasm-codegen/src/units.rs CHANGED
@@ -152,10 +152,10 @@ impl<'a> TypeCollector<'a> {
152
152
  }
153
153
  }
154
154
 
155
- /// `T(..s, f: v)` where `s` is a plain variable of the same record type `T` proved unique:
155
+ /// `T(..s, f: v)` where `s` is a plain variable or `self`, of the same record type `T`, proved
156
- /// the update is written into `s` (`struct.set` per named field) and `s` is the
156
+ /// unique: the update is written into `s` (`struct.set` per named field) and `s` is the
157
157
  /// result. A value may read a field an earlier one overwrote only if it is not
158
- /// safely ordered (see `inPlaceHazard`), in which case the copy path runs.
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
161
  ctx: &LocalCtx,
@@ -163,8 +163,10 @@ pub(crate) fn spreadInPlace(
163
163
  let Some(sp) = call.spread.as_deref() else {
164
164
  return false;
165
165
  };
166
+ let name = match &sp.kind {
166
- let ast::Expr { kind: ast::ExprKind::Var(name), .. } = sp else {
167
+ ast::ExprKind::Var(n) => n.as_str(),
168
+ ast::ExprKind::Self_ => "self",
167
- return false;
169
+ _ => return false,
168
170
  };
169
171
  if !call.unique {
170
172
  return false;
@@ -172,35 +174,7 @@ pub(crate) fn spreadInPlace(
172
174
  if !matches!(inferLocalType(sp, ctx), PlumType::TNamed(ref n) if *n == call.type_name) {
173
175
  return false;
174
176
  }
175
- !inPlaceHazard(name, &call.fields)
177
+ !plum_core::uniqueness::inPlaceHazard(name, &call.fields)
176
- }
177
-
178
- /// True when some field value, evaluated after an earlier overwrite, could observe
179
- /// the overwritten field of the source: any use of `s` other than a read of a field
180
- /// no earlier named field overwrote. Conservative on purpose (a method call on `s`,
181
- /// passing `s` along or capturing it in a closure all count as hazards).
182
- pub(crate) fn inPlaceHazard(src: &str, fields: &[ast::FieldArg]) -> bool {
183
- for (i, f) in fields.iter().enumerate().skip(1) {
184
- let written: Vec<&str> = fields[..i].iter().map(|e| e.name.as_str()).collect();
185
- let mut uses = 0usize;
186
- let mut safeReads = 0usize;
187
- let mut value = f.value.clone();
188
- plum_core::forms::mapExprsIn(&mut value, &mut |e| match e {
189
- ast::Expr { kind: ast::ExprKind::Var(n), .. } if n == src => uses += 1,
190
- ast::Expr { kind: ast::ExprKind::Attribute(a), .. } => {
191
- if let (ast::Expr { kind: ast::ExprKind::Var(n), .. }, ast::AttrKind::Field(fname)) = (&a.object, &a.attr) {
192
- if n == src && !written.contains(&fname.as_str()) {
193
- safeReads += 1;
194
- }
195
- }
196
- }
197
- _ => {}
198
- });
199
- if uses != safeReads {
200
- return true;
201
- }
202
- }
203
- false
204
178
  }
205
179
 
206
180
  /// The checker's expression types for one unit body (a non-generic fn, or one instantiation).
compiler/wasm-codegen/tests/wasm_codegen/fusion_alloc_test.rs CHANGED
@@ -612,3 +612,45 @@ fun main(io: Io) -> Int =
612
612
  ";
613
613
  sameTrace(types, rest, &[4, 2]);
614
614
  }
615
+
616
+ // ---- `..self` is written in place ----
617
+
618
+ /// Where `main`'s one allocation's type is allocated, in the whole module. Test builds have no
619
+ /// type names, so the type is read off `main`, whose constructor is the only allowed one.
620
+ fn allocsOfMainsType(wasm: &[u8]) -> Vec<String> {
621
+ let fns = functions(wasm);
622
+ let main = fns.iter().find(|f| f.name == "main").expect("main compiled");
623
+ assert_eq!(main.news.len(), 1, "main allocates one object: {:?}", main.news);
624
+ let ty = &main.news[0];
625
+ fns.iter().flat_map(|f| f.news.iter().filter(|a| *a == ty).map(|_| f.name.clone())).collect()
626
+ }
627
+
628
+ const SELF_SPREAD: &str = "struct Ship(label: Str, x: Int, y: Int) =\n \
629
+ fun step(self) -> Ship = Ship(..self, x: self.x + 1)\n\n\
630
+ fun spin(s: Ship, n: Int) -> Ship = if n == 0 then s else spin(s.step(), n - 1)\n\n\
631
+ fun main() -> Int =\n s := spin(Ship(label: \"a\", x: 0, y: 7), 1000)\n s.x + s.y\n";
632
+
633
+ /// A method's `Ship(..self, x: ..)` on a unique receiver writes the object in place: the proof
634
+ /// marks it and codegen must act on `self` as it does on a variable.
635
+ #[test]
636
+ fn self_spread_allocates_nothing_when_unique() {
637
+ let src = load("self_spread_alloc", &format!("{PRE}{SELF_SPREAD}"));
638
+ let wasm = compile(&src, true);
639
+ assert_eq!(allocsOfMainsType(&wasm), ["main"], "only the constructor in `main` allocates a Ship");
640
+ let engine = engine(false);
641
+ assert_eq!(runInt(&engine, &wasm).0, 1007);
642
+ }
643
+
644
+ /// `self` read through a method in a later field after an earlier field was overwritten: the
645
+ /// values must see the old object, so the spread stays a copy.
646
+ #[test]
647
+ fn self_spread_hazard_stays_a_copy() {
648
+ let body = "struct Ship(label: Str, x: Int, y: Int) =\n \
649
+ fun peek(self) -> Int = self.x\n \
650
+ fun step(self) -> Ship = Ship(..self, x: self.x + 1, y: self.peek())\n\n\
651
+ fun main() -> Int =\n s := Ship(label: \"a\", x: 5, y: 0).step()\n s.x * 100 + s.y\n";
652
+ let src = load("self_spread_hazard", &format!("{PRE}{body}"));
653
+ let wasm = compile(&src, true);
654
+ let engine = engine(false);
655
+ assert_eq!(runInt(&engine, &wasm).0, 605);
656
+ }
tests/fbip/fuzz/gen.pl CHANGED
@@ -3,12 +3,16 @@
3
3
  # Locals can't be reassigned, so every statement binds a fresh name (v0, v1, ...
4
4
  # for P values, w0, w1, ... for Q values) built from earlier ones by aliasing,
5
5
  # spreads, method and function calls, `mut` field stores and a Slice. A wrong
6
- # in-place proof shows as a different dump with and without --no-fbip.
6
+ # in-place proof shows as a different dump with and without --no-fbip. A value is
7
+ # only provable at its last use, so most statements use recent values and the
8
+ # dump shows the newest values and a random part of the rest: a value that is
9
+ # dumped is never updated in place.
7
10
  use strict; use warnings;
8
11
  my ($seed, $out) = @ARGV;
9
12
  srand($seed);
10
13
  sub r { return int(rand($_[0])); }
11
14
  sub pick { return $_[r(scalar @_)]; }
15
+ sub recent { return r(2) ? $_[-1 - r(@_ < 2 ? 1 : 2)] : pick(@_); }
12
16
  my @vs = ('v0', 'v1', 'v2');
13
17
  my @ws = ('w0', 'w1');
14
18
  my ($nv, $nw) = (3, 2);
@@ -23,9 +27,9 @@ sub iexpr {
23
27
  }
24
28
  my @stmts;
25
29
  for my $n (1..(6+r(12))) {
26
- my $k = r(42);
30
+ my $k = r(46);
27
31
  my $s;
28
- my $V = pick(@vs); my $V2 = pick(@vs); my $W = pick(@ws);
32
+ my $V = recent(@vs); my $V2 = recent(@vs); my $W = recent(@ws);
29
33
  my ($nvn, $nwn) = ("v$nv", "w$nw");
30
34
  my $isv = 1;
31
35
  if ($k==0) { $s = "$V2"; }
@@ -52,6 +56,9 @@ for my $n (1..(6+r(12))) {
52
56
  elsif ($k==35) { $s = "spin3($V, ".r(3).")"; }
53
57
  elsif ($k==36) { $s = "0.until(".r(4).").fold($V, |acc, i| ".pick("acc.inc()", "P(..acc, a: acc.a + i)", "pass(acc, $V2)", "bump(acc)", "P(..acc, b: acc.a + $V.b)").")"; }
54
58
  elsif ($k==37) { $s = "0.until(".r(4).").fold($W.p, |acc, i| ".pick("acc.inc()", "pass(acc, acc)", "P(..acc, a: i)").")"; }
59
+ elsif ($k==43) { $s = "rtick($V)"; }
60
+ elsif ($k==44) { $s = "rleak(".pick("R(n: $V.a, p: $V)", "R(p: bump($V), n: $V.a)", "R(p: $V, n: 0).tick()").")"; }
61
+ elsif ($k==45) { $s = "0.until(".r(4).").fold($V, |acc, i| ".pick("step2(acc, i)", "step2(acc, $V2.a)").")"; }
55
62
  else { $isv = 0; }
56
63
  if ($isv) { push @stmts, "$nvn := $s"; push @vs, $nvn; $nv++; next; }
57
64
  if ($k==16) { $s = "Q(p: $V, n: ".r(4).")"; }
@@ -65,7 +72,8 @@ for my $n (1..(6+r(12))) {
65
72
  elsif ($k==39) { $s = "Q(..$W, p.a: ".iexpr().")"; }
66
73
  elsif ($k==40) { $s = pick("Q(..$W, n: $W.p.a, p: $W.p.inc())", "Q(..$W, p: $W.p.inc(), n: $W.p.a)", "Q(..$W, p: $W.p.inc(), n: $W.n + 1)", "Q(..$W, p: pass($W.p, $V))"); }
67
74
  elsif ($k==41) { $s = pick("Q(..$W, p.b: $W.p.a)", "Q(..$W, p.a: 1, p.b: 2)", "Q(p: spin($W.p, 2), n: $W.n)", "Q(..$W, p: $W.p.inc().inc())"); }
68
- if (($k >= 16 && $k <= 22) || ($k >= 38 && $k <= 41)) { push @stmts, "$nwn := $s"; push @ws, $nwn; $nw++; next; }
75
+ elsif ($k==42) { $s = pick("Q(n: $V.a, p: bump($V))", "Q(p: pass($V, $V2), n: 1)", "Q(p: bump(bump($V)), n: 2)", "Q(p: $V.inc(), n: $V.a)", "Q(..$W, p: pass($V, $V2))", "wrap(pass(bump($V), $V2))"); }
76
+ if (($k >= 16 && $k <= 22) || ($k >= 38 && $k <= 42)) { push @stmts, "$nwn := $s"; push @ws, $nwn; $nw++; next; }
69
77
  if ($k==23) { $s = "m.p = $V"; }
70
78
  elsif ($k==24) { $s = "m.p = m.p.inc()"; }
71
79
  elsif ($k==25) { $s = "m.p = pass(m.p, $V)"; }
@@ -78,11 +86,53 @@ for my $n (1..(6+r(12))) {
78
86
  my $body = join("\n ", @stmts);
79
87
  my $dump = "";
80
88
  my $i = 0;
89
+ my ($kv, $kw) = (0, 0);
81
- for my $v (@vs) { $dump .= " o$i := $v.show()\n"; $i++; }
90
+ for my $v (reverse @vs) { next unless $kv++ < 2 || r(3) == 0; $dump .= " o$i := $v.show()\n"; $i++; }
82
- for my $w (@ws) { $dump .= " o$i := $w.show()\n"; $i++; }
91
+ for my $w (reverse @ws) { next unless $kw++ < 2 || r(3) == 0; $dump .= " o$i := $w.show()\n"; $i++; }
83
92
  $dump .= " oM := m.p.show()\n oX := xs.at(0).show() + xs.at(1).show() + ys.at(0).show() + ys.at(1).show()\n";
84
93
  my $join = join(" + ", (map { "o$_" } 0..($i-1)), "oM", "oX");
85
94
  $dump .= " assert $join == \"\"\n";
95
+ # A second test on types of its own, with a field name of its own (a read of `x.p` whose type is not
96
+ # known counts against `p` on every type), used almost linearly. One shared use poisons a field's proof for
97
+ # the whole program, so the updates of fields only ever run in place in programs like this; the
98
+ # occasional value that is kept is what a wrong proof would corrupt: mostly one moved into a field,
99
+ # since any other kept value leaves the whole program copying.
100
+ my @ls = ('l0'); my @qs = ('q0');
101
+ my ($nl, $nq) = (1, 1);
102
+ my @kept;
103
+ sub consume {
104
+ my ($pool, $odds) = @_;
105
+ my $i = r(scalar @$pool);
106
+ my $x = $pool->[$i];
107
+ if (r($odds // 24) == 0) { push @kept, $x; } else { splice(@$pool, $i, 1); }
108
+ return $x;
109
+ }
110
+ my @lin;
111
+ for my $n (1..(4+r(9))) {
112
+ my $k = r(13);
113
+ my $x;
114
+ if ($k <= 4 && !@qs) { $k = 5; }
115
+ if ($k >= 5 && $k <= 11 && !@ls) { push @lin, "l$nl := lmk(".r(9).")"; push @ls, "l$nl"; $nl++; }
116
+ if ($k == 0) { $x = "qtick(".consume(\@qs).")"; }
117
+ elsif ($k == 1) { $x = consume(\@qs).".ticked()"; }
118
+ elsif ($k == 2) { my $q = consume(\@qs); $x = r(4) ? "qtick($q)" : "qrun($q, ".r(4).")"; }
119
+ elsif ($k == 3) { $x = "qthru(".consume(\@qs).")"; }
120
+ elsif ($k == 4) { my $q = consume(\@qs); $x = @ls ? "qstore($q, ".consume(\@ls, 4).")" : "qtick($q)"; }
121
+ elsif ($k == 5) { my $l = consume(\@ls, 4); $x = "Lq(core: $l, n: ".r(5).")"; }
122
+ elsif ($k == 6) { my $l = consume(\@ls, 4); $x = "Lq(core: lthru($l), n: 1)"; }
123
+ elsif ($k == 7) { my $l = consume(\@ls); $x = r(4) ? pick("Lq(core: lup($l), n: 2)", "lq2($l)") : pick("Lq(n: $l.a, core: lup($l))", "Lq(core: $l.up(), n: $l.a)"); }
124
+ if (defined $x) { push @lin, "q$nq := $x"; push @qs, "q$nq"; $nq++; next; }
125
+ if ($k == 8) { $x = "lup(".consume(\@ls).")"; }
126
+ elsif ($k == 9) { $x = consume(\@ls).".up()"; }
127
+ elsif ($k == 10) { $x = "lthru(".consume(\@ls).")"; }
128
+ elsif ($k == 11) { $x = "0.until(".r(4).").fold(".consume(\@ls).", |acc, i| lup(acc))"; }
129
+ else { $x = "lmk(".r(9).")"; }
130
+ push @lin, "l$nl := $x"; push @ls, "l$nl"; $nl++;
131
+ }
132
+ my %seen; my @show = grep { !$seen{$_}++ } (@ls, @qs, @kept);
133
+ my $linBody = join("
134
+ ", @lin);
135
+ my $linDump = join(" + ", map { "$_.show()" } @show) || '""';
86
136
  open(my $fh, '>', $out) or die;
87
137
  print $fh <<"EOP";
88
138
  import std/Int
@@ -99,6 +149,42 @@ struct Q(p: P, n: Int) =
99
149
 
100
150
  struct M(mut p: P)
101
151
 
152
+ # Another type with a field named `p`: only `rleak` reads it as a plain value.
153
+ struct R(p: P, n: Int) =
154
+ fun tick(self) -> R = R(..self, p: self.p.inc())
155
+
156
+ fun rleak(r: R) -> P = r.p
157
+
158
+ fun rtick(p: P) -> P =
159
+ r := R(p: p, n: 0)
160
+ rleak(r.tick())
161
+
162
+ fun step2(p: P, i: Int) -> P = P(..p, b: p.b + i)
163
+
164
+ struct Lp(a: Int, tag: Str) =
165
+ fun up(self) -> Lp = Lp(..self, a: self.a + 1)
166
+ fun show(self) -> Str = "L(" + self.a.toStr() + "," + self.tag + ");"
167
+
168
+ struct Lq(core: Lp, n: Int) =
169
+ fun ticked(self) -> Lq = Lq(..self, core: self.core.up(), n: self.n + 1)
170
+ fun show(self) -> Str = "M(" + self.core.show() + self.n.toStr() + ");"
171
+
172
+ fun lmk(a: Int) -> Lp = Lp(a: a, tag: "k")
173
+
174
+ fun lup(l: Lp) -> Lp = Lp(..l, a: l.a + 10)
175
+
176
+ fun lthru(l: Lp) -> Lp = if l.a > 100 then Lp(a: 0, tag: "z") else l
177
+
178
+ fun lq2(l: Lp) -> Lq = Lq(core: l, n: 3)
179
+
180
+ fun qtick(q: Lq) -> Lq = Lq(..q, core: lup(q.core))
181
+
182
+ fun qthru(q: Lq) -> Lq = Lq(..q, core: lthru(q.core))
183
+
184
+ fun qstore(q: Lq, l: Lp) -> Lq = Lq(..q, core: l, n: q.n + 1)
185
+
186
+ fun qrun(q: Lq, n: Int) -> Lq = if n == 0 then q else qrun(q.ticked(), n - 1)
187
+
102
188
  fun mk(a: Int, b: Int) -> P = P(a: a, b: b, tag: "mk")
103
189
 
104
190
  fun bump(p: P) -> P = P(..p, a: p.a + 1)
@@ -137,5 +223,10 @@ test "fuzz"
137
223
  ys.push(Q(p: P(a: 19, b: 20, tag: "w"), n: 4))
138
224
  $body
139
225
  $dump
226
+ test "linear"
227
+ l0 := lmk(1)
228
+ q0 := Lq(core: lmk(2), n: 0)
229
+ $linBody
230
+ assert $linDump == ""
140
231
  EOP
141
232
  close $fh;
tests/fbip/moves_into_fields.plum ADDED
@@ -0,0 +1,149 @@
1
+ import std/Int
2
+ import std/Str
3
+
4
+ # Locals moved into fields, and the order constructor values run in.
5
+
6
+ # A constructor runs its values in declaration order, whatever order they are written in.
7
+
8
+ struct OrderV(label: Str, y: Int)
9
+
10
+ struct OrderT(b: OrderV, a: Int)
11
+
12
+ fun orderBump(v: OrderV) -> OrderV = OrderV(..v, y: v.y + 1)
13
+
14
+ fun orderGo() -> OrderT =
15
+ v := OrderV(label: "x", y: 1)
16
+ OrderT(a: v.y, b: orderBump(v))
17
+
18
+ # A local moved into a field is not the field's only holder when it is used again.
19
+
20
+ struct MoveIn(label: Str, n: Int) =
21
+ fun up(self) -> MoveIn = MoveIn(..self, n: self.n + 1)
22
+
23
+ struct MoveOut(p: MoveIn, k: Int) =
24
+ fun tick(self) -> MoveOut = MoveOut(..self, p: self.p.up())
25
+
26
+ fun moveKeep() -> Int =
27
+ v := MoveIn(label: "x", n: 1)
28
+ o := MoveOut(p: v, k: 0).tick()
29
+ o.p.n * 10 + v.n
30
+
31
+ struct MoveTwo(p: MoveIn, q: MoveIn) =
32
+ fun tock(self) -> MoveTwo = MoveTwo(..self, p: self.p.up())
33
+
34
+ fun moveTwice() -> Int =
35
+ v := MoveIn(label: "x", n: 1)
36
+ t := MoveTwo(p: v, q: v).tock()
37
+ t.p.n * 10 + t.q.n
38
+
39
+ fun moveKept(v: MoveIn) -> MoveOut = MoveOut(p: v, k: 0).tick()
40
+
41
+ fun moveShared() -> Int =
42
+ v := MoveIn(label: "x", n: 1)
43
+ o := moveKept(v)
44
+ o.p.n * 10 + v.n
45
+
46
+ MoveStart = MoveIn(label: "s", n: 1)
47
+
48
+ fun moveGlobal() -> Int =
49
+ o := MoveOut(p: MoveStart, k: 0).tick()
50
+ o.p.n * 10 + MoveStart.n
51
+
52
+ # A local moved into a field reuses both objects.
53
+
54
+ struct Fm(label: Str, n: Int) =
55
+ fun up(self) -> Fm = Fm(..self, n: self.n + 1)
56
+
57
+ struct Fo(p: Fm, k: Int) =
58
+ fun tick(self) -> Fo = Fo(..self, p: self.p.up(), k: self.k + 1)
59
+
60
+ fun fieldMoveLoop(o: Fo, n: Int) -> Fo = if n == 0 then o else fieldMoveLoop(o.tick(), n - 1)
61
+
62
+ fun fieldMoved() -> Fo =
63
+ v := Fm(label: "x", n: 1)
64
+ w := v.up()
65
+ fieldMoveLoop(Fo(p: w, k: 0), 5)
66
+
67
+ # A pass-through result written into a field.
68
+ fun thru(c: MoveIn) -> MoveIn = if c.n > 100 then MoveIn(label: "big", n: 0) else c
69
+
70
+ fun thruKeep() -> Int =
71
+ v := MoveIn(label: "x", n: 1)
72
+ o := MoveOut(p: thru(v), k: 0).tick()
73
+ o.p.n * 10 + v.n
74
+
75
+ fun thruMoved() -> Int =
76
+ v := MoveIn(label: "x", n: 1)
77
+ o := MoveOut(p: thru(v), k: 0).tick().tick()
78
+ o.p.n
79
+
80
+ MoveHeld = MoveIn(label: "h", n: 1)
81
+
82
+ fun thruGlobal() -> Int =
83
+ o := MoveOut(p: thru(MoveHeld), k: 0).tick()
84
+ o.p.n * 10 + MoveHeld.n
85
+
86
+ # A fold whose closure calls a named function: the literal left at the call never runs.
87
+ fip fun foldStep(c: MoveIn, i: Int) -> MoveIn = MoveIn(..c, n: c.n + i)
88
+
89
+ fun foldNamed() -> MoveIn = 0.until(4).fold(MoveIn(label: "f", n: 0), |acc, i| foldStep(acc, i))
90
+
91
+ fun foldSeedShared() -> Int =
92
+ seed := MoveIn(label: "s", n: 1)
93
+ r := 0.until(4).fold(seed, |acc, i| MoveIn(..acc, n: acc.n + i))
94
+ r.n * 10 + seed.n
95
+
96
+ fun foldCapture() -> Int =
97
+ c := MoveIn(label: "c", n: 5)
98
+ r := 0.until(3).fold(MoveIn(label: "f", n: 0), |acc, i| MoveIn(..acc, n: acc.n + c.n))
99
+ r.n * 10 + c.n
100
+
101
+ fun foldCaptureSpread() -> Int =
102
+ c := MoveIn(label: "c", n: 5)
103
+ r := 0.until(3).fold(0, |acc, i| acc + MoveIn(..c, n: c.n + 1).n)
104
+ r
105
+
106
+ test "a field written first still reads the value from before the update"
107
+ t := orderGo()
108
+ assert t.a == 1
109
+ assert t.b.y == 2
110
+
111
+ test "a read after the move into a field sees the old value"
112
+ assert moveKeep() == 21
113
+
114
+ test "the same value moved into two fields stays two values"
115
+ assert moveTwice() == 21
116
+
117
+ test "a parameter moved into a field with a caller still holding it"
118
+ assert moveShared() == 21
119
+
120
+ test "a global moved into a field stays as it was"
121
+ assert moveGlobal() == 21
122
+ assert moveGlobal() == 21
123
+
124
+ test "a local moved into a field keeps its updates"
125
+ o := fieldMoved()
126
+ assert o.p.n == 7
127
+ assert o.k == 5
128
+
129
+ test "a pass-through result in a field with the value read later"
130
+ assert thruKeep() == 21
131
+
132
+ test "a pass-through result in a field keeps its updates"
133
+ assert thruMoved() == 3
134
+
135
+ test "a pass-through of a global in a field leaves the global"
136
+ assert thruGlobal() == 21
137
+ assert thruGlobal() == 21
138
+
139
+ test "a fold calling a named function"
140
+ assert foldNamed().n == 6
141
+
142
+ test "a fold over a seed read afterwards leaves the seed"
143
+ assert foldSeedShared() == 71
144
+
145
+ test "a fold capturing a value leaves it"
146
+ assert foldCapture() == 155
147
+
148
+ test "a fold spreading a captured value starts over each time"
149
+ assert foldCaptureSpread() == 18
tests/fbip/reuse_hostile.plum ADDED
@@ -0,0 +1,126 @@
1
+ # Cell reuse under attack: a reused cell must never be seen through another holder, and a cell is
2
+ # only ever reused for its own variant, however alike two types look.
3
+ import std/Int
4
+ import std/Str
5
+
6
+ enum Link =
7
+ | Nil
8
+ | Cons(head: Int, tail: Link)
9
+
10
+ enum Alt =
11
+ | Done
12
+ | Duo(head: Int, tail: Link)
13
+
14
+ struct Same(head: Int, tail: Link)
15
+
16
+ fun sum(xs: Link) -> Int = match xs
17
+ Nil => 0
18
+ Cons(h, t) => h + sum(t) * 10
19
+
20
+ # Same variant, each cell dead after its arm: reused.
21
+ fun inc(xs: Link) -> Link = match xs
22
+ Nil => Nil
23
+ Cons(h, t) => Cons(head: h + 1, tail: inc(t))
24
+
25
+ # Field values taken from the old cell, the other way round.
26
+ fun swapHead(xs: Link, k: Int) -> Link = match xs
27
+ Nil => Nil
28
+ Cons(h, t) => Cons(head: k, tail: swapHead(t, h))
29
+
30
+ # The tail binder is used twice: the cell under it is held twice.
31
+ fun twice(xs: Link) -> Link = match xs
32
+ Nil => Nil
33
+ Cons(h, t) => Cons(head: sum(t), tail: inc2(t))
34
+
35
+ fun inc2(xs: Link) -> Link = match xs
36
+ Nil => Nil
37
+ Cons(h, t) => Cons(head: h + 1, tail: inc2(t))
38
+
39
+ # A caller keeps the list: nothing may be reused.
40
+ fun keepAndInc() -> Int =
41
+ xs := Cons(head: 1, tail: Cons(head: 2, tail: Nil))
42
+ ys := inc2(xs)
43
+ sum(xs) * 100 + sum(ys)
44
+
45
+ # The same shape, another enum: a new object, the old one untouched.
46
+ fun toAlt(xs: Link) -> Alt = match xs
47
+ Nil => Done
48
+ Cons(h, t) => Duo(head: h + 1, tail: t)
49
+
50
+ fun altKeeps() -> Int =
51
+ xs := Cons(head: 1, tail: Nil)
52
+ a := toAlt(xs)
53
+ match a
54
+ Done => 0
55
+ Duo(h, t) => h * 100 + sum(xs)
56
+
57
+ # The same shape, a struct.
58
+ fun toSame(xs: Link) -> Same = match xs
59
+ Nil => Same(head: 0, tail: Nil)
60
+ Cons(h, t) => Same(head: h + 1, tail: t)
61
+
62
+ fun sameKeeps() -> Int =
63
+ xs := Cons(head: 1, tail: Cons(head: 2, tail: Nil))
64
+ s := toSame(xs)
65
+ s.head * 1000 + sum(s.tail) * 100 + sum(xs)
66
+
67
+ # Each arm its own variant, a fresh argument, called twice.
68
+ enum Shape =
69
+ | Circle(r: Int, tag: Str)
70
+ | Square(w: Int, tag: Str)
71
+
72
+ fun grow(s: Shape) -> Shape = match s
73
+ Circle(r, tag) => Circle(r: r + 1, tag: tag)
74
+ Square(w, tag) => Square(w: w + 2, tag: tag)
75
+
76
+ fun flip(s: Shape) -> Shape = match s
77
+ Circle(r, tag) => Square(w: r, tag: tag)
78
+ Square(w, tag) => Circle(r: w, tag: tag)
79
+
80
+ fun size(s: Shape) -> Int = match s
81
+ Circle(r, _) => r
82
+ Square(w, _) => w * 100
83
+
84
+ # A nested pattern: the inner cell is dead too, the outer one reused.
85
+ fun dropSecond(xs: Link) -> Link = match xs
86
+ Cons(h, Cons(_, t)) => Cons(head: h, tail: t)
87
+ other => other
88
+
89
+ # A variant whose result keeps a field of the old cell, the old cell kept by no one.
90
+ fun keepTail(xs: Link) -> Link = match xs
91
+ Nil => Nil
92
+ Cons(h, t) => Cons(head: h, tail: t)
93
+
94
+ test "same variant, dead cell: values come out right"
95
+ assert sum(inc(Cons(head: 1, tail: Cons(head: 2, tail: Nil)))) == 32
96
+
97
+ test "values taken from the old cell, in another order"
98
+ assert sum(swapHead(Cons(head: 1, tail: Cons(head: 2, tail: Nil)), 5)) == 15
99
+
100
+ test "a tail held twice"
101
+ xs := twice(Cons(head: 1, tail: Cons(head: 2, tail: Cons(head: 3, tail: Nil))))
102
+ assert sum(xs) == 32 + 430
103
+
104
+ test "a caller keeps the list"
105
+ assert keepAndInc() == 2100 + 32
106
+
107
+ test "another enum of the same shape is a new object"
108
+ assert altKeeps() == 201
109
+
110
+ test "a struct of the same shape is a new object"
111
+ assert sameKeeps() == 2000 + 200 + 21
112
+
113
+ test "each variant keeps its own fields"
114
+ assert size(grow(Circle(r: 1, tag: "c"))) == 2
115
+ assert size(grow(Square(w: 1, tag: "s"))) == 300
116
+
117
+ test "changing variant reuses nothing"
118
+ assert size(flip(Circle(r: 7, tag: "c"))) == 700
119
+ assert size(flip(Square(w: 7, tag: "s"))) == 7
120
+
121
+ test "a nested pattern and a pass-through arm"
122
+ assert sum(dropSecond(Cons(head: 1, tail: Cons(head: 2, tail: Cons(head: 3, tail: Nil))))) == 31
123
+ assert sum(dropSecond(Nil)) == 0
124
+
125
+ test "a kept tail"
126
+ assert sum(keepTail(Cons(head: 1, tail: Cons(head: 2, tail: Nil)))) == 21