plum

#treesitter#compiler#wasm

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

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


95a32e5 — Peter John 2026-11-11T02:33:58+05:30
uniqueness: reuse matched cells in generic fns and methods
compiler/core/src/forms.rs CHANGED
@@ -630,7 +630,18 @@ fn liftFor(f: Loop, lift: Lift, at: &LiftSite, lifted: &mut Vec<Item>) -> Vec<St
630
630
  guard: None,
631
631
  body: Block { stmts: vec![Stmt::Expr(Expr::BoolLit(true), f.line, f.column)] },
632
632
  },
633
+ value: {
634
+ // The checker's type of the source: the uniqueness proof then resolves the call to
635
+ // that type's `next` alone, not to every `next` (a type parameter stays unstamped).
633
- value: method(&it, "next", vec![]),
636
+ let mut call = method(&it, "next", vec![]);
637
+ let generic = ty.name.chars().count() == 1 || at.generics.contains(&ty.name);
638
+ if let (ExprKind::Attribute(a), false) = (&mut call.kind, generic) {
639
+ if let AttrKind::Method(c) = &mut a.attr {
640
+ c.recv = Some(ty.name.clone());
641
+ }
642
+ }
643
+ call
644
+ },
634
645
  }));
635
646
  let mut params = vec![param(&it, ty.clone())];
636
647
  params.extend(freeParams(&lift));
compiler/core/src/uniqueness.rs CHANGED
@@ -13,8 +13,8 @@
13
13
  //! handed over as above, or `x.f` in `x.f = g(x.f)` when field `f` is itself unique.
14
14
  //! * A field `f` of a type (see `An.ownerOf`: when the owner is not known, of every type that has one)
15
15
  //! is unique when every write to it is fresh, every read of it is `x.f.h`,
16
- //! `x.f.h = ..` or the assign-back argument above, no pattern binds it, and no spread
16
+ //! `x.f.h = ..` or the assign-back argument above, no pattern binds it (but see cell reuse
17
- //! that is not itself proved copies it.
17
+ //! below), and no spread that is not itself proved copies it.
18
18
  //!
19
19
  //! * A fn may also return one of its own parameters (`fun act(self, n) = ..; n`). Its result
20
20
  //! then counts as fresh to a caller only when the argument handed in for that parameter is
@@ -26,11 +26,27 @@
26
26
  //!
27
27
  //! * A method whose `self` is only read (`ro`: field reads, field writes, calls of other `ro`
28
28
  //! methods; never returned, stored, passed on or captured) does not block a receiver. What
29
- //! it returns of `self`'s fields is the field analysis' business, not the receiver's.
29
+ //! it returns of `self`'s fields is the field analysis' business, not the receiver's. A
30
+ //! `match self` counts as a read when no arm builds the matched variant in tail position and
31
+ //! no binder is handed on (`selfMatchReads`): `Map.get` is read-only, `Map.with` is not.
30
32
  //!
31
33
  //! * Methods the compiler calls without a visible call site (`IMPLICIT`: interpolation, hashing,
32
34
  //! operators) are never proved: their callers are unknown.
33
35
  //!
36
+ //! * Cell reuse. `match x / T(a, b) => .. T(f: .., g: ..)`: an arm *consumes* `x` when nothing in it
37
+ //! (and nothing after the match) mentions or rebinds `x`, `T` has no `mut` field, and `x` is not
38
+ //! the `self` of a read-only method (`An.consumes`). When it does and `x` is unique, a constructor
39
+ //! of the same variant in tail position of the arm, with every field given, builds into `x`'s cell
40
+ //! (`ClassCall.reuse`, `reuseSites`): one such tail runs per path, after the binders were read.
41
+ //! * A field binder of a consuming arm takes the field over: `a` is unique when `x` is and field
42
+ //! `T.f` is unique (`Scan.patternMove`). So `l.with(k, v)` on `MapBin(_, _, _, l, r)` of a unique
43
+ //! map hands a unique subtree on. A binder that is only read (field reads, read-only receivers)
44
+ //! with `x` left alone in the arm is no second holder of its field, like `x.f.h`; one of a
45
+ //! consuming arm of a shared `x` is shared too, so every way it could leave needs a proof that
46
+ //! fails. Any other pattern binding makes the field shared, as before.
47
+ //! * A fn may also return a field binder moved out of a parameter, or the result of a call of
48
+ //! such fns handed its parameters (`Map.glue(l, r)`): both count as returning that parameter.
49
+ //!
34
50
  //! Parameters and fields are solved as a greatest fixpoint (assume unique, remove what
35
51
  //! fails, repeat). Code the program cannot reach from its entry points takes no part (`liveUnits`).
36
52
  //!
@@ -49,6 +65,10 @@ pub struct UniqueReport {
49
65
  pub fipSites: Vec<SiteVerdict>,
50
66
  /// The unique versions kept (`f$unique`), and why any were not made.
51
67
  pub versions: Vec<String>,
68
+ /// Constructors that reuse the cell of the value their arm took apart: `Fn:line` and the value.
69
+ pub reused: Vec<(String, String)>,
70
+ /// Arms that build the variant they took apart but do not reuse its cell, and why.
71
+ pub notReused: Vec<(String, String)>,
52
72
  }
53
73
 
54
74
  /// One spread of a `fip fun`, and whether it was proved in place.
@@ -467,6 +487,8 @@ struct An {
467
487
  /// Fns whose every result is fresh or one of their own parameters: the parameters they
468
488
  /// may return (see the header).
469
489
  passes: HashMap<usize, Vec<usize>>,
490
+ /// The field binders a fn of `passes` returns for a parameter (see `movedOutOf`).
491
+ passBinders: HashMap<(usize, usize), Vec<String>>,
470
492
  /// Field writes `o.f = g(..)` of a returning fn: the `(fn, parameter)` pairs that must stay
471
493
  /// unique and unstored for field `f` to stay unique.
472
494
  passWrites: Vec<(Vec<String>, Vec<(usize, usize)>)>,
@@ -478,6 +500,10 @@ struct An {
478
500
  // static field facts
479
501
  badField: HashSet<String>,
480
502
  patternBound: HashSet<String>,
503
+ /// Why a field is not unique, by `fieldKey` (`--explain-fusion`).
504
+ ufWhy: RefCell<HashMap<String, String>>,
505
+ /// Per unit, `reuseCandidates`.
506
+ reuseCands: Vec<bool>,
481
507
  poisonAll: bool,
482
508
  spreads: Vec<SpreadSite>,
483
509
  /// Methods whose `self` is only read: used as the object of field reads and field writes, or
@@ -618,6 +644,8 @@ impl An {
618
644
  fn fresh(&self, e: &Expr) -> bool {
619
645
  match &e.kind {
620
646
  ExprKind::ClassCall(_) => true,
647
+ // A variant without fields (`MapTip`): nothing can be written into it or reuse it.
648
+ ExprKind::TypeName(n) => self.enums.get(n).is_some_and(|f| f.is_empty()) && self.owner.get(n).is_some_and(|o| o != n),
621
649
  ExprKind::InlineIf(i) => self.fresh(&i.then) && self.fresh(&i.else_),
622
650
  // A block value is as fresh as its last values.
623
651
  ExprKind::Block(b) => {
@@ -731,10 +759,17 @@ impl An {
731
759
  fn passParamOk(&self, g: usize, j: usize) -> bool {
732
760
  let u = &self.units[g];
733
761
  let receiver = u.method && u.hasSelf && j == 0;
762
+ // A binder may also be moved into a new node on another path (`left: l`), which only the
763
+ // scan outside strict mode accepts; whether that keeps the field unique is `varWrites`'.
764
+ let binders = self.passBinders.get(&(g, j)).map(|v| v.as_slice()).unwrap_or(&[]);
734
765
  if receiver {
766
+ u.params.get(j).is_some_and(|p| p.plain)
735
- u.params.get(j).is_some_and(|p| p.plain) && self.varOkCached(g, &u.params[j].name, true, true).is_ok()
767
+ && self.varOkCached(g, &u.params[j].name, true, true).is_ok()
768
+ && binders.iter().all(|b| self.varOkCached(g, b, false, true).is_ok())
736
769
  } else {
770
+ self.paramUnique(g, j)
737
- self.paramUnique(g, j) && self.varOkMode(g, &u.params[j].name, true).is_ok()
771
+ && self.varOkMode(g, &u.params[j].name, true).is_ok()
772
+ && binders.iter().all(|b| self.varOkMode(g, b, false).is_ok())
738
773
  }
739
774
  }
740
775
 
@@ -748,14 +783,14 @@ impl An {
748
783
  /// The parameter of method `g` that argument `k` of `c` binds (`None` = the receiver).
749
784
  fn methodParam(&self, g: usize, c: &FnCall, k: Option<usize>) -> Option<usize> {
750
785
  let u = &self.units[g];
786
+ // A static method (`Map.bin(k, v, l, r)`): its arguments are its parameters, and the
787
+ // receiver is a type name.
751
- if !u.hasSelf {
788
+ let off = u.hasSelf as usize;
752
- return None;
753
- }
754
789
  match k {
755
- None => Some(0),
790
+ None => u.hasSelf.then_some(0),
756
791
  Some(k) => match &c.args[k] {
757
792
  Arg::Positional(_) => {
758
- Some(1 + c.args[..k].iter().filter(|a| matches!(a, Arg::Positional(_))).count())
793
+ Some(off + c.args[..k].iter().filter(|a| matches!(a, Arg::Positional(_))).count())
759
794
  }
760
795
  Arg::Keyword { name, .. } => u.params.iter().position(|p| &p.name == name),
761
796
  },
@@ -828,7 +863,7 @@ impl An {
828
863
  return Err(why.unwrap_or_else(|| format!("a caller of `{}` may pass a shared `{v}`", u.name)));
829
864
  }
830
865
  }
831
- let mut s = Scan { an: self, unit, v, strict, boundDepth: if param.is_some() { Some(0) } else { None }, err: None, mentioned: RefCell::new(HashMap::new()) };
866
+ let mut s = Scan { an: self, unit, v, strict, entryUnique, boundDepth: if param.is_some() { Some(0) } else { None }, err: None, mentioned: RefCell::new(HashMap::new()) };
832
867
  s.block(&u.block, true, false, 0);
833
868
  if let Some(e) = s.err {
834
869
  return Err(e);
@@ -957,6 +992,115 @@ impl An {
957
992
  fn movedField(&self, e: &Expr) -> bool {
958
993
  self.moveReads.get(&e.id).is_some_and(|k| self.uf.borrow().contains(k))
959
994
  }
995
+
996
+ /// Does case `c` of `m` (in `unit`) consume subject `k`, a constructor pattern on a plain
997
+ /// variable `x` (returned)? It does when nothing in the case (guard, body, other patterns)
998
+ /// mentions or rebinds `x`, no other subject mentions it, the type has no `mut` field, nothing
999
+ /// after the match reads `x` (a loop around it counts as a read), and `x` is not the `self`
1000
+ /// of a read-only method (whose callers keep using their receiver). Whether `x` is unique is
1001
+ /// the caller's question.
1002
+ fn consumes<'m>(&self, unit: usize, m: &'m Match, k: usize, c: &Case) -> Result<&'m str, String> {
1003
+ let Some(x) = m.subjects.get(k).and_then(varName) else {
1004
+ return Err("the matched value is not a variable".to_string());
1005
+ };
1006
+ let CasePattern::Class { name, .. } = &c.patterns[k] else {
1007
+ return Err(format!("`{x}` is not matched by a constructor pattern"));
1008
+ };
1009
+ if c.patterns.iter().any(|p| oddName(self, p)) {
1010
+ return Err("a pattern binds an uppercase name".to_string());
1011
+ }
1012
+ if self.mutTypes.contains(name) {
1013
+ return Err(format!("`{name}` has `mut` fields"));
1014
+ }
1015
+ if m.subjects.iter().enumerate().any(|(i, s)| i != k && {
1016
+ let mut f = false;
1017
+ walkExpr(s, &mut |n| {
1018
+ if let Node::E(e) = n {
1019
+ f |= isVar(e, x);
1020
+ }
1021
+ !f
1022
+ });
1023
+ f
1024
+ }) {
1025
+ return Err(format!("`{x}` is matched twice"));
1026
+ }
1027
+ if x == "self" && self.ro.contains(&unit) {
1028
+ return Err("`self` of a read-only method: its callers keep using it".to_string());
1029
+ }
1030
+ if caseTouches(c, k, x) {
1031
+ return Err(format!("`{x}` is still used in the arm that takes it apart"));
1032
+ }
1033
+ if liveAfterMatch(&self.units[unit].block.stmts, m, x) != Some(false) {
1034
+ return Err(format!("`{x}` may be used after the match that takes it apart"));
1035
+ }
1036
+ Ok(x)
1037
+ }
1038
+
1039
+ /// Is binder `b` of case `c` only read: each use the object of a field read `b.f` or the
1040
+ /// receiver of read-only methods, never rebound or captured? Then it is no second holder
1041
+ /// of the field it was bound from (like a read `x.f.h`).
1042
+ fn binderReadOnly(&self, c: &Case, k: usize, b: &str) -> bool {
1043
+ let (mut uses, mut reads, mut bad) = (0usize, 0usize, false);
1044
+ let mut look = |n: Node| {
1045
+ if let Node::E(e) = n {
1046
+ match &e.kind {
1047
+ _ if isVar(e, b) => uses += 1,
1048
+ ExprKind::Attribute(a) if isVar(&a.object, b) => match &a.attr {
1049
+ AttrKind::Field(_) => reads += 1,
1050
+ AttrKind::Method(mc) => {
1051
+ let cands = self.cands(mc);
1052
+ if !cands.is_empty() && cands.iter().all(|g| self.ro.contains(g)) {
1053
+ reads += 1;
1054
+ }
1055
+ }
1056
+ },
1057
+ ExprKind::Closure(_) => {
1058
+ let mut f = false;
1059
+ walkExpr(e, &mut |m| {
1060
+ if let Node::E(x) = m {
1061
+ f |= isVar(x, b);
1062
+ }
1063
+ !f
1064
+ });
1065
+ bad |= f;
1066
+ }
1067
+ _ => {}
1068
+ }
1069
+ }
1070
+ !bad
1071
+ };
1072
+ if let Some(g) = &c.guard {
1073
+ walkExpr(g, &mut look);
1074
+ }
1075
+ walkBlock(&c.body, &mut look);
1076
+ !bad && uses == reads && bindsOnce(&c.patterns[k], b) && !caseTouchesWith(c, k, b, false)
1077
+ }
1078
+ }
1079
+
1080
+ /// A constructor of `c`'s pattern at `k` in tail position of the arm, with every field given and no
1081
+ /// spread: the matched cell can take its values. The ids of those constructors.
1082
+ fn reuseTails(an: &An, c: &Case, k: usize) -> Vec<NodeId> {
1083
+ let CasePattern::Class { name, fields, .. } = &c.patterns[k] else { return vec![] };
1084
+ let Some(declared) = an.enums.get(name) else { return vec![] };
1085
+ if fields.is_empty() || declared.is_empty() || an.owner.get(name).is_none_or(|o| o == name) {
1086
+ return vec![];
1087
+ }
1088
+ let mut tails = vec![];
1089
+ collectTails(&c.body, &mut tails);
1090
+ tails
1091
+ .into_iter()
1092
+ .filter(|e| match &e.kind {
1093
+ ExprKind::ClassCall(cc) => {
1094
+ cc.type_name == *name
1095
+ && cc.spread.is_none()
1096
+ && cc.reuse.is_none()
1097
+ && cc.fields.len() == declared.len()
1098
+ && declared.iter().all(|d| cc.fields.iter().filter(|f| f.name == *d).count() == 1)
1099
+ }
1100
+ _ => false,
1101
+ })
1102
+ .map(|e| e.id)
1103
+ .collect()
960
1104
  }
961
1105
 
962
1106
  // ---------- liveness after a downcast ----------
@@ -1006,6 +1150,128 @@ fn containsMatch(s: &Stmt, target: &Match) -> bool {
1006
1150
  found
1007
1151
  }
1008
1152
 
1153
+ /// Does pattern `p` bind a name of its own (`x`, not a variant name like `MapTip` or `_`)?
1154
+ fn bindsName(p: &CasePattern) -> bool {
1155
+ let mut names = vec![];
1156
+ crate::visit::patternBinders(p, &mut names);
1157
+ match p {
1158
+ CasePattern::Name(_) | CasePattern::As { .. } => !names.is_empty(),
1159
+ _ => false,
1160
+ }
1161
+ }
1162
+
1163
+ /// Does case `c` (its guard, its body or a pattern of it other than at `k`) mention `x`, or bind or
1164
+ /// assign a name `x` anywhere (a closure parameter, an inner pattern, `x = ..`)?
1165
+ fn caseTouches(c: &Case, k: usize, x: &str) -> bool {
1166
+ caseTouchesWith(c, k, x, true)
1167
+ }
1168
+
1169
+ /// `caseTouches`; with `uses` off, only a binding or assignment of `x` counts.
1170
+ fn caseTouchesWith(c: &Case, k: usize, x: &str, uses: bool) -> bool {
1171
+ let mut found = c.patterns.iter().enumerate().any(|(i, p)| {
1172
+ let mut names = vec![];
1173
+ crate::visit::patternBinders(p, &mut names);
1174
+ i != k && names.iter().any(|n| n == x)
1175
+ });
1176
+ let mut look = |n: Node| {
1177
+ match n {
1178
+ Node::E(e) => match &e.kind {
1179
+ _ if uses && isVar(e, x) => found = true,
1180
+ ExprKind::Closure(cl) => found |= cl.params.iter().any(|p| p == x),
1181
+ ExprKind::Bind(b) => {
1182
+ let mut names = vec![];
1183
+ b.case.patterns.iter().for_each(|p| crate::visit::patternBinders(p, &mut names));
1184
+ found |= names.iter().any(|n| n == x);
1185
+ }
1186
+ _ => {}
1187
+ },
1188
+ Node::S(s) => match &s.kind {
1189
+ StmtKind::Assign(a) => found |= a.targets.iter().any(|t| matches!(t, AssignTarget::Var(n) if n == x)),
1190
+ StmtKind::Match(m) => {
1191
+ let mut names = vec![];
1192
+ m.cases.iter().flat_map(|c| &c.patterns).for_each(|p| crate::visit::patternBinders(p, &mut names));
1193
+ found |= names.iter().any(|n| n == x);
1194
+ }
1195
+ _ => {}
1196
+ },
1197
+ Node::M(..) => {}
1198
+ }
1199
+ !found
1200
+ };
1201
+ if let Some(g) = &c.guard {
1202
+ walkExpr(g, &mut look);
1203
+ }
1204
+ walkBlock(&c.body, &mut look);
1205
+ found
1206
+ }
1207
+
1208
+ /// The parameter `b` is a field binder of, when every binding of `b` in `u` is a direct field of a
1209
+ /// constructor pattern in a match on that same plain parameter (`removeMin`'s two arms bind `r`).
1210
+ /// Whether the field is taken over is `patternMove`'s.
1211
+ fn movedOutOf(u: &Unit, b: &str) -> Option<usize> {
1212
+ let mut other = false;
1213
+ let mut subjects: Vec<String> = vec![];
1214
+ walkBlock(&u.block, &mut |n| {
1215
+ match n {
1216
+ Node::S(Stmt { kind: StmtKind::Match(m), .. }) => {
1217
+ for c in &m.cases {
1218
+ for (k, p) in c.patterns.iter().enumerate() {
1219
+ let mut names = vec![];
1220
+ crate::visit::patternBinders(p, &mut names);
1221
+ let here = names.iter().filter(|n| *n == b).count();
1222
+ if here == 0 {
1223
+ continue;
1224
+ }
1225
+ match m.subjects.get(k).and_then(varName) {
1226
+ Some(x) if here == 1 && directBinders(p).iter().any(|(y, _)| *y == b) => subjects.push(x.to_string()),
1227
+ _ => other = true,
1228
+ }
1229
+ }
1230
+ }
1231
+ }
1232
+ Node::S(Stmt { kind: StmtKind::Assign(a), .. }) => {
1233
+ other |= a.targets.iter().any(|t| matches!(t, AssignTarget::Var(n) if n == b));
1234
+ }
1235
+ Node::E(Expr { kind: ExprKind::Closure(cl), .. }) => other |= cl.params.iter().any(|p| p == b),
1236
+ Node::E(Expr { kind: ExprKind::Bind(x), .. }) => {
1237
+ let mut names = vec![];
1238
+ x.case.patterns.iter().for_each(|p| crate::visit::patternBinders(p, &mut names));
1239
+ other |= names.iter().any(|n| n == b);
1240
+ }
1241
+ _ => {}
1242
+ }
1243
+ !other
1244
+ });
1245
+ if other || subjects.is_empty() || u.params.iter().any(|p| p.name == b) {
1246
+ return None;
1247
+ }
1248
+ let s = &subjects[0];
1249
+ if subjects.iter().any(|x| x != s) {
1250
+ return None;
1251
+ }
1252
+ u.params.iter().position(|p| p.name == *s && p.plain)
1253
+ }
1254
+
1255
+ /// Does `p` bind `b` exactly once?
1256
+ fn bindsOnce(p: &CasePattern, b: &str) -> bool {
1257
+ let mut names = vec![];
1258
+ crate::visit::patternBinders(p, &mut names);
1259
+ names.iter().filter(|n| *n == b).count() == 1
1260
+ }
1261
+
1262
+ /// The direct field binders of a constructor pattern: `(binder, field position)`.
1263
+ fn directBinders(p: &CasePattern) -> Vec<(&str, usize)> {
1264
+ let CasePattern::Class { fields, .. } = p else { return vec![] };
1265
+ fields
1266
+ .iter()
1267
+ .enumerate()
1268
+ .filter_map(|(i, f)| match f {
1269
+ CasePattern::Name(n) if bindsName(f) => Some((n.as_str(), i)),
1270
+ _ => None,
1271
+ })
1272
+ .collect()
1273
+ }
1274
+
1009
1275
  fn mentionsVar(ss: &[Stmt], x: &str) -> bool {
1010
1276
  let mut found = false;
1011
1277
  for s in ss {
@@ -1026,6 +1292,8 @@ struct Scan<'a> {
1026
1292
  unit: usize,
1027
1293
  v: &'a str,
1028
1294
  strict: bool,
1295
+ /// The parameters are taken to arrive unique (see `An.varOkCached`).
1296
+ entryUnique: bool,
1029
1297
  boundDepth: Option<usize>,
1030
1298
  err: Option<String>,
1031
1299
  /// `mentionsStmt` per statement (by address): a nested statement is asked again at each
@@ -1202,6 +1470,44 @@ impl<'a> Scan<'a> {
1202
1470
  Some(Ok(()))
1203
1471
  }
1204
1472
 
1473
+ /// `match x / T(.., v, ..) => ..` where the arm consumes a unique `x` (`An.consumes`): `v` takes
1474
+ /// over field `f` of `x`, which only `x` held when `f` is a unique field, so `v` is unique in the
1475
+ /// arm. `None`: `v` is not a direct field binder of a constructor pattern in `c`.
1476
+ fn patternMove(&mut self, m: &Match, c: &Case, depth: usize) -> Option<Result<(), String>> {
1477
+ let v = self.v.to_string();
1478
+ let (k, i) = c.patterns.iter().enumerate().find_map(|(k, p)| directBinders(p).into_iter().find(|(b, _)| *b == v).map(|(_, i)| (k, i)))?;
1479
+ let mut names = vec![];
1480
+ c.patterns.iter().for_each(|p| crate::visit::patternBinders(p, &mut names));
1481
+ if names.iter().filter(|n| **n == v).count() != 1 {
1482
+ return Some(Err(format!("`{v}` is bound more than once by a pattern")));
1483
+ }
1484
+ let x = match self.an.consumes(self.unit, m, k, c) {
1485
+ Ok(x) => x.to_string(),
1486
+ Err(why) => return Some(Err(format!("`{v}` is rebound by a pattern: {why}"))),
1487
+ };
1488
+ let CasePattern::Class { name, .. } = &c.patterns[k] else { return None };
1489
+ let key = fieldsOf(&self.an.enums, name).and_then(|fs| fs.get(i).cloned()).map(|f| fieldKey(self.an.owner.get(name).map_or(name.as_str(), |o| o.as_str()), &f));
1490
+ match key {
1491
+ Some(key) if self.an.uf.borrow().contains(&key) => {}
1492
+ Some(key) => {
1493
+ let why = self.an.ufWhy.borrow().get(&key).cloned().unwrap_or_default();
1494
+ return Some(Err(format!("`{v}` is taken out of `{key}`, which may be shared: {why}")));
1495
+ }
1496
+ None => return Some(Err(format!("`{v}` is taken out of a field of `{x}` of unknown type"))),
1497
+ }
1498
+ if let Err(why) = self.an.varOkCached(self.unit, &x, self.strict, self.entryUnique) {
1499
+ return Some(Err(format!("`{v}` is taken out of `{x}`, which may be shared: {why}")));
1500
+ }
1501
+ // Another arm may bind the same name: each arm is a scope of its own, and a later mention
1502
+ // only makes the scan count the variable as live.
1503
+ match self.boundDepth {
1504
+ None => self.boundDepth = Some(depth + 1),
1505
+ Some(d) if d == depth + 1 => {}
1506
+ Some(_) => return Some(Err(format!("`{v}` is bound more than once"))),
1507
+ }
1508
+ Some(Ok(()))
1509
+ }
1510
+
1205
1511
  fn stmt(&mut self, s: &Stmt, tail: bool, live: bool, depth: usize) {
1206
1512
  let v: &'a str = self.v;
1207
1513
  match &s.kind {
@@ -1283,7 +1589,7 @@ impl<'a> Scan<'a> {
1283
1589
  let inCases = m.cases.iter().any(|c| self.mentionsBlock(&c.body) || c.guard.as_ref().is_some_and(|g| self.mentions(g)));
1284
1590
  for (k, sub) in m.subjects.iter().enumerate() {
1285
1591
  if self.bare(sub) {
1286
- if m.cases.iter().any(|c| matches!(c.patterns.get(k), Some(CasePattern::Name(_)))) {
1592
+ if m.cases.iter().any(|c| matches!(c.patterns.get(k), Some(CasePattern::Name(n)) if !self.an.owner.contains_key(n))) {
1287
1593
  self.failWith(|| format!("`{v}` is also held by a pattern binding"));
1288
1594
  }
1289
1595
  // A downcast `T as o` moves the value into `o` only if `v` is dead in
@@ -1299,7 +1605,7 @@ impl<'a> Scan<'a> {
1299
1605
  }
1300
1606
  }
1301
1607
  for c in &m.cases {
1302
- match self.downcastMove(m, c, tail, depth) {
1608
+ match self.downcastMove(m, c, tail, depth).or_else(|| self.patternMove(m, c, depth)) {
1303
1609
  Some(Ok(())) => {}
1304
1610
  Some(Err(why)) => self.fail(why),
1305
1611
  None => self.checkPatterns(&c.patterns),
@@ -1348,11 +1654,13 @@ impl<'a> Scan<'a> {
1348
1654
  let cands: Vec<usize> = self.an.cands(c);
1349
1655
  let recvBare = self.bare(&a.object);
1350
1656
  let bareCount = recvBare as usize + c.args.iter().filter(|x| self.bare(argExpr(x))).count();
1657
+ // A call on a type name runs a static method; one on a value, an instance method.
1658
+ let isType = matches!(a.object.kind, ExprKind::TypeName(_));
1351
1659
  let handOver = |s: &Scan, k: Option<usize>, lv: bool| -> bool {
1352
1660
  bareCount == 1
1353
1661
  && !lv
1354
1662
  && !cands.is_empty()
1355
- && cands.iter().all(|&g| s.an.methodParam(g, c, k).is_some_and(|j| s.an.handOk(g, j)))
1663
+ && cands.iter().all(|&g| s.an.units[g].hasSelf != isType && s.an.methodParam(g, c, k).is_some_and(|j| s.an.handOk(g, j)))
1356
1664
  };
1357
1665
  let readOnly = recvBare && !cands.is_empty() && cands.iter().all(|g| self.an.ro.contains(g));
1358
1666
  let inArgs = c.args.iter().any(|x| self.mentions(argExpr(x)));
@@ -1538,16 +1846,38 @@ pub fn markUnique(src: &mut Source) -> UniqueReport {
1538
1846
  copied.push((ui, d.span, result));
1539
1847
  }
1540
1848
  }
1849
+ let reuse = reuseSites(&an);
1850
+ for (ui, u) in an.units.iter().enumerate() {
1851
+ let mut why = Some(vec![]);
1852
+ reuseWhy(&an, ui, &mut why);
1853
+ let mut why = why.unwrap_or_default();
1854
+ why.dedup();
1855
+ for w in why {
1856
+ report.notReused.push((format!("{}:{}", u.label, lineOf(src, u)), w));
1857
+ }
1858
+ }
1541
1859
  // Mutable pass.
1542
1860
  for (ui, u) in an.units.iter().enumerate() {
1543
1861
  if u.kind == Kind::Const {
1544
1862
  continue;
1545
1863
  }
1546
1864
  let ok = &okVars[ui];
1865
+ let reuseHere = &reuse[ui];
1866
+ if !reuseHere.is_empty() {
1867
+ let label = format!("{}:{}", u.label, lineOf(src, u));
1868
+ let mut vars: Vec<&String> = reuseHere.values().collect();
1869
+ vars.sort();
1870
+ vars.dedup();
1871
+ report.reused.extend(vars.into_iter().map(|v| (label.clone(), v.clone())));
1872
+ }
1547
1873
  let mut spans: HashMap<NodeId, Span> = HashMap::new();
1548
1874
  let mut mark = |e: &mut Expr| {
1549
1875
  spans.insert(e.id, e.span);
1550
1876
  let ExprKind::ClassCall(c) = &mut e.kind else { return };
1877
+ if let Some(x) = reuseHere.get(&e.id) {
1878
+ c.reuse = Some(x.clone());
1879
+ return;
1880
+ }
1551
1881
  if let Some(s) = &c.spread {
1552
1882
  if let Some(v) = varName(s) {
1553
1883
  if ok.contains(v) && an.varOk(ui, v).is_ok() && an.copyReason(c, v).is_none() {
@@ -1582,6 +1912,90 @@ pub fn markUnique(src: &mut Source) -> UniqueReport {
1582
1912
  report
1583
1913
  }
1584
1914
 
1915
+ /// Per unit, the constructors that may build into the cell of the value their arm takes apart, by
1916
+ /// node id: `match x / T(..) => .. T(..)` where the arm consumes `x` (`An.consumes`), `x` is unique,
1917
+ /// and the constructor is of the same variant, in tail position of the arm, with every field given.
1918
+ /// On each path through the arm one tail runs, once, after which nothing reads `x`; the fields the
1919
+ /// arm bound from `x` were read into locals when it matched. A node id met more than once in the
1920
+ /// unit (a copied call) is left alone.
1921
+ fn reuseSites(an: &An) -> Vec<HashMap<NodeId, String>> {
1922
+ (0..an.units.len()).map(|ui| reuseIn(an, ui)).collect()
1923
+ }
1924
+
1925
+ /// `reuseSites` of one unit.
1926
+ fn reuseIn(an: &An, ui: usize) -> HashMap<NodeId, String> {
1927
+ reuseWhy(an, ui, &mut None)
1928
+ }
1929
+
1930
+ /// `reuseIn`; with `why`, also the reason each candidate arm does not reuse (`--explain-fusion`).
1931
+ fn reuseWhy(an: &An, ui: usize, why: &mut Option<Vec<String>>) -> HashMap<NodeId, String> {
1932
+ let mut out: HashMap<NodeId, String> = HashMap::new();
1933
+ let u = &an.units[ui];
1934
+ if u.kind == Kind::Const || !an.live[ui] || !an.reuseCands[ui] {
1935
+ return out;
1936
+ }
1937
+ {
1938
+ let mut found: Vec<(NodeId, String)> = vec![];
1939
+ let mut ids: HashMap<NodeId, usize> = HashMap::new();
1940
+ walkBlock(&u.block, &mut |n| {
1941
+ match n {
1942
+ Node::E(e) => *ids.entry(e.id).or_default() += 1,
1943
+ Node::S(Stmt { kind: StmtKind::Match(m), .. }) => {
1944
+ for c in &m.cases {
1945
+ for k in 0..c.patterns.len() {
1946
+ let tails = reuseTails(an, c, k);
1947
+ if tails.is_empty() {
1948
+ continue;
1949
+ }
1950
+ let x = match an.consumes(ui, m, k, c) {
1951
+ Ok(x) => x,
1952
+ Err(w) => {
1953
+ if let Some(ws) = why.as_mut() {
1954
+ ws.push(w);
1955
+ }
1956
+ continue;
1957
+ }
1958
+ };
1959
+ if let Err(w) = an.varOk(ui, x) {
1960
+ if let Some(ws) = why.as_mut() {
1961
+ ws.push(w);
1962
+ }
1963
+ continue;
1964
+ }
1965
+ found.extend(tails.into_iter().map(|id| (id, x.to_string())));
1966
+ }
1967
+ }
1968
+ }
1969
+ _ => {}
1970
+ }
1971
+ true
1972
+ });
1973
+ for (id, x) in found {
1974
+ if ids.get(&id) == Some(&1) {
1975
+ out.entry(id).or_insert(x);
1976
+ }
1977
+ }
1978
+ }
1979
+ out
1980
+ }
1981
+
1982
+ /// Per unit: does it have a constructor that could reuse a matched cell (`reuseTails`)?
1983
+ fn reuseCandidates(an: &An) -> Vec<bool> {
1984
+ an.units
1985
+ .iter()
1986
+ .map(|u| {
1987
+ let mut any = false;
1988
+ walkBlock(&u.block, &mut |n| {
1989
+ if let Node::S(Stmt { kind: StmtKind::Match(m), .. }) = n {
1990
+ any |= m.cases.iter().any(|c| (0..c.patterns.len()).any(|k| !reuseTails(an, c, k).is_empty()));
1991
+ }
1992
+ !any
1993
+ });
1994
+ any
1995
+ })
1996
+ .collect()
1997
+ }
1998
+
1585
1999
  fn lineOf(src: &Source, u: &Unit) -> usize {
1586
2000
  match &src.items[u.itemIdx] {
1587
2001
  Item::Fn(f) => f.line,
@@ -1889,6 +2303,9 @@ fn build(src: &Source) -> An {
1889
2303
  cache: RefCell::new(HashMap::new()),
1890
2304
  badField: HashSet::new(),
1891
2305
  patternBound: HashSet::new(),
2306
+ ufWhy: RefCell::new(HashMap::new()),
2307
+ reuseCands: vec![],
2308
+ passBinders: HashMap::new(),
1892
2309
  poisonAll: false,
1893
2310
  spreads: vec![],
1894
2311
  ro: HashSet::new(),
@@ -1919,6 +2336,7 @@ fn build(src: &Source) -> An {
1919
2336
  }
1920
2337
  }
1921
2338
  an.ro = readOnlySelf(&an);
2339
+ an.reuseCands = reuseCandidates(&an);
1922
2340
  // Fresh-return fns: greatest fixpoint.
1923
2341
  let mut fr: HashSet<usize> = an.freeIdx.values().copied().collect();
1924
2342
  fr.extend(an.methodIdx.values().flatten().copied());
@@ -1953,56 +2371,118 @@ fn build(src: &Source) -> An {
1953
2371
  }
1954
2372
  }
1955
2373
  *an.fresh_ret.borrow_mut() = fr;
1956
- // Fns that may return one of their own parameters: every result is fresh or such a parameter.
2374
+ // Fns that may return one of their own parameters: every result is fresh, such a parameter, a
2375
+ // field binder moved out of one, or a call of such fns handed those for what they return.
2376
+ // A greatest fixpoint: every fn starts out returning none of its parameters, and each round
1957
- let mut passes: HashMap<usize, Vec<usize>> = HashMap::new();
2377
+ // drops the fns whose results are not accounted for and adds the parameters they return. A
2378
+ // recursive call (`l.until(hi)`) then returns what the fn does: on each path the innermost call
2379
+ // returns something else, or never returns.
1958
2380
  let mut order: Vec<usize> = an.freeIdx.values().copied().chain(an.methodIdx.values().flatten().copied()).collect();
1959
2381
  order.sort();
2382
+ order.dedup();
2383
+ order.retain(|g| !an.fresh_ret.borrow().contains(g));
2384
+ an.passes = order.iter().map(|&g| (g, vec![])).collect();
2385
+ let mut settled = false;
1960
- for g in order {
2386
+ for _ in 0..64 {
2387
+ let mut passes: HashMap<usize, Vec<usize>> = HashMap::new();
2388
+ let mut passBinders: HashMap<(usize, usize), Vec<String>> = HashMap::new();
2389
+ for &g in &order {
1961
- if an.fresh_ret.borrow().contains(&g) {
2390
+ if !an.passes.contains_key(&g) {
1962
- continue;
2391
+ continue;
1963
- }
1964
- let u = &an.units[g];
1965
- let mut tails = vec![];
1966
- let mut ok = collectTails(&u.block, &mut tails);
1967
- walkBlock(&u.block, &mut |n| {
1968
- match n {
1969
- Node::S(Stmt { kind: StmtKind::Return(Some(e)), .. }) => tails.push(e),
1970
- Node::E(Expr { kind: ExprKind::Closure(_), .. }) => return false,
1971
- _ => {}
1972
2392
  }
2393
+ let u = &an.units[g];
2394
+ let mut tails = vec![];
2395
+ let mut ok = collectTails(&u.block, &mut tails);
2396
+ walkBlock(&u.block, &mut |n| {
2397
+ match n {
2398
+ Node::S(Stmt { kind: StmtKind::Return(Some(e)), .. }) => tails.push(e),
2399
+ Node::E(Expr { kind: ExprKind::Closure(_), .. }) => return false,
2400
+ _ => {}
2401
+ }
1973
- true
2402
+ true
1974
- });
2403
+ });
1975
- // `if c then a else b` as a result: each branch is a result.
2404
+ // `if c then a else b` as a result: each branch is a result.
1976
- let mut flat: Vec<&Expr> = vec![];
2405
+ let mut flat: Vec<&Expr> = vec![];
1977
- while let Some(e) = tails.pop() {
2406
+ while let Some(e) = tails.pop() {
1978
- match &e.kind {
2407
+ match &e.kind {
1979
- ExprKind::InlineIf(i) => {
2408
+ ExprKind::InlineIf(i) => {
1980
- tails.push(&i.then);
2409
+ tails.push(&i.then);
1981
- tails.push(&i.else_);
2410
+ tails.push(&i.else_);
2411
+ }
2412
+ _ => flat.push(e),
1982
2413
  }
1983
- _ => flat.push(e),
1984
2414
  }
2415
+ let mut ps: Vec<usize> = vec![];
2416
+ let mut binders: Vec<(usize, String)> = vec![];
2417
+ // The parameter `e` is, or a field binder moved out of (`MapBin(_, _, _, l, MapTip) => l`:
2418
+ // the result is that parameter's when the binder takes the field over, see `passParamOk`).
2419
+ let ofParam = |e: &Expr, binders: &mut Vec<(usize, String)>| -> Option<usize> {
2420
+ let n = varName(e)?;
2421
+ if let Some(j) = u.params.iter().position(|p| p.name == n && p.plain) {
2422
+ return Some(j);
1985
- }
2423
+ }
1986
- let mut ps: Vec<usize> = vec![];
2424
+ let j = movedOutOf(u, n)?;
2425
+ binders.push((j, n.to_string()));
2426
+ Some(j)
2427
+ };
1987
- for e in flat {
2428
+ for e in flat {
1988
- if an.fresh(e) {
2429
+ if an.fresh(e) {
1989
- continue;
2430
+ continue;
2431
+ }
2432
+ if let Some(j) = ofParam(e, &mut binders) {
2433
+ ps.push(j);
2434
+ continue;
2435
+ }
2436
+ // `Map.glue(l, r)`, which returns `l`, `r` or a fresh map.
2437
+ match an.callTargets(e) {
2438
+ Some(targets) => {
2439
+ for (h, args) in targets {
2440
+ if an.fresh_ret.borrow().contains(&h) {
2441
+ continue;
2442
+ }
2443
+ let Some(hs) = an.passes.get(&h) else {
2444
+ ok = false;
2445
+ continue;
2446
+ };
2447
+ for &k in hs {
2448
+ match args.get(k).copied().flatten() {
2449
+ Some(a) if an.fresh(a) => {}
2450
+ Some(a) => match ofParam(a, &mut binders) {
2451
+ Some(j) => ps.push(j),
2452
+ None => ok = false,
2453
+ },
2454
+ None => ok = false,
2455
+ }
2456
+ }
2457
+ }
2458
+ }
2459
+ None => ok = false,
2460
+ }
1990
2461
  }
2462
+ ps.sort();
1991
- match varName(e).and_then(|n| u.params.iter().position(|p| p.name == n && p.plain)) {
2463
+ ps.dedup();
2464
+ if ok {
1992
- Some(j) => {
2465
+ for (j, b) in binders {
2466
+ let v: &mut Vec<String> = passBinders.entry((g, j)).or_default();
1993
- if !ps.contains(&j) {
2467
+ if !v.contains(&b) {
1994
- ps.push(j);
2468
+ v.push(b);
1995
2469
  }
1996
2470
  }
1997
- None => ok = false,
2471
+ passes.insert(g, ps);
1998
2472
  }
1999
2473
  }
2000
- if ok && !ps.is_empty() {
2474
+ let same = passes == an.passes;
2001
- ps.sort();
2002
- passes.insert(g, ps);
2475
+ an.passes = passes;
2476
+ an.passBinders = passBinders;
2477
+ if same {
2478
+ settled = true;
2479
+ break;
2003
2480
  }
2004
2481
  }
2482
+ if !settled {
2005
- an.passes = passes;
2483
+ an.passes.clear();
2484
+ an.passBinders.clear();
2485
+ }
2006
2486
  collectFacts(&mut an);
2007
2487
  let (host, hostMain) = hostShared(&an, src);
2008
2488
  an.escaped.extend(host);
@@ -2247,7 +2727,7 @@ fn hostShared(an: &An, src: &Source) -> (Vec<usize>, Option<(usize, usize)>) {
2247
2727
  let fresh = an.fresh_ret.borrow();
2248
2728
  let main = userMain.or_else(|| find("main"));
2249
2729
  let mainFresh = main.is_some_and(|m| fresh.contains(&m));
2250
- let updateOk = update.is_some_and(|g| fresh.contains(&g) || an.passes.get(&g).is_some_and(|ps| ps == &[0]));
2730
+ let updateOk = update.is_some_and(|g| fresh.contains(&g) || (an.passes.get(&g).is_some_and(|ps| ps == &[0]) && !an.passBinders.contains_key(&(g, 0))));
2251
2731
  let drawKeeps = find(crate::game_entry::GAME_DRAW).is_none_or(|d| {
2252
2732
  let mut seen = HashSet::new();
2253
2733
  let state = an.units[d].params.iter().position(|p| p.ty == stateTy);
@@ -2652,6 +3132,81 @@ fn readsBefore(b: &Block, spread: NodeId, o: &str, g: &str, out: &mut Vec<NodeId
2652
3132
 
2653
3133
  /// The methods whose `self` is only read (see `An.ro`): a greatest fixpoint, since a method may
2654
3134
  /// call another read-only one on `self`.
3135
+ /// Does `p` hold an uppercase name that is no type or variant? Codegen binds it like a lowercase
3136
+ /// one, but `patternBinders` does not list it.
3137
+ fn oddName(an: &An, p: &CasePattern) -> bool {
3138
+ match p {
3139
+ CasePattern::Name(n) => n.chars().next().is_some_and(|c| c.is_uppercase()) && !an.owner.contains_key(n),
3140
+ CasePattern::Class { fields, .. } => fields.iter().any(|f| oddName(an, f)),
3141
+ _ => false,
3142
+ }
3143
+ }
3144
+
3145
+ /// Does case `c` only read the `self` matched at `k` (see `readOnlySelf`)? Its pattern there binds
3146
+ /// no alias of `self`, builds no constructor of the matched variant in tail position, and no binder
3147
+ /// is handed on: a bare argument of a call (but of a method the compiler calls implicitly, like
3148
+ /// `compare`), the receiver of a method that is not read-only, a spread source, a match subject,
3149
+ /// a value bound to another name, or captured by a closure.
3150
+ fn selfMatchReads(an: &An, ro: &HashSet<usize>, c: &Case, k: usize) -> bool {
3151
+ let p = &c.patterns[k];
3152
+ if bindsName(p) || oddName(an, p) {
3153
+ return false;
3154
+ }
3155
+ if !matches!(p, CasePattern::Class { .. }) {
3156
+ return true;
3157
+ }
3158
+ if !reuseTails(an, c, k).is_empty() {
3159
+ return false;
3160
+ }
3161
+ let mut binders = vec![];
3162
+ crate::visit::patternBinders(p, &mut binders);
3163
+ if binders.is_empty() {
3164
+ return true;
3165
+ }
3166
+ let isB = |e: &Expr| varName(e).is_some_and(|n| binders.iter().any(|b| b == n));
3167
+ let mut handed = false;
3168
+ let mut look = |n: Node| {
3169
+ match n {
3170
+ Node::E(e) => match &e.kind {
3171
+ // A closure call (no free fn by that name) never takes its arguments uniquely.
3172
+ ExprKind::FnCall(fc) => handed |= an.isFree(&fc.name).is_some() && fc.args.iter().any(|a| isB(argExpr(a))),
3173
+ ExprKind::Attribute(a) => {
3174
+ if let AttrKind::Method(mc) = &a.attr {
3175
+ let cands = an.cands(mc);
3176
+ if isB(&a.object) && (cands.is_empty() || !cands.iter().all(|g| ro.contains(g))) {
3177
+ handed = true;
3178
+ }
3179
+ let implicit = !cands.is_empty() && cands.iter().all(|&g| IMPLICIT.contains(&an.units[g].name.as_str()));
3180
+ if !implicit && mc.args.iter().any(|x| isB(argExpr(x))) {
3181
+ handed = true;
3182
+ }
3183
+ }
3184
+ }
3185
+ ExprKind::ClassCall(cc) => handed |= cc.spread.as_deref().is_some_and(isB),
3186
+ ExprKind::Closure(_) => walkExpr(e, &mut |m| {
3187
+ if let Node::E(x) = m {
3188
+ handed |= isB(x);
3189
+ }
3190
+ !handed
3191
+ }),
3192
+ _ => {}
3193
+ },
3194
+ Node::S(s) => match &s.kind {
3195
+ StmtKind::Match(m) => handed |= m.subjects.iter().any(isB),
3196
+ StmtKind::Assign(a) => handed |= a.values.iter().any(isB),
3197
+ _ => {}
3198
+ },
3199
+ Node::M(..) => {}
3200
+ }
3201
+ !handed
3202
+ };
3203
+ if let Some(g) = &c.guard {
3204
+ walkExpr(g, &mut look);
3205
+ }
3206
+ walkBlock(&c.body, &mut look);
3207
+ !handed
3208
+ }
3209
+
2655
3210
  fn readOnlySelf(an: &An) -> HashSet<usize> {
2656
3211
  let mut ro: HashSet<usize> =
2657
3212
  (0..an.units.len()).filter(|&g| an.units[g].kind == Kind::Fn && an.units[g].method && an.units[g].hasSelf).collect();
@@ -2665,6 +3220,11 @@ fn readOnlySelf(an: &An) -> HashSet<usize> {
2665
3220
  match n {
2666
3221
  Node::E(e) => match &e.kind {
2667
3222
  ExprKind::Self_ => allSelf.push(e.id),
3223
+ ExprKind::Bind(b) if matches!(b.value.kind, ExprKind::Self_) && b.case.patterns.len() == 1 => {
3224
+ if selfMatchReads(an, &ro, &b.case, 0) {
3225
+ allowed.insert(b.value.id);
3226
+ }
3227
+ }
2668
3228
  ExprKind::Attribute(a) if matches!(a.object.kind, ExprKind::Self_) => match &a.attr {
2669
3229
  AttrKind::Field(_) => {
2670
3230
  allowed.insert(a.object.id);
@@ -2693,6 +3253,16 @@ fn readOnlySelf(an: &An) -> HashSet<usize> {
2693
3253
  }
2694
3254
  }
2695
3255
  }
3256
+ // `match self` reads its fields, unless an arm may take `self` apart to build
3257
+ // from it (a constructor of the matched variant in tail position, or a binder
3258
+ // handed on: then the method may want `self` unique).
3259
+ Node::S(Stmt { kind: StmtKind::Match(m), .. }) => {
3260
+ for (k, sub) in m.subjects.iter().enumerate() {
3261
+ if matches!(sub.kind, ExprKind::Self_) && m.cases.iter().all(|c| selfMatchReads(an, &ro, c, k)) {
3262
+ allowed.insert(sub.id);
3263
+ }
3264
+ }
3265
+ }
2696
3266
  _ => {}
2697
3267
  }
2698
3268
  true
@@ -2710,12 +3280,29 @@ fn readOnlySelf(an: &An) -> HashSet<usize> {
2710
3280
  }
2711
3281
  }
2712
3282
 
3283
+ /// Every field a pattern binds (at any depth) may now be held by its binder as well.
3284
+ fn poisonBinders(an: &An, p: &CasePattern, bound: &mut HashSet<String>) {
3285
+ if let CasePattern::Class { name, fields, .. } = p {
3286
+ let names = fieldsOf(&an.enums, name);
3287
+ for (i, fp) in fields.iter().enumerate() {
3288
+ if matches!(fp, CasePattern::Name(_)) {
3289
+ if let Some(f) = names.as_ref().and_then(|n| n.get(i)) {
3290
+ // The pattern names its own type, unless it is unknown here.
3291
+ bound.insert(fieldKey(an.owner.get(name).map_or(name.as_str(), |t| t.as_str()), f));
3292
+ }
3293
+ }
3294
+ poisonBinders(an, fp, bound);
3295
+ }
3296
+ }
3297
+ }
3298
+
2713
3299
  fn collectFacts(an: &mut An) {
2714
3300
  let mut sites: Vec<Site> = vec![];
2715
3301
  let mut escaped: HashSet<usize> = HashSet::new();
2716
3302
  let mut badField: HashSet<String> = HashSet::new();
2717
3303
  let mut patternBound: HashSet<String> = HashSet::new();
3304
+ let mut fieldWhy: HashMap<String, String> = HashMap::new();
2718
- let mut poisonAll = false;
3305
+ let poisonAll = false;
2719
3306
  let mut spreads: Vec<SpreadSite> = vec![];
2720
3307
  let mut passWrites: Vec<(Vec<String>, Vec<(usize, usize)>)> = vec![];
2721
3308
  let mut varWrites: Vec<(String, usize, String)> = vec![];
@@ -2760,38 +3347,49 @@ fn collectFacts(an: &mut An) {
2760
3347
  }
2761
3348
  true
2762
3349
  });
2763
- let mut pats = |ps: &[CasePattern]| {
2764
- fn rec(an: &An, p: &CasePattern, bound: &mut HashSet<String>, all: &mut bool) {
2765
- if let CasePattern::Class { name, fields, .. } = p {
2766
- let names = fieldsOf(&an.enums, name);
2767
- for (i, fp) in fields.iter().enumerate() {
2768
- if matches!(fp, CasePattern::Name(_)) {
2769
- match names.as_ref().and_then(|n| n.get(i)) {
2770
- Some(f) => {
2771
- // The pattern names its own type, unless it is unknown here.
2772
- bound.insert(fieldKey(an.owner.get(name).map_or(name.as_str(), |t| t.as_str()), f));
2773
- }
2774
- None => {
2775
- // unnamed field of a known type cannot be read as `.f`
2776
- if names.is_none() && !an.enums.is_empty() {
2777
- // unknown type: be conservative only if it could be user-defined
2778
- }
2779
- }
2780
- }
2781
- }
2782
- rec(an, fp, bound, all);
2783
- }
2784
- }
2785
- }
2786
- for p in ps {
2787
- rec(a, p, &mut patternBound, &mut poisonAll);
2788
- }
2789
- };
2790
3350
  walkBlock(&u.block, &mut |n| {
2791
3351
  match n {
2792
3352
  Node::S(Stmt { kind: StmtKind::Match(m), .. }) => {
2793
3353
  for c in &m.cases {
3354
+ for (k, p) in c.patterns.iter().enumerate() {
3355
+ let CasePattern::Class { name, fields, .. } = p else { continue };
3356
+ let names = fieldsOf(&a.enums, name);
3357
+ let owner = a.owner.get(name).map_or(name.as_str(), |t| t.as_str());
3358
+ let subject = m.subjects.get(k).and_then(varName);
3359
+ let consumed = a.consumes(ui, m, k, c).ok();
3360
+ for (i, fp) in fields.iter().enumerate() {
3361
+ match fp {
3362
+ CasePattern::Name(b) if bindsName(fp) => {
3363
+ let Some(f) = names.as_ref().and_then(|n| n.get(i)) else { continue };
3364
+ let key = fieldKey(owner, f);
3365
+ // Only read in the arm, with the matched value left alone there:
3366
+ // no second holder of the field's object (like `x.f.h`).
3367
+ if subject.is_some_and(|x| !caseTouches(c, k, x)) && a.binderReadOnly(c, k, b) {
3368
+ continue;
3369
+ }
3370
+ // Taken out of a value the arm consumes: no second holder once that
3371
+ // value is dead. When it is unique, the binder takes the field over
3372
+ // (`Scan.patternMove`); when it is shared, so is the binder, and every
3373
+ // way the binder could leave (a store, a hand-over, a result, another
3374
+ // match) needs it proved unique.
3375
+ match consumed {
3376
+ Some(_) => {}
3377
+ None => {
3378
+ fieldWhy.entry(key.clone()).or_insert_with(|| format!("a pattern in {} binds it while the value is still used", u.label));
2794
- pats(&c.patterns);
3379
+ patternBound.insert(key);
3380
+ }
3381
+ }
3382
+ }
3383
+ // A name that is not a variant binds the field too (as codegen reads it).
3384
+ CasePattern::Name(n) if !a.owner.contains_key(n) => {
3385
+ if let Some(f) = names.as_ref().and_then(|ns| ns.get(i)) {
3386
+ patternBound.insert(fieldKey(owner, f));
3387
+ }
3388
+ }
3389
+ _ => poisonBinders(a, fp, &mut patternBound),
3390
+ }
3391
+ }
3392
+ }
2795
3393
  }
2796
3394
  }
2797
3395
  Node::S(Stmt { kind: StmtKind::Assign(asg), .. }) => {
@@ -2968,7 +3566,32 @@ fn collectFacts(an: &mut An) {
2968
3566
  allowed.insert(nodeKey(x.object.id));
2969
3567
  }
2970
3568
  }
3569
+ // `if T(.., b, ..) := x`: like one arm of a match, but never a consuming one.
2971
- ExprKind::Bind(b) => pats(&b.case.patterns),
3570
+ ExprKind::Bind(b) => match (varName(&b.value), b.case.patterns.as_slice()) {
3571
+ (Some(x), [CasePattern::Class { name, fields, .. }]) if !caseTouches(&b.case, 0, x) => {
3572
+ let names = fieldsOf(&a.enums, name);
3573
+ let owner = a.owner.get(name).map_or(name.as_str(), |t| t.as_str());
3574
+ for (i, fp) in fields.iter().enumerate() {
3575
+ match fp {
3576
+ CasePattern::Name(n) if bindsName(fp) => {
3577
+ if let Some(f) = names.as_ref().and_then(|ns| ns.get(i)) {
3578
+ if !a.binderReadOnly(&b.case, 0, n) {
3579
+ fieldWhy.entry(fieldKey(owner, f)).or_insert_with(|| format!("`{n} :=` in {} binds it and uses it beyond reads", u.label));
3580
+ patternBound.insert(fieldKey(owner, f));
3581
+ }
3582
+ }
3583
+ }
3584
+ CasePattern::Name(n) if !a.owner.contains_key(n) => {
3585
+ if let Some(f) = names.as_ref().and_then(|ns| ns.get(i)) {
3586
+ patternBound.insert(fieldKey(owner, f));
3587
+ }
3588
+ }
3589
+ _ => poisonBinders(a, fp, &mut patternBound),
3590
+ }
3591
+ }
3592
+ }
3593
+ _ => b.case.patterns.iter().for_each(|p| poisonBinders(a, p, &mut patternBound)),
3594
+ },
2972
3595
  ExprKind::Var(n) => {
2973
3596
  if let Some(g) = a.isFree(n) {
2974
3597
  escaped.insert(g);
@@ -3043,6 +3666,13 @@ fn collectFacts(an: &mut An) {
3043
3666
  an.escaped = escaped;
3044
3667
  an.badField = badField;
3045
3668
  an.patternBound = patternBound;
3669
+ for f in &an.badField {
3670
+ fieldWhy.entry(f.clone()).or_insert_with(|| "it is read as a whole value or written with a value that is not fresh".to_string());
3671
+ }
3672
+ for f in &an.patternBound {
3673
+ fieldWhy.entry(f.clone()).or_insert_with(|| "a pattern binds it".to_string());
3674
+ }
3675
+ *an.ufWhy.borrow_mut() = fieldWhy;
3046
3676
  an.poisonAll = poisonAll;
3047
3677
  an.spreads = spreads;
3048
3678
  an.passWrites = passWrites;
@@ -3120,41 +3750,51 @@ fn solve(an: &An) {
3120
3750
  }
3121
3751
  }
3122
3752
  // Fields poisoned by spreads that are not proved.
3123
- let mut poisoned: HashSet<String> = HashSet::new();
3753
+ let mut poisoned: HashMap<String, String> = HashMap::new();
3754
+ let mut poison = |k: &str, why: &dyn std::ops::Fn() -> String| {
3755
+ if !poisoned.contains_key(k) && an.uf.borrow().contains(k) {
3756
+ poisoned.insert(k.to_string(), why());
3757
+ }
3758
+ };
3124
3759
  for s in &an.spreads {
3125
3760
  if an.spreadProved(s) {
3126
3761
  continue;
3127
3762
  }
3763
+ let why = || format!("a spread in {} that is not in place copies it", an.units[s.unit].label);
3128
3764
  match (fieldsOf(&an.enums, &s.typeName), an.owner.get(&s.typeName)) {
3129
- (Some(all), Some(o)) => poisoned.extend(all.into_iter().filter(|f| !s.given.contains(f)).map(|f| fieldKey(o, &f))),
3765
+ (Some(all), Some(o)) => all.into_iter().filter(|f| !s.given.contains(f)).for_each(|f| poison(&fieldKey(o, &f), &why)),
3130
3766
  _ => {
3131
3767
  // unknown type: cannot tell which fields it copies
3132
- poisoned.extend(an.uf.borrow().iter().cloned());
3768
+ let all: Vec<String> = an.uf.borrow().iter().cloned().collect();
3769
+ all.iter().for_each(|f| poison(f, &why));
3133
3770
  }
3134
3771
  }
3135
3772
  }
3136
3773
  for (f, ui, node) in &an.moves {
3137
3774
  let proved = spreadAt.get(&(*ui, *node)).is_some_and(|v| v.iter().any(|s| an.spreadProved(s)));
3138
3775
  if !proved {
3139
- poisoned.insert(f.clone());
3776
+ poison(f, &|| format!("{} moves it out for a spread that is not in place", an.units[*ui].label));
3140
3777
  }
3141
3778
  }
3142
3779
  for (key, ui, v) in &an.varWrites {
3780
+ if an.uf.borrow().contains(key) {
3143
- if an.varOk(*ui, v).is_err() {
3781
+ if let Err(w) = an.varOk(*ui, v) {
3144
- poisoned.insert(key.clone());
3782
+ poison(key, &|| format!("{} writes `{v}` into it, which may be shared: {w}", an.units[*ui].label));
3783
+ }
3145
3784
  }
3146
3785
  }
3147
3786
  for (key, ui, e) in &an.valueWrites {
3148
3787
  if !an.freshArg(*ui, e, None) && !hostMainCall(an, e) {
3149
- poisoned.insert(key.clone());
3788
+ poison(key, &|| format!("{} writes a value into it that may be shared", an.units[*ui].label));
3150
3789
  }
3151
3790
  }
3152
3791
  for (keys, deps) in &an.passWrites {
3153
3792
  if !deps.iter().all(|&(g, j)| an.passParamOk(g, j)) {
3154
- poisoned.extend(keys.iter().cloned());
3793
+ keys.iter().for_each(|k| poison(k, &|| "an update writes back a value that may be shared".to_string()));
3155
3794
  }
3156
3795
  }
3157
- let removeUf: Vec<String> = an.uf.borrow().iter().filter(|f| poisoned.contains(*f)).cloned().collect();
3796
+ let mut removeUf: Vec<String> = poisoned.keys().cloned().collect();
3797
+ removeUf.sort();
3158
3798
  if removeUp.is_empty() && removeUf.is_empty() {
3159
3799
  break;
3160
3800
  }
@@ -3164,6 +3804,7 @@ fn solve(an: &An) {
3164
3804
  }
3165
3805
  for f in removeUf {
3166
3806
  an.uf.borrow_mut().remove(&f);
3807
+ an.ufWhy.borrow_mut().insert(f.clone(), poisoned.remove(&f).unwrap_or_default());
3167
3808
  }
3168
3809
  }
3169
3810
  an.clearCache();
@@ -3273,6 +3914,7 @@ fn provedIn(an: &An, ui: usize) -> usize {
3273
3914
  .filter(|s| s.unit == ui)
3274
3915
  .filter(|s| s.var.as_ref().is_some_and(|v| an.varOk(ui, v).is_ok()) && s.copies.is_none())
3275
3916
  .count()
3917
+ + reuseIn(an, ui).len()
3276
3918
  }
3277
3919
 
3278
3920
  /// The calls to move to a unique version, per callee: those whose arguments are unique for every
@@ -3280,6 +3922,7 @@ fn provedIn(an: &An, ui: usize) -> usize {
3280
3922
  fn versionPlan(an: &An) -> Vec<(usize, Vec<(usize, NodeId)>)> {
3281
3923
  // Only a fn that runs a spread, itself or further down, can gain from a copy.
3282
3924
  let mut gains: HashSet<usize> = an.spreads.iter().map(|s| s.unit).collect();
3925
+ gains.extend((0..an.units.len()).filter(|&ui| an.reuseCands[ui]));
3283
3926
  loop {
3284
3927
  let before = gains.len();
3285
3928
  let more: Vec<usize> = an.sites.iter().filter(|s| gains.contains(&s.callee)).map(|s| s.caller).collect();
compiler/core/tests/core/main.rs CHANGED
@@ -29,6 +29,7 @@ mod traits_parse_test;
29
29
  mod trmc_test;
30
30
  mod enum_checks_test;
31
31
  mod uniqueness_moves_test;
32
+ mod uniqueness_reuse_test;
32
33
  mod uniqueness_test;
33
34
  mod uniqueness_versions_test;
34
35
  mod visit_test;
compiler/core/tests/core/uniqueness_reuse_test.rs ADDED
@@ -0,0 +1,119 @@
1
+ #![allow(non_snake_case)]
2
+ //! Cell reuse decided by the uniqueness proof: a match that takes a unique value apart may build
3
+ //! the same variant into its cell, and a field binder of it is unique when the field is.
4
+ use plum_core::uniqueness::{markUnique, UniqueReport};
5
+
6
+ fn run(src: &str) -> UniqueReport {
7
+ let mut s = plum_test_support::parseRawSource(src);
8
+ markUnique(&mut s)
9
+ }
10
+
11
+ fn reused(r: &UniqueReport, label: &str) -> bool {
12
+ r.reused.iter().any(|(l, _)| l.starts_with(&format!("{label}:")))
13
+ }
14
+
15
+ /// A persistent tree: `ins` rebuilds the path it walks, `has` only reads.
16
+ const TREE: &str = "\
17
+ enum Tree<T> =
18
+ | Leaf
19
+ | Node(key: Int, val: T, left: Tree<T>, right: Tree<T>)
20
+
21
+ fun ins(self, k: Int, v: T) -> Tree<T> = match self
22
+ Leaf => Node(key: k, val: v, left: Leaf, right: Leaf)
23
+ Node(nk, nv, l, r) =>
24
+ if k < nk
25
+ nl := l.ins(k, v)
26
+ Node(key: nk, val: nv, left: nl, right: r)
27
+ else if k > nk
28
+ nr := r.ins(k, v)
29
+ Node(key: nk, val: nv, left: l, right: nr)
30
+ else
31
+ Node(key: k, val: v, left: l, right: r)
32
+
33
+ fun has(self, k: Int) -> Bool = match self
34
+ Leaf => false
35
+ Node(nk, _, l, r) => if k < nk then l.has(k) else if k > nk then r.has(k) else true
36
+
37
+ fun size(self) -> Int = match self
38
+ Leaf => 0
39
+ Node(_, _, l, r) => l.size() + r.size() + 1
40
+
41
+ fun fill(t: Tree<Int>, i: Int, n: Int) -> Tree<Int> = if i >= n then t else fill(t.ins(i * 7 % 13, i), i + 1, n)
42
+ ";
43
+
44
+ #[test]
45
+ fn a_tree_used_once_reuses_every_cell_on_the_path() {
46
+ let r = run(&format!("{TREE}fun main() -> Int =\n t := fill(Leaf, 0, 13)\n if t.has(3) then t.size() else 0\n"));
47
+ assert!(reused(&r, "Tree.ins"), "{r:?}");
48
+ }
49
+
50
+ #[test]
51
+ fn a_kept_snapshot_stops_reuse() {
52
+ // `a` is updated and still read: `ins` gets a shared tree, and the new tree shares
53
+ // `a`'s subtrees, so no binder of it may be written over.
54
+ let r = run(&format!("{TREE}fun main() -> Int =\n a := fill(Leaf, 0, 13)\n b := a.ins(100, 1)\n b.size() + a.size()\n"));
55
+ assert!(!reused(&r, "Tree.ins"), "{r:?}");
56
+ }
57
+
58
+ #[test]
59
+ fn a_tree_passed_to_two_calls_stops_reuse() {
60
+ let r = run(&format!(
61
+ "{TREE}fun grow(t: Tree<Int>) -> Tree<Int> = t.ins(50, 5)\nfun main() -> Int =\n a := fill(Leaf, 0, 13)\n grow(a).size() + grow(a).size()\n"
62
+ ));
63
+ assert!(!reused(&r, "Tree.ins"), "{r:?}");
64
+ }
65
+
66
+ #[test]
67
+ fn a_tree_in_a_closure_stops_reuse() {
68
+ let r = run(&format!(
69
+ "{TREE}fun twice(f: fn(Int) -> Tree<Int>) -> Int = f(1).size() + f(2).size()\nfun main() -> Int =\n a := fill(Leaf, 0, 13)\n twice(|k| a.ins(k, k))\n"
70
+ ));
71
+ assert!(!reused(&r, "Tree.ins"), "{r:?}");
72
+ }
73
+
74
+ #[test]
75
+ fn a_method_that_hands_out_a_subtree_stops_reuse() {
76
+ // `leftOf` reads `self` only, but its result shares `left` with the tree it came from.
77
+ let r = run(&format!(
78
+ "{TREE}fun leftOf(t: Tree<Int>) -> Tree<Int> = match t\n Leaf => Leaf\n Node(_, _, l, _) => l\nfun main() -> Int =\n a := fill(Leaf, 0, 13)\n s := leftOf(a)\n b := a.ins(4, 4)\n s.size() + b.size()\n"
79
+ ));
80
+ assert!(!reused(&r, "Tree.ins"), "{r:?}");
81
+ }
82
+
83
+ #[test]
84
+ fn an_arm_that_still_reads_the_matched_value_does_not_reuse_it() {
85
+ let src = "\
86
+ enum Box =
87
+ | Empty
88
+ | Full(n: Int, rest: Box)
89
+
90
+ fun again(b: Box) -> Box = match b
91
+ Empty => Empty
92
+ Full(n, rest) => if n > 3 then b else Full(n: n + 1, rest: rest)
93
+
94
+ fun main() -> Int = match again(Full(n: 1, rest: Empty))
95
+ Empty => 0
96
+ Full(n, _) => n
97
+ ";
98
+ let r = run(src);
99
+ assert!(!reused(&r, "again"), "{r:?}");
100
+ }
101
+
102
+ #[test]
103
+ fn a_matched_value_compared_by_identity_is_not_reused() {
104
+ let src = "\
105
+ enum Box =
106
+ | Empty
107
+ | Full(n: Int, rest: Box)
108
+
109
+ fun bump(b: Box) -> Box = match b
110
+ Empty => Empty
111
+ Full(n, rest) => Full(n: n + 1, rest: rest)
112
+
113
+ fun main() -> Bool =
114
+ a := Full(n: 1, rest: Empty)
115
+ @sameRef(a, bump(a))
116
+ ";
117
+ let r = run(src);
118
+ assert!(!reused(&r, "bump"), "{r:?}");
119
+ }
compiler/driver/src/lib.rs CHANGED
@@ -101,6 +101,8 @@ pub fn inPlaceRun(copy: &mut Source, origins: Option<&plum_core::fip::FipOrigins
101
101
  let mut notes: Vec<String> = rep.versions.iter().cloned().collect();
102
102
  notes.extend(rep.proved.iter().map(|l| format!("unique spread at {l}")));
103
103
  notes.extend(rep.unproved.iter().map(|(l, why)| format!("uniqueness: not in place {l}: {why}")));
104
+ notes.extend(rep.reused.iter().map(|(l, x)| format!("reuse: the cell of `{x}` at {l}")));
105
+ notes.extend(rep.notReused.iter().map(|(l, why)| format!("reuse: no cell reused at {l}: {why}")));
104
106
  let errors = plum_core::timing::time("fip", || plum_core::fip::diagnostics(copy, &rep, origins));
105
107
  notes.retain(|n| !n.is_empty());
106
108
  notes.extend(plum_core::timing::time("reuse", || plum_core::reuse::markReuse(copy)));
compiler/wasm-codegen/src/expr.rs CHANGED
@@ -628,14 +628,21 @@ fn compileExprNode(
628
628
  // Cell reuse (`markReuse`): the dead matched cell of the same variant and
629
629
  // enum type takes the new field values in place of a fresh `struct.new`.
630
630
  if let Some(r) = call.reuse.as_deref() {
631
- let rv = ast::Expr::Var(r.to_string());
631
+ let rv = if r == "self" { ast::Expr::new(ast::ExprKind::Self_) } else { ast::Expr::Var(r.to_string()) };
632
+ // The cell's own type, type arguments included: a generic enum's copy for these
633
+ // arguments has one struct per variant, so only the same arguments share it.
634
+ let sameTy = match localType(r, ctx) {
635
+ Some(ref t @ (PlumType::TNamed(ref n) | PlumType::TApp(ref n, _))) => {
636
+ *n == info.enum_name && crate::values::canonTy(&plum_checker::types::substitute(t, ctx.unit_subst)) == crate::values::canonTy(&plum_checker::types::substitute(&ety, ctx.unit_subst))
637
+ }
638
+ _ => false,
639
+ };
632
640
  let same = call.spread.is_none()
633
641
  && call.fields.len() == field_names.len()
634
642
  && field_names
635
643
  .iter()
636
644
  .all(|n| call.fields.iter().any(|fa| &fa.name == n))
637
- && info.generics.is_empty()
645
+ && sameTy;
638
- && matches!(localType(r, ctx), Some(PlumType::TNamed(_)));
639
646
  if same {
640
647
  for (field_idx, field_name) in field_names.iter().enumerate() {
641
648
  let i = call
docs/performance.md CHANGED
@@ -23,7 +23,7 @@ fun bump(s: Cell) -> Cell =
23
23
  Cell(..s, x: s.x + 1.0)
24
24
  ```
25
25
 
26
- **Reuses memory.** Rebuilding a value of the same shape can reuse the old one.
26
+ **Reuses memory.** Rebuilding a value of the same shape can reuse the old one. A `match` that takes apart a value nothing else holds may build the same variant into its cell, in generic types and methods too: `m.with(k, v)` on such a `Map` writes the new path into the old one's cells instead of allocating it. A value something else can still reach (a snapshot, a field, a closure, a second call) is never written. This is decided for a type's fields over the whole program, so while any code keeps old versions of a `Map` around, every `Map` update copies its path.
27
27
 
28
28
  **Inlines closures.** A closure passed straight to a function that only calls it becomes a direct copy of the code, with no allocation.
29
29
 
std/collections/Map.plum CHANGED
@@ -130,7 +130,7 @@ enum Map<K, V> =
130
130
 
131
131
  # The map with `k` mapped to `v`, replacing the value of an existing `k`.
132
132
  fun with(self, k: K, v: V) -> Map<K, V> = match self
133
- MapTip => MapBin(size: 1, key: k, value: v, left: self, right: self)
133
+ MapTip => MapBin(size: 1, key: k, value: v, left: MapTip, right: MapTip)
134
134
  MapBin(n, nk, nv, l, r) =>
135
135
  c := k.compare(nk)
136
136
  if c < 0
@@ -453,7 +453,9 @@ enum Map<K, V> =
453
453
  # order. Each step is O(log n); `m.entries()` is cheaper when every entry is read.
454
454
  fun next(self) -> Option<Pair<Pair<K, V>, Map<K, V>>> = match self
455
455
  MapTip => None
456
+ MapBin(_, _, _, _, _) =>
457
+ first := self.min()!
456
- MapBin(_, _, _, _, _) => Some(Pair(first: self.min()!, second: self.removeMin()))
458
+ Some(Pair(first: first, second: self.removeMin()))
457
459
 
458
460
  # Same keys with equal values (`m == n`); the shapes may differ.
459
461
  fun eq(self, o: Map<K, V>) -> Bool =
@@ -482,7 +484,8 @@ enum Map<K, V> =
482
484
 
483
485
  # A node over `l` and `r` with its size worked out (no rebalancing).
484
486
  fun bin(k: K, v: V, l: Map<K, V>, r: Map<K, V>) -> Map<K, V> =
487
+ n := l.length() + r.length() + 1
485
- MapBin(size: l.length() + r.length() + 1, key: k, value: v, left: l, right: r)
488
+ MapBin(size: n, key: k, value: v, left: l, right: r)
486
489
 
487
490
  # `bin`, rotating when one side holds more than 3 times the other's entries (after one
488
491
  # insert or remove below, or one `link`/`merge` step).
@@ -507,7 +510,8 @@ enum Map<K, V> =
507
510
  else
508
511
  match rl
509
512
  MapBin(_, mk, mv, ml, mr) => Map.bin(mk, mv, Map.bin(k, v, l, ml), Map.bin(rk, rv, mr, rr))
513
+ # `r` again, built from its parts: the arm took `r` apart.
510
- MapTip => Map.bin(k, v, l, r)
514
+ MapTip => Map.bin(k, v, l, Map.bin(rk, rv, rl, rr))
511
515
  MapTip => Map.bin(k, v, l, r)
512
516
 
513
517
  # The mirror of `rotateLeft`.
@@ -518,7 +522,7 @@ enum Map<K, V> =
518
522
  else
519
523
  match lr
520
524
  MapBin(_, mk, mv, ml, mr) => Map.bin(mk, mv, Map.bin(lk, lv, ll, ml), Map.bin(k, v, mr, r))
521
- MapTip => Map.bin(k, v, l, r)
525
+ MapTip => Map.bin(k, v, Map.bin(lk, lv, ll, lr), r)
522
526
  MapTip => Map.bin(k, v, l, r)
523
527
 
524
528
  # `l` and `r` joined, where every key of `l` is before every key of `r` and the two are
@@ -536,42 +540,53 @@ enum Map<K, V> =
536
540
  Map.balance(m.first, m.second, l, r.removeMin())
537
541
 
538
542
  # `l` and `r` joined, where every key of `l` is before every key of `r`, of any sizes.
543
+ # Each side is taken apart only where its parts are used, so an update can build into its cells.
539
- fun merge(l: Map<K, V>, r: Map<K, V>) -> Map<K, V> = match l
544
+ fun merge(l: Map<K, V>, r: Map<K, V>) -> Map<K, V> =
545
+ sl := l.length()
546
+ sr := r.length()
547
+ if sl == 0
548
+ r
540
- MapTip => r
549
+ else if sr == 0
550
+ l
541
- MapBin(sl, lk, lv, ll, lr) =>
551
+ else if 3 * sl < sr
542
552
  match r
553
+ MapBin(_, rk, rv, rl, rr) => Map.balance(rk, rv, Map.merge(l, rl), rr)
543
554
  MapTip => l
544
- MapBin(sr, rk, rv, rl, rr) =>
545
- if 3 * sl < sr
546
- Map.balance(rk, rv, Map.merge(l, rl), rr)
547
- else if 3 * sr < sl
555
+ else if 3 * sr < sl
556
+ match l
548
- Map.balance(lk, lv, ll, Map.merge(lr, r))
557
+ MapBin(_, lk, lv, ll, lr) => Map.balance(lk, lv, ll, Map.merge(lr, r))
558
+ MapTip => r
549
- else
559
+ else
550
- Map.glue(l, r)
560
+ Map.glue(l, r)
551
561
 
552
562
  # `l`, then `k`, then `r`, where every key of `l` is before `k` and `k` before every key
553
563
  # of `r`, of any sizes: descends the larger side until the two are balanced.
554
- fun link(k: K, v: V, l: Map<K, V>, r: Map<K, V>) -> Map<K, V> = match l
564
+ fun link(k: K, v: V, l: Map<K, V>, r: Map<K, V>) -> Map<K, V> =
565
+ sl := l.length()
566
+ sr := r.length()
567
+ if sl == 0
555
- MapTip => r.insertMin(k, v)
568
+ r.insertMin(k, v)
569
+ else if sr == 0
570
+ l.insertMax(k, v)
556
- MapBin(sl, lk, lv, ll, lr) =>
571
+ else if 3 * sl < sr
557
572
  match r
573
+ MapBin(_, rk, rv, rl, rr) => Map.balance(rk, rv, Map.link(k, v, l, rl), rr)
558
- MapTip => l.insertMax(k, v)
574
+ MapTip => Map.bin(k, v, l, r)
559
- MapBin(sr, rk, rv, rl, rr) =>
560
- if 3 * sl < sr
561
- Map.balance(rk, rv, Map.link(k, v, l, rl), rr)
562
- else if 3 * sr < sl
575
+ else if 3 * sr < sl
576
+ match l
563
- Map.balance(lk, lv, ll, Map.link(k, v, lr, r))
577
+ MapBin(_, lk, lv, ll, lr) => Map.balance(lk, lv, ll, Map.link(k, v, lr, r))
578
+ MapTip => Map.bin(k, v, l, r)
564
- else
579
+ else
565
- Map.bin(k, v, l, r)
580
+ Map.bin(k, v, l, r)
566
581
 
567
582
  # Adds `k`, which is before every key here.
568
583
  fun insertMin(self, k: K, v: V) -> Map<K, V> = match self
569
- MapTip => MapBin(size: 1, key: k, value: v, left: self, right: self)
584
+ MapTip => MapBin(size: 1, key: k, value: v, left: MapTip, right: MapTip)
570
585
  MapBin(_, nk, nv, l, r) => Map.balance(nk, nv, l.insertMin(k, v), r)
571
586
 
572
587
  # Adds `k`, which is after every key here.
573
588
  fun insertMax(self, k: K, v: V) -> Map<K, V> = match self
574
- MapTip => MapBin(size: 1, key: k, value: v, left: self, right: self)
589
+ MapTip => MapBin(size: 1, key: k, value: v, left: MapTip, right: MapTip)
575
590
  MapBin(_, nk, nv, l, r) => Map.balance(nk, nv, l, r.insertMax(k, v))
576
591
 
577
592
  # This map cut at `k`.
tests/fbip/map_persistence/closure.plum ADDED
@@ -0,0 +1,26 @@
1
+ # A map captured by a closure: each call of the closure starts from the same map.
2
+ import std/Int
3
+ import std/Bool
4
+ import std/Str
5
+ import std/Option
6
+ import std/collections/List
7
+ import std/collections/Map
8
+ import std/collections/Set
9
+
10
+ # `n` entries: key `i * 37 % 101` (distinct for `n` up to 101) holds `i`.
11
+ fun fillTo(m: Map<Int, Int>, i: Int, n: Int) -> Map<Int, Int> = if i >= n then m else fillTo(m.with(i * 37 % 101, i), i + 1, n)
12
+
13
+ # Does `m` hold exactly the entries `fillTo(.., 0, n)` makes?
14
+ fun holds(m: Map<Int, Int>, n: Int, i: Int) -> Bool = if i >= n then m.length() == n else m.getOr(i * 37 % 101, -1) == i && holds(m, n, i + 1)
15
+
16
+ fun twice(f: fn(Int) -> Map<Int, Int>) -> Int = f(1000).length() * 1000 + f(1001).getOr(1001, 0)
17
+
18
+ test "a captured map is the same for every call"
19
+ a := fillTo(Map.empty(), 0, 60)
20
+ grow := |k: Int| a.with(k, k).with(37, 0)
21
+ assert twice(grow) == 61 * 1000 + 1001
22
+ x := grow(2000)
23
+ y := grow(2001)
24
+ assert x.getOr(2001, 0) == 0 && y.getOr(2000, 0) == 0
25
+ assert x.getOr(37, -1) == 0
26
+ assert holds(a, 60, 0)
tests/fbip/map_persistence/combine.plum ADDED
@@ -0,0 +1,30 @@
1
+ # union, remove and split on maps that are still used afterwards.
2
+ import std/Int
3
+ import std/Bool
4
+ import std/Str
5
+ import std/Option
6
+ import std/collections/List
7
+ import std/collections/Map
8
+ import std/collections/Set
9
+
10
+ # `n` entries: key `i * 37 % 101` (distinct for `n` up to 101) holds `i`.
11
+ fun fillTo(m: Map<Int, Int>, i: Int, n: Int) -> Map<Int, Int> = if i >= n then m else fillTo(m.with(i * 37 % 101, i), i + 1, n)
12
+
13
+ # Does `m` hold exactly the entries `fillTo(.., 0, n)` makes?
14
+ fun holds(m: Map<Int, Int>, n: Int, i: Int) -> Bool = if i >= n then m.length() == n else m.getOr(i * 37 % 101, -1) == i && holds(m, n, i + 1)
15
+
16
+ test "union, remove and split leave their inputs as they were"
17
+ a := fillTo(Map.empty(), 0, 60)
18
+ b := fillTo(Map.empty(), 40, 101).with(1000, 9)
19
+ u := a.union(b)
20
+ r := a.remove(37).remove(0)
21
+ p := a.split(50)
22
+ assert holds(a, 60, 0)
23
+ assert b.length() == 62 && b.getOr(1000, 0) == 9 && b.getOr(0, -1) == -1
24
+ assert u.length() == 102 && holds(u.remove(1000), 101, 0)
25
+ assert r.length() == 58 && r.getOr(37, -1) == -1
26
+ assert p.first.length() + p.second.length() + 1 == 60
27
+ assert p.first.keys().all(|k| k < 50) && p.second.keys().all(|k| k > 50)
28
+ assert holds(a, 60, 0)
29
+ q := u.split(50)
30
+ assert q.first.union(q.second).with(50, u.getOr(50, 0)).length() == u.length()
tests/fbip/map_persistence/field.plum ADDED
@@ -0,0 +1,35 @@
1
+ # A map stored in a struct field and updated through it: older holders keep their map.
2
+ import std/Int
3
+ import std/Bool
4
+ import std/Str
5
+ import std/Option
6
+ import std/collections/List
7
+ import std/collections/Map
8
+ import std/collections/Set
9
+
10
+ # `n` entries: key `i * 37 % 101` (distinct for `n` up to 101) holds `i`.
11
+ fun fillTo(m: Map<Int, Int>, i: Int, n: Int) -> Map<Int, Int> = if i >= n then m else fillTo(m.with(i * 37 % 101, i), i + 1, n)
12
+
13
+ # Does `m` hold exactly the entries `fillTo(.., 0, n)` makes?
14
+ fun holds(m: Map<Int, Int>, n: Int, i: Int) -> Bool = if i >= n then m.length() == n else m.getOr(i * 37 % 101, -1) == i && holds(m, n, i + 1)
15
+
16
+ struct Holder(m: Map<Int, Int>, n: Int)
17
+
18
+ fun step(h: Holder, k: Int) -> Holder = Holder(..h, m: h.m.with(k, k * 2), n: h.n + 1)
19
+
20
+ fun steps(h: Holder, k: Int, n: Int) -> Holder = if k >= n then h else steps(step(h, 200 + k), k + 1, n)
21
+
22
+ test "a map in a field updated through it, the old holder kept"
23
+ h0 := Holder(m: fillTo(Map.empty(), 0, 60), n: 0)
24
+ h1 := step(h0, 500)
25
+ h2 := step(h1, 501)
26
+ assert holds(h0.m, 60, 0)
27
+ assert h1.m.getOr(500, 0) == 1000 && h1.m.getOr(501, 0) == 0 && h1.m.length() == 61
28
+ assert h2.m.getOr(501, 0) == 1002 && h2.m.length() == 62
29
+ assert h0.n == 0 && h2.n == 2
30
+
31
+ test "a map in a field updated many times with nothing else holding it"
32
+ h := steps(Holder(m: fillTo(Map.empty(), 0, 30), n: 0), 0, 40)
33
+ assert h.n == 40 && h.m.length() == 70
34
+ assert holds(h.m.filter(|k, v| k < 101), 30, 0)
35
+ assert h.m.getOr(239, 0) == 478
tests/fbip/map_persistence/linear.plum ADDED
@@ -0,0 +1,27 @@
1
+ # A map used once at a time: every update may build into the cells of the map it replaces
2
+ # (the compiler proves no one else holds them). The results must be those of fresh copies.
3
+ import std/Int
4
+ import std/Bool
5
+ import std/Str
6
+ import std/Option
7
+ import std/collections/List
8
+ import std/collections/Map
9
+
10
+ # `n` entries: key `i * 37 % 101` (distinct for `n` up to 101) holds `i`.
11
+ fun fillTo(m: Map<Int, Int>, i: Int, n: Int) -> Map<Int, Int> = if i >= n then m else fillTo(m.with(i * 37 % 101, i), i + 1, n)
12
+
13
+ # Does `m` hold exactly the entries `fillTo(.., 0, n)` makes?
14
+ fun holds(m: Map<Int, Int>, n: Int, i: Int) -> Bool = if i >= n then m.length() == n else m.getOr(i * 37 % 101, -1) == i && holds(m, n, i + 1)
15
+
16
+ test "a map filled one entry at a time holds every entry"
17
+ m := fillTo(Map.empty(), 0, 101)
18
+ assert holds(m, 101, 0)
19
+ assert m.keys().length() == 101
20
+
21
+ test "updates and removals of a map nothing else holds"
22
+ m := fillTo(Map.empty(), 0, 60).with(37, -5).remove(74).with(500, 1)
23
+ assert m.getOr(37, 0) == -5
24
+ assert m.getOr(74, 0) == 0
25
+ assert m.getOr(500, 0) == 1
26
+ assert m.length() == 60
27
+ assert m.getOr(0, -1) == 0
tests/fbip/map_persistence/many_snapshots.plum ADDED
@@ -0,0 +1,31 @@
1
+ # 100 snapshots of a growing map, each kept: every one must still hold what it held.
2
+ import std/Int
3
+ import std/Bool
4
+ import std/Str
5
+ import std/Option
6
+ import std/collections/List
7
+ import std/collections/Map
8
+ import std/collections/Set
9
+
10
+ # `n` entries: key `i * 37 % 101` (distinct for `n` up to 101) holds `i`.
11
+ fun fillTo(m: Map<Int, Int>, i: Int, n: Int) -> Map<Int, Int> = if i >= n then m else fillTo(m.with(i * 37 % 101, i), i + 1, n)
12
+
13
+ # Does `m` hold exactly the entries `fillTo(.., 0, n)` makes?
14
+ fun holds(m: Map<Int, Int>, n: Int, i: Int) -> Bool = if i >= n then m.length() == n else m.getOr(i * 37 % 101, -1) == i && holds(m, n, i + 1)
15
+
16
+ fun snaps(m: Map<Int, Int>, i: Int, acc: List<Map<Int, Int>>) -> List<Map<Int, Int>> =
17
+ if i >= 100
18
+ acc
19
+ else
20
+ next := m.with(i * 37 % 101, i)
21
+ snaps(next, i + 1, Cons(head: next, tail: acc))
22
+
23
+ # Snapshot `i` of `xs` (newest first) holds the first `i + 1` entries.
24
+ fun allHold(xs: List<Map<Int, Int>>, i: Int) -> Bool = match xs
25
+ Nil => i == -1
26
+ Cons(m, rest) => holds(m, i + 1, 0) && allHold(rest, i - 1)
27
+
28
+ test "every one of 100 snapshots is intact"
29
+ xs := snaps(Map.empty(), 0, Nil)
30
+ assert xs.length() == 100
31
+ assert allHold(xs, 99)
tests/fbip/map_persistence/snapshot.plum ADDED
@@ -0,0 +1,31 @@
1
+ # A map kept in a variable while a newer version is updated: the kept one must not change.
2
+ import std/Int
3
+ import std/Bool
4
+ import std/Str
5
+ import std/Option
6
+ import std/collections/List
7
+ import std/collections/Map
8
+ import std/collections/Set
9
+
10
+ # `n` entries: key `i * 37 % 101` (distinct for `n` up to 101) holds `i`.
11
+ fun fillTo(m: Map<Int, Int>, i: Int, n: Int) -> Map<Int, Int> = if i >= n then m else fillTo(m.with(i * 37 % 101, i), i + 1, n)
12
+
13
+ # Does `m` hold exactly the entries `fillTo(.., 0, n)` makes?
14
+ fun holds(m: Map<Int, Int>, n: Int, i: Int) -> Bool = if i >= n then m.length() == n else m.getOr(i * 37 % 101, -1) == i && holds(m, n, i + 1)
15
+
16
+ test "a kept snapshot is unchanged by updates of the new version"
17
+ a := fillTo(Map.empty(), 0, 60)
18
+ b := a.with(1000, 1).with(37, -1).remove(74).with(2000, 55)
19
+ assert holds(a, 60, 0)
20
+ assert b.getOr(1000, 0) == 1 && b.getOr(37, 0) == -1 && b.getOr(74, 0) == 0
21
+ assert b.length() == 61
22
+ c := b.with(1001, 2)
23
+ assert b.getOr(1001, 0) == 0
24
+ assert c.getOr(1001, 0) == 2 && c.length() == 62
25
+ assert holds(a, 60, 0)
26
+
27
+ test "a kept set is unchanged by updates of the new version"
28
+ a := 0.until(40).fold(Set<Int>(), |acc, i| acc.add(i))
29
+ b := a.add(100).remove(7).add(101)
30
+ assert a.length() == 40 && a.contains(7) && !a.contains(100)
31
+ assert b.length() == 41 && !b.contains(7) && b.contains(101)
tests/fbip/map_persistence/two_calls.plum ADDED
@@ -0,0 +1,27 @@
1
+ # One map passed to two functions that each update it.
2
+ import std/Int
3
+ import std/Bool
4
+ import std/Str
5
+ import std/Option
6
+ import std/collections/List
7
+ import std/collections/Map
8
+ import std/collections/Set
9
+
10
+ # `n` entries: key `i * 37 % 101` (distinct for `n` up to 101) holds `i`.
11
+ fun fillTo(m: Map<Int, Int>, i: Int, n: Int) -> Map<Int, Int> = if i >= n then m else fillTo(m.with(i * 37 % 101, i), i + 1, n)
12
+
13
+ # Does `m` hold exactly the entries `fillTo(.., 0, n)` makes?
14
+ fun holds(m: Map<Int, Int>, n: Int, i: Int) -> Bool = if i >= n then m.length() == n else m.getOr(i * 37 % 101, -1) == i && holds(m, n, i + 1)
15
+
16
+ fun grow(m: Map<Int, Int>, k: Int) -> Map<Int, Int> = m.with(k, k).with(k + 1, k)
17
+
18
+ fun shrink(m: Map<Int, Int>) -> Map<Int, Int> = m.remove(0).remove(37)
19
+
20
+ test "a map passed to two updating functions"
21
+ a := fillTo(Map.empty(), 0, 60)
22
+ g := grow(a, 300)
23
+ s := shrink(a)
24
+ assert holds(a, 60, 0)
25
+ assert g.length() == 62 && g.getOr(301, 0) == 300
26
+ assert s.length() == 58 && s.getOr(37, -1) == -1 && s.getOr(74, -1) == 2
27
+ assert g.getOr(37, -1) == 1