plum

#treesitter#compiler#wasm

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

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


b369d7f — Peter John 2026-11-07T03:11:32+05:30
Simpler language: last-use moves in the in-place proof
compiler/core/src/uniqueness.rs CHANGED
@@ -416,6 +416,14 @@ struct An {
416
416
  ro: HashSet<usize>,
417
417
  /// `Array` methods that always return a new array.
418
418
  arrayFresh: HashSet<usize>,
419
+ /// Reads `o.f` that move field `f` out of `o` while `o`'s one spread overwrites `f` (see
420
+ /// `collectMoves`), by node id.
421
+ moveReads: HashSet<NodeId>,
422
+ /// `(field, unit, spread node)` per move: the field stays unique only while that spread is proved.
423
+ moves: Vec<(String, usize, NodeId)>,
424
+ /// Variable checks in progress, and whether one of them has been answered by assuming it holds.
425
+ active: RefCell<HashSet<(usize, String, bool, bool)>>,
426
+ assumed: std::cell::Cell<bool>,
419
427
  }
420
428
 
421
429
  struct SpreadSite {
@@ -459,6 +467,11 @@ impl An {
459
467
  match &e.kind {
460
468
  ExprKind::ClassCall(_) => true,
461
469
  ExprKind::InlineIf(i) => self.fresh(&i.then) && self.fresh(&i.else_),
470
+ // A block value is as fresh as its last values.
471
+ ExprKind::Block(b) => {
472
+ let mut tails = vec![];
473
+ collectTails(b, &mut tails) && !tails.is_empty() && tails.iter().all(|t| self.fresh(t))
474
+ }
462
475
  ExprKind::FnCall(c) => self.isFree(&c.name).is_some_and(|g| self.fresh_ret.borrow().contains(&g)),
463
476
  ExprKind::Attribute(a) => match &a.attr {
464
477
  AttrKind::Method(c) => {
@@ -629,8 +642,22 @@ impl An {
629
642
  if let Some(r) = self.cache.borrow().get(&key) {
630
643
  return r.clone();
631
644
  }
645
+ // A check that meets itself again (a variable bound to the result of a call that passes
646
+ // another unique variable through, which is bound back to the first) is assumed to hold:
647
+ // every value round the cycle comes from a fresh value outside it. Answers reached on an
648
+ // assumption are kept only once the outermost check is done.
649
+ if !self.active.borrow_mut().insert(key.clone()) {
650
+ self.assumed.set(true);
651
+ return Ok(());
652
+ }
632
653
  let r = self.varOkRaw(unit, v, strict, entryUnique);
654
+ self.active.borrow_mut().remove(&key);
655
+ if self.active.borrow().is_empty() {
656
+ self.assumed.set(false);
633
- self.cache.borrow_mut().insert(key, r.clone());
657
+ self.cache.borrow_mut().insert(key, r.clone());
658
+ } else if !self.assumed.get() {
659
+ self.cache.borrow_mut().insert(key, r.clone());
660
+ }
634
661
  r
635
662
  }
636
663
 
@@ -649,8 +676,8 @@ impl An {
649
676
  return Err(why.unwrap_or_else(|| format!("a caller of `{}` may pass a shared `{v}`", u.name)));
650
677
  }
651
678
  }
652
- let mut s = Scan { an: self, v, strict, boundDepth: if param.is_some() { Some(0) } else { None }, err: None };
679
+ let mut s = Scan { an: self, unit, v, strict, boundDepth: if param.is_some() { Some(0) } else { None }, err: None };
653
- s.block(&u.block, true, 0);
680
+ s.block(&u.block, true, false, 0);
654
681
  if let Some(e) = s.err {
655
682
  return Err(e);
656
683
  }
@@ -679,11 +706,20 @@ impl An {
679
706
  if site.inClosure {
680
707
  return Err("an argument is passed from inside a closure".to_string());
681
708
  }
709
+ if self.moveReads.contains(&e.id) {
710
+ let ExprKind::Attribute(a) = &e.kind else { unreachable!() };
711
+ 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")) };
713
+ }
682
714
  match &e.kind {
683
715
  ExprKind::Var(_) | ExprKind::Self_ => self.varOk(site.caller, varName(e).unwrap()),
684
716
  ExprKind::Attribute(a) => {
685
717
  let AttrKind::Field(f) = &a.attr else {
718
+ return if self.freshArg(site.caller, e, None) {
719
+ Ok(())
720
+ } else {
686
- return Err("an argument is a method call result that may be shared".to_string());
721
+ Err("an argument is a method call result that may be shared".to_string())
722
+ };
687
723
  };
688
724
  let ok = match &site.assignBack {
689
725
  Some(AssignTarget::Field(tobj, tf)) => tf == f && **tobj == a.object,
@@ -698,15 +734,49 @@ impl An {
698
734
  Err(format!("field `{f}` may be shared"))
699
735
  }
700
736
  }
737
+ ExprKind::FnCall(_) => {
738
+ if self.freshArg(site.caller, e, None) {
739
+ Ok(())
740
+ } else {
741
+ Err("an argument may be shared".to_string())
742
+ }
743
+ }
701
744
  _ => Err("an argument may be shared".to_string()),
702
745
  }
703
746
  }
747
+
748
+ /// Is `e` a value no one else holds: fresh, or a call of fns that return fresh values or
749
+ /// their own parameters, handed (only) such values? A unique variable of `unit` counts when
750
+ /// the call is its last use (checked by the variable's own scan). `not`: the variable being
751
+ /// scanned, which cannot vouch for itself here.
752
+ fn freshArg(&self, unit: usize, e: &Expr, not: Option<&str>) -> bool {
753
+ if self.fresh(e) {
754
+ return true;
755
+ }
756
+ if let Some(n) = varName(e) {
757
+ return Some(n) != not && self.varOk(unit, n).is_ok();
758
+ }
759
+ let same = |a: &Expr| self.freshArg(unit, a, not);
760
+ match self.passDeps(e, &same) {
761
+ Some(deps) => deps.iter().all(|&(g, j)| self.passParamOk(g, j)),
762
+ None => false,
763
+ }
764
+ }
765
+
766
+ /// A read `o.f` that moves the field out of `o` (see `collectMoves`), whose field is unique.
767
+ 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)))
772
+ }
704
773
  }
705
774
 
706
775
  // ---------- per-variable scan ----------
707
776
 
708
777
  struct Scan<'a> {
709
778
  an: &'a An,
779
+ unit: usize,
710
780
  v: &'a str,
711
781
  strict: bool,
712
782
  boundDepth: Option<usize>,
@@ -724,24 +794,60 @@ impl<'a> Scan<'a> {
724
794
  isVar(e, self.v)
725
795
  }
726
796
 
797
+ /// Does `e` mention the variable anywhere (a closure body included)?
798
+ fn mentions(&self, e: &Expr) -> bool {
799
+ let mut found = false;
800
+ walkExpr(e, &mut |n| {
801
+ if let Node::E(x) = n {
802
+ if isVar(x, self.v) {
803
+ found = true;
804
+ }
805
+ }
806
+ !found
807
+ });
808
+ found
809
+ }
810
+
811
+ fn mentionsStmts(&self, ss: &[Stmt]) -> bool {
812
+ let mut found = false;
813
+ for s in ss {
814
+ walkStmt(s, &mut |n| {
815
+ if let Node::E(x) = n {
816
+ if isVar(x, self.v) {
817
+ found = true;
818
+ }
819
+ }
820
+ !found
821
+ });
822
+ }
823
+ found
824
+ }
825
+
826
+ fn mentionsBlock(&self, b: &Block) -> bool {
827
+ self.mentionsStmts(&b.stmts)
828
+ }
829
+
727
830
  /// Walk `e` where a bare use of the variable is not allowed.
728
- fn operand(&mut self, e: &Expr, why: String) {
831
+ fn operand(&mut self, e: &Expr, live: bool, why: String) {
729
832
  if self.bare(e) {
730
833
  self.fail(why);
731
834
  } else {
732
- self.expr(e, false, false);
835
+ self.expr(e, false, live);
733
836
  }
734
837
  }
735
838
 
839
+ /// `live`: the variable is mentioned after the block, in the order things run.
736
- fn block(&mut self, b: &Block, tail: bool, depth: usize) {
840
+ fn block(&mut self, b: &Block, tail: bool, live: bool, depth: usize) {
737
841
  let n = b.stmts.len();
738
842
  for (i, s) in b.stmts.iter().enumerate() {
843
+ let later = self.mentionsStmts(&b.stmts[i + 1..]);
739
- self.stmt(s, tail && i + 1 == n, depth);
844
+ self.stmt(s, tail && i + 1 == n, live || later, depth);
740
845
  }
741
846
  }
742
847
 
743
848
  /// May `v` be bound to `val`? A fresh value, or (outside strict mode) the result of a fn
744
- /// returning a parameter we hand it unique: a fresh argument, or `v` itself in `v = g(v)`.
849
+ /// returning a parameter we hand it unique: a fresh argument, another unique variable at its
850
+ /// last use, or a field moved out of a unique owner that is overwritten in the same update.
745
851
  fn bindingOk(&self, val: &Expr, declare: bool) -> bool {
746
852
  if self.an.fresh(val) {
747
853
  return true;
@@ -749,19 +855,18 @@ impl<'a> Scan<'a> {
749
855
  if self.strict {
750
856
  return false;
751
857
  }
858
+ if self.an.movedField(val) {
859
+ return true;
860
+ }
752
861
  let v = self.v;
862
+ let unit = self.unit;
753
- let same = |a: &Expr| !declare && isVar(a, v);
863
+ let same = |a: &Expr| (!declare && isVar(a, v)) || self.an.freshArg(unit, a, Some(v));
754
864
  match self.an.passDeps(val, &same) {
755
865
  Some(deps) => deps.iter().all(|&(g, j)| self.an.passParamOk(g, j)),
756
866
  None => false,
757
867
  }
758
868
  }
759
869
 
760
- /// May a hand-over `v = g(v)` to `g` rebind `v` to its result?
761
- fn resultOk(&self, g: usize) -> bool {
762
- self.an.fresh_ret.borrow().contains(&g) || (!self.strict && self.an.passes.contains_key(&g))
763
- }
764
-
765
870
  fn escapes(&self) -> String {
766
871
  format!("`{}` is still used after the update", self.v)
767
872
  }
@@ -774,13 +879,13 @@ impl<'a> Scan<'a> {
774
879
  }
775
880
  }
776
881
 
777
- fn stmt(&mut self, s: &Stmt, tail: bool, depth: usize) {
882
+ fn stmt(&mut self, s: &Stmt, tail: bool, live: bool, depth: usize) {
778
883
  let v = self.v.to_string();
779
884
  match &s.kind {
780
- StmtKind::Expr(e, _, _) => self.expr(e, tail, false),
885
+ StmtKind::Expr(e, _, _) => self.expr(e, tail, live),
781
886
  StmtKind::Return(Some(e)) => self.expr(e, true, false),
782
- StmtKind::Crash(e) => self.expr(e, false, false),
887
+ StmtKind::Crash(e) => self.expr(e, false, live),
783
- StmtKind::Assert(c) => self.expr(&c.cond, false, false),
888
+ StmtKind::Assert(c) => self.expr(&c.cond, false, true),
784
889
  StmtKind::Assign(a) => {
785
890
  if a.targets.len() == 1 && a.values.len() == 1 {
786
891
  let val = &a.values[0];
@@ -799,12 +904,12 @@ impl<'a> Scan<'a> {
799
904
  self.expr(val, false, true);
800
905
  }
801
906
  }
802
- AssignTarget::Var(n) => self.operand(val, format!("`{v}` is also held by `{n}`")),
907
+ AssignTarget::Var(n) => self.operand(val, live, format!("`{v}` is also held by `{n}`")),
803
908
  AssignTarget::Field(o, f) => {
804
909
  if !self.bare(o) {
805
- self.expr(o, false, false);
910
+ self.expr(o, false, true);
806
911
  }
807
- self.operand(val, format!("`{v}` is stored in field `{f}`"));
912
+ self.operand(val, live, format!("`{v}` is stored in field `{f}`"));
808
913
  }
809
914
  }
810
915
  } else {
@@ -814,199 +919,208 @@ impl<'a> Scan<'a> {
814
919
  AssignTarget::Var(_) => {}
815
920
  AssignTarget::Field(o, _) => {
816
921
  if !self.bare(o) {
817
- self.expr(o, false, false);
922
+ self.expr(o, false, true);
818
923
  }
819
924
  }
820
925
  }
821
926
  }
822
927
  for val in &a.values {
823
- self.operand(val, format!("`{v}` is also held through a multi-assign"));
928
+ self.operand(val, true, format!("`{v}` is also held through a multi-assign"));
824
929
  }
825
930
  }
826
931
  }
827
932
  StmtKind::While(w) => {
933
+ // The body runs again: nothing in it is a last use.
828
- self.expr(&w.condition, false, false);
934
+ self.expr(&w.condition, false, true);
829
- self.block(&w.body, false, depth + 1);
935
+ self.block(&w.body, false, true, depth + 1);
830
936
  }
831
937
  StmtKind::If(i) => {
938
+ let inBodies = self.mentionsBlock(&i.body)
939
+ || i.else_ifs.iter().any(|e| self.mentionsBlock(&e.body))
940
+ || i.else_.as_ref().is_some_and(|b| self.mentionsBlock(b));
941
+ let inConds = self.mentions(&i.condition) || i.else_ifs.iter().any(|e| self.mentions(&e.condition));
942
+ // A condition runs before the branches and the later conditions.
832
- self.expr(&i.condition, false, false);
943
+ self.expr(&i.condition, false, live || inBodies || inConds);
833
- self.block(&i.body, tail, depth + 1);
944
+ self.block(&i.body, tail, live, depth + 1);
834
945
  for e in &i.else_ifs {
835
- self.expr(&e.condition, false, false);
946
+ self.expr(&e.condition, false, live || inBodies || inConds);
836
- self.block(&e.body, tail, depth + 1);
947
+ self.block(&e.body, tail, live, depth + 1);
837
948
  }
838
949
  if let Some(b) = &i.else_ {
839
- self.block(b, tail, depth + 1);
950
+ self.block(b, tail, live, depth + 1);
840
951
  }
841
952
  }
842
953
  StmtKind::Match(m) => {
954
+ let inCases = m.cases.iter().any(|c| self.mentionsBlock(&c.body) || c.guard.as_ref().is_some_and(|g| self.mentions(g)));
843
955
  for (k, sub) in m.subjects.iter().enumerate() {
844
956
  if self.bare(sub) {
845
957
  if m.cases.iter().any(|c| matches!(c.patterns.get(k), Some(CasePattern::Name(_)))) {
846
958
  self.fail(format!("`{v}` is also held by a pattern binding"));
847
959
  }
848
960
  } else {
849
- self.expr(sub, false, false);
961
+ self.expr(sub, false, live || inCases || m.subjects.iter().skip(k + 1).any(|x| self.mentions(x)));
850
962
  }
851
963
  }
852
964
  for c in &m.cases {
853
965
  self.checkPatterns(&c.patterns);
854
966
  if let Some(g) = &c.guard {
855
- self.expr(g, false, false);
967
+ self.expr(g, false, true);
856
968
  }
857
- self.block(&c.body, tail, depth + 1);
969
+ self.block(&c.body, tail, live, depth + 1);
858
970
  }
859
971
  }
860
972
  StmtKind::Return(None) | StmtKind::Todo => {}
861
973
  }
862
974
  }
863
975
 
864
- fn call(&mut self, c: &FnCall, tail: bool, ab: bool) {
976
+ fn call(&mut self, c: &FnCall, live: bool) {
865
977
  let v = self.v.to_string();
866
978
  let g = self.an.isFree(&c.name);
867
979
  let bareCount = c.args.iter().filter(|a| self.bare(argExpr(a))).count();
868
980
  for (k, a) in c.args.iter().enumerate() {
869
981
  let e = argExpr(a);
982
+ let lv = live || c.args[k + 1..].iter().any(|x| self.mentions(argExpr(x)));
870
983
  if self.bare(e) {
871
984
  let ok = bareCount == 1
872
- && (tail || ab)
985
+ && !lv
873
- && g.is_some_and(|g| {
874
- self.an.paramPos(g, c, k).is_some_and(|j| self.an.handOk(g, j))
986
+ && g.is_some_and(|g| self.an.paramPos(g, c, k).is_some_and(|j| self.an.handOk(g, j)));
875
- && (!ab || self.resultOk(g))
876
- });
877
987
  if !ok {
878
988
  self.fail(format!("`{v}` is passed to `{}`, which may keep it or the caller reads it afterwards", c.name));
879
989
  }
880
990
  } else {
881
- self.expr(e, false, false);
991
+ self.expr(e, false, lv);
882
992
  }
883
993
  }
884
994
  }
885
995
 
886
- /// `recv.m(args)`: a bare use of the variable as receiver or argument is a hand-over
996
+ /// `recv.m(args)`: a bare use of the variable as receiver or argument, at its last use, is a
887
- /// to every method named `m`, so all of them must take that parameter uniquely.
997
+ /// hand-over to every method named `m` (of the receiver's type, when known), so all of them
998
+ /// must take that parameter uniquely.
888
- fn methodCall(&mut self, a: &AttributeExpr, c: &FnCall, tail: bool, ab: bool) {
999
+ fn methodCall(&mut self, a: &AttributeExpr, c: &FnCall, live: bool) {
889
1000
  let v = self.v.to_string();
890
1001
  let cands: Vec<usize> = self.an.cands(c);
891
1002
  let recvBare = self.bare(&a.object);
892
1003
  let bareCount = recvBare as usize + c.args.iter().filter(|x| self.bare(argExpr(x))).count();
893
- let handOver = |s: &Scan, k: Option<usize>| -> bool {
1004
+ let handOver = |s: &Scan, k: Option<usize>, lv: bool| -> bool {
894
1005
  bareCount == 1
895
- && (tail || ab)
1006
+ && !lv
896
1007
  && !cands.is_empty()
897
- && cands.iter().all(|&g| {
898
- s.an.methodParam(g, c, k).is_some_and(|j| s.an.handOk(g, j))
1008
+ && cands.iter().all(|&g| s.an.methodParam(g, c, k).is_some_and(|j| s.an.handOk(g, j)))
899
- && (!ab || s.resultOk(g))
900
- })
901
1009
  };
902
1010
  let readOnly = recvBare && !cands.is_empty() && cands.iter().all(|g| self.an.ro.contains(g));
1011
+ let inArgs = c.args.iter().any(|x| self.mentions(argExpr(x)));
903
1012
  if recvBare {
904
- if !readOnly && !handOver(self, None) {
1013
+ if !readOnly && !handOver(self, None, live || inArgs) {
905
1014
  self.fail(format!("`{v}` is the receiver of `{}`, which may keep it or the caller reads it afterwards", c.name));
906
1015
  }
907
1016
  } else {
908
- self.expr(&a.object, false, false);
1017
+ self.expr(&a.object, false, live || inArgs);
909
1018
  }
910
1019
  for (k, x) in c.args.iter().enumerate() {
911
1020
  let e = argExpr(x);
1021
+ let lv = live || c.args[k + 1..].iter().any(|y| self.mentions(argExpr(y)));
912
1022
  if self.bare(e) {
913
- if !handOver(self, Some(k)) {
1023
+ if !handOver(self, Some(k), lv) {
914
1024
  self.fail(format!("`{v}` is passed to method `{}`, which may keep it or the caller reads it afterwards", c.name));
915
1025
  }
916
1026
  } else {
917
- self.expr(e, false, false);
1027
+ self.expr(e, false, lv);
918
1028
  }
919
1029
  }
920
1030
  }
921
1031
 
1032
+ /// `tail`: the value of `e` is the result of the unit. `live`: the variable is mentioned after
1033
+ /// `e` has run.
922
- fn expr(&mut self, e: &Expr, tail: bool, ab: bool) {
1034
+ fn expr(&mut self, e: &Expr, tail: bool, live: bool) {
923
1035
  let v = self.v.to_string();
924
1036
  match &e.kind {
925
1037
  ExprKind::Var(n) if *n == v => {
926
- if !tail {
1038
+ if !tail || live {
927
1039
  let m = self.escapes();
928
1040
  self.fail(m);
929
1041
  }
930
1042
  }
931
1043
  ExprKind::Self_ if v == "self" => {
932
- if !tail {
1044
+ if !tail || live {
933
1045
  let m = self.escapes();
934
1046
  self.fail(m);
935
1047
  }
936
1048
  }
937
1049
  ExprKind::InlineIf(i) => {
1050
+ let inBranch = self.mentions(&i.then) || self.mentions(&i.else_);
938
- self.expr(&i.condition, false, false);
1051
+ self.expr(&i.condition, false, live || inBranch);
939
- self.expr(&i.then, tail, ab);
1052
+ self.expr(&i.then, tail, live);
940
- self.expr(&i.else_, tail, ab);
1053
+ self.expr(&i.else_, tail, live);
941
- }
1054
+ }
942
- // A block value runs its statements in order inside the expression. Its value is in
1055
+ // A block value runs its statements in order inside the expression.
943
- // tail position only when the block is; an assign-back through it is not followed.
944
- ExprKind::Block(b) => self.block(b, tail, 99),
1056
+ ExprKind::Block(b) => self.block(b, tail, live, 99),
945
- ExprKind::FnCall(c) => self.call(c, tail, ab),
1057
+ ExprKind::FnCall(c) => self.call(c, live),
946
1058
  ExprKind::ClassCall(cc) => {
1059
+ // The field values run first, then the spread writes into its source.
1060
+ let spreadMentions = cc.spread.as_ref().is_some_and(|s| self.mentions(s));
947
1061
  match &cc.spread {
948
1062
  Some(s) if self.bare(s) => {
949
- if !(tail || ab) {
1063
+ if live {
950
1064
  self.fail(format!("`{v}` is read after the spread"));
951
1065
  }
952
1066
  }
953
- Some(s) => self.expr(s, false, false),
1067
+ Some(s) => self.expr(s, false, live),
954
1068
  None => {}
955
1069
  }
956
- for fa in &cc.fields {
1070
+ for (k, fa) in cc.fields.iter().enumerate() {
1071
+ let lv = live || spreadMentions || cc.fields[k + 1..].iter().any(|x| self.mentions(&x.value));
957
- self.operand(&fa.value, format!("`{v}` is stored in field `{}`", fa.name));
1072
+ self.operand(&fa.value, lv, format!("`{v}` is stored in field `{}`", fa.name));
958
1073
  }
959
1074
  }
960
1075
  ExprKind::Attribute(a) => match &a.attr {
961
- AttrKind::Method(c) => self.methodCall(a, c, tail, ab),
1076
+ AttrKind::Method(c) => self.methodCall(a, c, live),
962
1077
  _ => {
963
1078
  if !self.bare(&a.object) {
964
- self.expr(&a.object, false, false);
1079
+ self.expr(&a.object, false, live);
965
1080
  }
966
1081
  }
967
1082
  },
968
1083
  ExprKind::Closure(_) => {
969
- let mut found = false;
970
- walkExpr(e, &mut |n| {
971
- match n {
972
- Node::E(Expr { kind: ExprKind::Var(x), .. }) if *x == v => found = true,
973
- Node::E(Expr { kind: ExprKind::Self_, .. }) if v == "self" => found = true,
974
- _ => {}
975
- }
976
- true
977
- });
978
- if found {
1084
+ if self.mentions(e) {
979
1085
  self.fail(format!("`{v}` is captured by a closure"));
980
1086
  }
981
1087
  }
982
1088
  ExprKind::Binary(b) => {
1089
+ let r = self.mentions(&b.right);
983
- self.expr(&b.left, false, false);
1090
+ self.expr(&b.left, false, live || r);
984
- self.expr(&b.right, false, false);
1091
+ self.expr(&b.right, false, live);
985
1092
  }
986
- ExprKind::Unary(u) => self.expr(&u.operand, false, false),
1093
+ ExprKind::Unary(u) => self.expr(&u.operand, false, live),
987
1094
  ExprKind::Bool(b) => {
1095
+ let r = self.mentions(&b.right);
988
- self.expr(&b.left, false, false);
1096
+ self.expr(&b.left, false, live || r);
989
- self.expr(&b.right, false, false);
1097
+ self.expr(&b.right, false, live);
990
1098
  }
991
1099
  ExprKind::Compare(c) => {
1100
+ let r = self.mentions(&c.right);
992
- self.expr(&c.left, false, false);
1101
+ self.expr(&c.left, false, live || r);
993
- self.expr(&c.right, false, false);
1102
+ self.expr(&c.right, false, live);
994
1103
  }
995
- ExprKind::Not(x) | ExprKind::Question(x) => self.expr(x, false, false),
1104
+ ExprKind::Not(x) | ExprKind::Question(x) => self.expr(x, false, live),
996
- ExprKind::Bang(b) => self.expr(&b.value, false, false),
1105
+ ExprKind::Bang(b) => self.expr(&b.value, false, live),
997
1106
  ExprKind::Bind(b) => {
1107
+ let inBody = self.mentionsBlock(&b.case.body) || b.case.guard.as_ref().is_some_and(|g| self.mentions(g));
998
- self.expr(&b.value, false, false);
1108
+ self.expr(&b.value, false, live || inBody);
999
1109
  self.checkPatterns(&b.case.patterns);
1000
1110
  if let Some(g) = &b.case.guard {
1001
- self.expr(g, false, false);
1111
+ self.expr(g, false, true);
1002
1112
  }
1003
- self.block(&b.case.body, false, 99);
1113
+ self.block(&b.case.body, false, live, 99);
1004
1114
  }
1005
1115
  ExprKind::String(s) => {
1006
- for p in &s.parts {
1116
+ let parts: Vec<&Expr> = s
1117
+ .parts
1118
+ .iter()
1007
- if let StringPart::Interp(x) = p {
1119
+ .filter_map(|p| if let StringPart::Interp(x) = p { Some(x) } else { None })
1120
+ .collect();
1121
+ for (k, x) in parts.iter().enumerate() {
1122
+ let lv = live || parts[k + 1..].iter().any(|y| self.mentions(y));
1008
- self.expr(x, false, false);
1123
+ self.expr(x, false, lv);
1009
- }
1010
1124
  }
1011
1125
  }
1012
1126
  _ => {}
@@ -1014,6 +1128,7 @@ impl<'a> Scan<'a> {
1014
1128
  }
1015
1129
  }
1016
1130
 
1131
+
1017
1132
  // ---------- driver ----------
1018
1133
 
1019
1134
  fn fieldsOf(enums: &HashMap<String, Vec<String>>, t: &str) -> Option<Vec<String>> {
@@ -1271,6 +1386,10 @@ fn build(src: &Source) -> An {
1271
1386
  spreads: vec![],
1272
1387
  ro: HashSet::new(),
1273
1388
  arrayFresh: HashSet::new(),
1389
+ moveReads: HashSet::new(),
1390
+ moves: vec![],
1391
+ active: RefCell::new(HashSet::new()),
1392
+ assumed: std::cell::Cell::new(false),
1274
1393
  };
1275
1394
  for (i, u) in an.units.iter().enumerate() {
1276
1395
  match u.label.as_str() {
@@ -1364,6 +1483,177 @@ fn nodeKey(id: NodeId) -> NodeId {
1364
1483
  id
1365
1484
  }
1366
1485
 
1486
+ /// Fields moved out of an owner that is overwritten at once. `S(..s, ship: s.ship.update(dt))`
1487
+ /// hands `s.ship` to `update`, which may write it in place: nothing else holds that object when
1488
+ /// `s` is unique, dies in this spread, and the spread replaces the field with the result. The same
1489
+ /// goes for `w := s.ship` followed by `S(..s, ship: Ship(..w, x: 1))` (what a path in a spread
1490
+ /// lowers to). A read counts as a move only when
1491
+ ///
1492
+ /// * the owner has exactly one spread in the unit, it gives the field, and the read is the only
1493
+ /// mention of `o.f` in the unit;
1494
+ /// * for the call form, the read is the receiver or an argument of a call inside the value given
1495
+ /// to that field; for the binding form, the binding comes before the spread and every mention of
1496
+ /// the bound name is inside the value given to that field.
1497
+ ///
1498
+ /// A move is valid while the owner's spread is proved (`solve` drops the field's uniqueness
1499
+ /// otherwise), and reading the field anywhere else still makes it shared.
1500
+ fn collectMoves(a: &An, _spreads: &[SpreadSite]) -> (HashSet<NodeId>, Vec<(String, usize, NodeId)>) {
1501
+ let mut reads: HashSet<NodeId> = HashSet::new();
1502
+ let mut moves: Vec<(String, usize, NodeId)> = vec![];
1503
+ for (ui, u) in a.units.iter().enumerate() {
1504
+ let mut order = 0usize;
1505
+ let mut fieldReads: HashMap<(String, String), usize> = HashMap::new();
1506
+ let mut varCount: HashMap<String, usize> = HashMap::new();
1507
+ let mut spreadsOf: HashMap<String, Vec<(usize, NodeId, &ClassCall)>> = HashMap::new();
1508
+ // (order, bound name, owner, field, id of the read)
1509
+ let mut binds: Vec<(usize, String, String, String, NodeId)> = vec![];
1510
+ walkBlock(&u.block, &mut |n| {
1511
+ order += 1;
1512
+ match n {
1513
+ Node::S(Stmt { kind: StmtKind::Assign(asg), .. }) => {
1514
+ if let ([AssignTarget::Var(w)], [val], true) = (&asg.targets[..], &asg.values[..], asg.declare) {
1515
+ if let ExprKind::Attribute(x) = &val.kind {
1516
+ if let (AttrKind::Field(g), Some(o)) = (&x.attr, varName(&x.object)) {
1517
+ if o != w {
1518
+ binds.push((order, w.clone(), o.to_string(), g.clone(), val.id));
1519
+ }
1520
+ }
1521
+ }
1522
+ }
1523
+ }
1524
+ Node::E(e) => match &e.kind {
1525
+ ExprKind::Var(_) | ExprKind::Self_ => {
1526
+ *varCount.entry(varName(e).unwrap().to_string()).or_default() += 1;
1527
+ }
1528
+ ExprKind::Attribute(x) => {
1529
+ if let (AttrKind::Field(g), Some(o)) = (&x.attr, varName(&x.object)) {
1530
+ *fieldReads.entry((o.to_string(), g.clone())).or_default() += 1;
1531
+ }
1532
+ }
1533
+ ExprKind::ClassCall(cc) => {
1534
+ if let Some(o) = cc.spread.as_ref().and_then(|x| varName(x)) {
1535
+ spreadsOf.entry(o.to_string()).or_default().push((order, e.id, cc));
1536
+ }
1537
+ }
1538
+ _ => {}
1539
+ },
1540
+ _ => {}
1541
+ }
1542
+ true
1543
+ });
1544
+ let fieldName = |cc: &ClassCall, k: usize| -> Option<String> {
1545
+ let fa = &cc.fields[k];
1546
+ if !fa.name.is_empty() {
1547
+ Some(fa.name.clone())
1548
+ } else {
1549
+ fieldsOf(&a.enums, &cc.type_name).and_then(|n| n.get(k).cloned())
1550
+ }
1551
+ };
1552
+ let countIn = |e: &Expr, w: &str| -> usize {
1553
+ let mut n = 0;
1554
+ walkExpr(e, &mut |x| {
1555
+ if let Node::E(y) = x {
1556
+ if varName(y) == Some(w) {
1557
+ n += 1;
1558
+ }
1559
+ }
1560
+ true
1561
+ });
1562
+ n
1563
+ };
1564
+ // Uses of `o` in the field values other than a plain read `o.g`: a method call on `o`
1565
+ // (read-only or not) or `o` passed along may look at the moved field after the in-place
1566
+ // update and see the new object, where a copy would show the old one.
1567
+ let bareUses = |cc: &ClassCall, o: &str| -> usize {
1568
+ let (mut vars, mut reads) = (0usize, 0usize);
1569
+ for fa in &cc.fields {
1570
+ walkExpr(&fa.value, &mut |n| {
1571
+ if let Node::E(e) = n {
1572
+ match &e.kind {
1573
+ ExprKind::Var(_) | ExprKind::Self_ if varName(e) == Some(o) => vars += 1,
1574
+ ExprKind::Attribute(x)
1575
+ if matches!(x.attr, AttrKind::Field(_)) && varName(&x.object) == Some(o) =>
1576
+ {
1577
+ reads += 1
1578
+ }
1579
+ _ => {}
1580
+ }
1581
+ }
1582
+ true
1583
+ });
1584
+ }
1585
+ vars.saturating_sub(reads)
1586
+ };
1587
+ // Call form.
1588
+ for (o, sites) in &spreadsOf {
1589
+ let [(_, node, cc)] = &sites[..] else { continue };
1590
+ if bareUses(cc, o) > 0 {
1591
+ continue;
1592
+ }
1593
+ for k in 0..cc.fields.len() {
1594
+ let Some(g) = fieldName(cc, k) else { continue };
1595
+ if g.contains('.') || fieldReads.get(&(o.clone(), g.clone())) != Some(&1) {
1596
+ continue;
1597
+ }
1598
+ let isRead = |x: &Expr| {
1599
+ matches!(&x.kind, ExprKind::Attribute(y)
1600
+ if y.attr == AttrKind::Field(g.clone()) && varName(&y.object) == Some(o.as_str()))
1601
+ };
1602
+ let mut found: Option<NodeId> = None;
1603
+ walkExpr(&cc.fields[k].value, &mut |n| {
1604
+ match n {
1605
+ Node::E(Expr { kind: ExprKind::Closure(_), .. }) => return false,
1606
+ Node::E(Expr { kind: ExprKind::FnCall(c), .. }) => {
1607
+ for x in &c.args {
1608
+ if isRead(argExpr(x)) {
1609
+ found = Some(argExpr(x).id);
1610
+ }
1611
+ }
1612
+ }
1613
+ Node::E(Expr { kind: ExprKind::Attribute(y), .. }) => {
1614
+ if let AttrKind::Method(c) = &y.attr {
1615
+ if isRead(&y.object) {
1616
+ found = Some(y.object.id);
1617
+ }
1618
+ for x in &c.args {
1619
+ if isRead(argExpr(x)) {
1620
+ found = Some(argExpr(x).id);
1621
+ }
1622
+ }
1623
+ }
1624
+ }
1625
+ _ => {}
1626
+ }
1627
+ true
1628
+ });
1629
+ if let Some(id) = found {
1630
+ reads.insert(id);
1631
+ moves.push((g, ui, *node));
1632
+ }
1633
+ }
1634
+ }
1635
+ // Binding form.
1636
+ for (at, w, o, g, id) in &binds {
1637
+ let Some(sites) = spreadsOf.get(o) else { continue };
1638
+ let [(sAt, node, cc)] = &sites[..] else { continue };
1639
+ if bareUses(cc, o) > 0 {
1640
+ continue;
1641
+ }
1642
+ if sAt < at || fieldReads.get(&(o.clone(), g.clone())) != Some(&1) {
1643
+ continue;
1644
+ }
1645
+ let Some(k) = (0..cc.fields.len()).find(|&k| fieldName(cc, k).as_deref() == Some(g.as_str())) else { continue };
1646
+ let inside = countIn(&cc.fields[k].value, w);
1647
+ if inside == 0 || varCount.get(w) != Some(&inside) {
1648
+ continue;
1649
+ }
1650
+ reads.insert(*id);
1651
+ moves.push((g.clone(), ui, *node));
1652
+ }
1653
+ }
1654
+ (reads, moves)
1655
+ }
1656
+
1367
1657
  /// The methods whose `self` is only read (see `An.ro`): a greatest fixpoint, since a method may
1368
1658
  /// call another read-only one on `self`.
1369
1659
  fn readOnlySelf(an: &An) -> HashSet<usize> {
@@ -1731,6 +2021,8 @@ fn collectFacts(an: &mut An) {
1731
2021
  escaped.insert(i);
1732
2022
  }
1733
2023
  }
2024
+ let (moveReads, moves) = collectMoves(a, &spreads);
2025
+ allowed.extend(moveReads.iter().copied());
1734
2026
  let readsEscape: HashSet<String> =
1735
2027
  reads.into_iter().filter(|(p, _)| !allowed.contains(p)).map(|(_, f)| f).collect();
1736
2028
  badField.extend(readsEscape);
@@ -1741,6 +2033,8 @@ fn collectFacts(an: &mut An) {
1741
2033
  an.poisonAll = poisonAll;
1742
2034
  an.spreads = spreads;
1743
2035
  an.passWrites = passWrites;
2036
+ an.moveReads = moveReads;
2037
+ an.moves = moves;
1744
2038
  }
1745
2039
 
1746
2040
  fn solve(an: &An) {
@@ -1817,6 +2111,12 @@ fn solve(an: &An) {
1817
2111
  }
1818
2112
  }
1819
2113
  }
2114
+ for (f, ui, node) in &an.moves {
2115
+ let proved = an.spreads.iter().any(|s| s.unit == *ui && s.node == *node && an.spreadProved(s));
2116
+ if !proved {
2117
+ poisoned.insert(f.clone());
2118
+ }
2119
+ }
1820
2120
  for (f, deps) in &an.passWrites {
1821
2121
  if !deps.iter().all(|&(g, j)| an.passParamOk(g, j)) {
1822
2122
  poisoned.insert(f.clone());
compiler/core/tests/core/main.rs CHANGED
@@ -26,6 +26,7 @@ mod tail_test;
26
26
  mod tests_lower_test;
27
27
  mod trmc_test;
28
28
  mod enum_checks_test;
29
+ mod uniqueness_moves_test;
29
30
  mod uniqueness_test;
30
31
  mod visit_test;
31
32
  mod whistle_test;
compiler/core/tests/core/uniqueness_moves_test.rs ADDED
@@ -0,0 +1,210 @@
1
+ #![allow(non_snake_case)]
2
+ //! Last-use moves (T12): a value handed on at its last use keeps the proof; a read or capture
3
+ //! after the move, a second move, or a shared owner does not.
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 provedFn(r: &UniqueReport, name: &str) -> bool {
12
+ r.proved.iter().any(|p| p.starts_with(&format!("{name}:")))
13
+ }
14
+
15
+ fn why(r: &UniqueReport, name: &str) -> String {
16
+ r.unproved.iter().find(|(l, _)| l.starts_with(&format!("{name}:"))).map(|(_, m)| m.clone()).unwrap_or_default()
17
+ }
18
+
19
+ const CELL: &str = "struct Cell(label: Str, mut n: Int) =\n fun bumped(self) -> Cell = Cell(..self, n: self.n + 1)\n\
20
+ fun bump(c: Cell) -> Cell = Cell(..c, n: c.n + 1)\n\
21
+ fun touch(c: Cell) -> Cell =\n c.n = c.n + 1\n c\n\
22
+ fun mk() -> Cell = Cell(label: \"a\", n: 0)\n";
23
+
24
+ // ---- the shapes that replace `v = v.f()` ----
25
+
26
+ #[test]
27
+ fn rebinding_with_no_use_after_proves() {
28
+ let r = run(&format!("{CELL}fun go() -> Int =\n c := mk()\n d := bump(c)\n d.n\n"));
29
+ assert!(provedFn(&r, "bump"), "{r:?}");
30
+ }
31
+
32
+ #[test]
33
+ fn rebinding_with_a_read_after_stays_shared() {
34
+ let r = run(&format!("{CELL}fun go() -> Int =\n c := mk()\n d := bump(c)\n c.n + d.n\n"));
35
+ assert!(!provedFn(&r, "bump"), "{r:?}");
36
+ }
37
+
38
+ #[test]
39
+ fn nested_argument_proves() {
40
+ let r = run(&format!("{CELL}fun id(c: Cell) -> Int = c.n\nfun go() -> Int = id(bump(mk()))\nfun go2() -> Int =\n c := mk()\n id(bump(c))\n"));
41
+ assert!(provedFn(&r, "bump"), "{r:?}");
42
+ }
43
+
44
+ #[test]
45
+ fn pass_through_function_keeps_the_proof() {
46
+ let r = run(&format!("{CELL}fun go() -> Cell = bump(touch(mk()))\n"));
47
+ assert!(provedFn(&r, "bump"), "{r:?}");
48
+ let r = run(&format!("{CELL}fun go() -> Cell =\n c := touch(mk())\n bump(c)\n"));
49
+ assert!(provedFn(&r, "bump"), "{r:?}");
50
+ }
51
+
52
+ #[test]
53
+ fn pass_through_of_a_shared_value_stays_shared() {
54
+ let r = run(&format!("{CELL}fun go(c: Cell) -> Int =\n d := bump(touch(c))\n c.n + d.n\n"));
55
+ assert!(!provedFn(&r, "bump"), "{r:?}");
56
+ }
57
+
58
+ #[test]
59
+ fn tail_recursive_method_argument_proves() {
60
+ let s = format!(
61
+ "{CELL}fun loop(c: Cell, i: Int) -> Cell = if i == 0 then c else loop(c.bumped(), i - 1)\n\
62
+ fun go() -> Cell = loop(mk(), 3)\n"
63
+ );
64
+ let r = run(&s);
65
+ assert!(provedFn(&r, "Cell.bumped"), "{r:?}");
66
+ }
67
+
68
+ #[test]
69
+ fn tail_recursive_state_loop_proves() {
70
+ let s = format!(
71
+ "{CELL}fun spin(c: Cell, n: Int) -> Cell = if n == 0 then c else spin(Cell(..c, n: c.n + 1), n - 1)\n\
72
+ fun go() -> Cell = spin(mk(), 3)\n"
73
+ );
74
+ let r = run(&s);
75
+ assert!(provedFn(&r, "spin"), "{r:?}");
76
+ }
77
+
78
+ #[test]
79
+ fn non_tail_argument_proves() {
80
+ let s = format!(
81
+ "{CELL}fun spin(c: Cell, n: Int) -> Int = if n == 0 then c.n else spin(c.bumped(), n - 1) + 1\n\
82
+ fun go() -> Int = spin(mk(), 3)\n"
83
+ );
84
+ let r = run(&s);
85
+ assert!(provedFn(&r, "Cell.bumped"), "{r:?}");
86
+ }
87
+
88
+ // ---- hostile: each must stay a copy ----
89
+
90
+ #[test]
91
+ fn read_after_the_move_in_one_branch_stays_shared() {
92
+ let s = format!("{CELL}fun go(flag: Bool) -> Int =\n c := mk()\n d := if flag then bump(c) else c\n c.n + d.n\n");
93
+ let r = run(&s);
94
+ assert!(!provedFn(&r, "bump"), "{r:?}");
95
+ }
96
+
97
+ #[test]
98
+ fn moves_in_different_branches_both_prove() {
99
+ let s = format!("{CELL}fun go(flag: Bool) -> Int =\n c := mk()\n d := if flag then bump(c) else Cell(..c, n: 9)\n d.n\n");
100
+ let r = run(&s);
101
+ assert!(provedFn(&r, "bump"), "{r:?}");
102
+ assert!(provedFn(&r, "go"), "{r:?}");
103
+ }
104
+
105
+ #[test]
106
+ fn move_in_a_nested_spread_then_a_read_stays_shared() {
107
+ let s = format!(
108
+ "{CELL}struct W(inner: Cell, k: Int)\nfun go() -> W =\n c := mk()\n W(inner: Cell(..c, n: 1), k: c.n)\n"
109
+ );
110
+ let r = run(&s);
111
+ assert!(!provedFn(&r, "go"), "{r:?}");
112
+ }
113
+
114
+ #[test]
115
+ fn move_in_a_nested_spread_without_a_read_proves() {
116
+ let s = format!(
117
+ "{CELL}struct W(inner: Cell, k: Int)\nfun go() -> W =\n c := mk()\n W(inner: Cell(..c, n: 1), k: 2)\n"
118
+ );
119
+ let r = run(&s);
120
+ assert!(provedFn(&r, "go"), "{r:?}");
121
+ }
122
+
123
+ #[test]
124
+ fn capture_before_the_move_stays_shared() {
125
+ let s = format!("{CELL}fun go() -> Int =\n c := mk()\n f := || c.n\n d := bump(c)\n f() + d.n\n");
126
+ let r = run(&s);
127
+ assert!(!provedFn(&r, "bump"), "{r:?}");
128
+ }
129
+
130
+ #[test]
131
+ fn the_same_value_moved_twice_stays_shared() {
132
+ let s = format!("{CELL}fun both(a: Cell, b: Cell) -> Int = a.n + b.n\nfun go() -> Int =\n c := mk()\n both(bump(c), bump(c))\n");
133
+ let r = run(&s);
134
+ assert!(!provedFn(&r, "bump"), "{r:?}");
135
+ let s = format!("{CELL}fun go() -> Int =\n c := mk()\n both(c, c)\nfun both(a: Cell, b: Cell) -> Cell = bump(a)\n");
136
+ let r = run(&s);
137
+ assert!(!provedFn(&r, "bump"), "{r:?}");
138
+ }
139
+
140
+ #[test]
141
+ fn a_value_read_after_the_recursive_call_stays_shared() {
142
+ let s = format!(
143
+ "{CELL}fun spin(c: Cell, i: Int) -> Int = if i == 0 then c.n else spin(c.bumped(), i - 1) + c.n\n\
144
+ fun go() -> Int = spin(mk(), 3)\n"
145
+ );
146
+ let r = run(&s);
147
+ assert!(!provedFn(&r, "Cell.bumped"), "{r:?}");
148
+ }
149
+
150
+ #[test]
151
+ fn a_field_of_a_shared_struct_stays_shared() {
152
+ let s = format!("{CELL}struct Holder(c: Cell, tag: Int)\nfun go(h: Holder) -> Int =\n d := bump(h.c)\n h.c.n + d.n\n");
153
+ let r = run(&s);
154
+ assert!(!provedFn(&r, "bump"), "{r:?}");
155
+ }
156
+
157
+ #[test]
158
+ fn contents_of_an_array_stay_shared() {
159
+ let s = format!("{CELL}fun go(a: Array[Cell]) -> Cell = bump(a.get(0))\n");
160
+ let r = run(&s);
161
+ assert!(!provedFn(&r, "bump"), "{r:?}");
162
+ }
163
+
164
+ // ---- fields moved out of a spread owner ----
165
+
166
+ const SHIP: &str = "struct Ship(name: Str, x: Int) =\n fun update(self, dt: Int) -> Ship = Ship(..self, x: self.x + dt)\n\
167
+ struct S(ship: Ship, n: Int) =\n fun step(self, dt: Int) -> S = S(..self, ship: self.ship.update(dt))\n\
168
+ fun mkS() -> S = S(ship: Ship(name: \"a\", x: 0), n: 0)\n";
169
+
170
+ #[test]
171
+ fn a_field_moved_into_its_own_update_proves_both() {
172
+ let r = run(&format!("{SHIP}fun go() -> S = mkS().step(1)\n"));
173
+ assert!(provedFn(&r, "S.step"), "{r:?}");
174
+ assert!(provedFn(&r, "Ship.update"), "{r:?}");
175
+ }
176
+
177
+ #[test]
178
+ fn a_shared_owner_keeps_both_copying() {
179
+ let r = run(&format!("{SHIP}fun go() -> Int =\n s := mkS()\n t := s.step(1)\n s.n + t.n\n"));
180
+ assert!(!provedFn(&r, "S.step"), "{r:?}");
181
+ assert!(!provedFn(&r, "Ship.update"), "{r:?}");
182
+ }
183
+
184
+ #[test]
185
+ fn a_field_moved_into_another_field_stays_shared() {
186
+ let s = "struct Ship(name: Str, x: Int) =\n fun update(self, dt: Int) -> Ship = Ship(..self, x: self.x + dt)\n\
187
+ struct S(ship: Ship, other: Ship) =\n fun step(self, dt: Int) -> S = S(..self, other: self.ship.update(dt))\n\
188
+ fun go() -> S =\n a := Ship(name: \"a\", x: 0)\n S(ship: a, other: a).step(1)\n";
189
+ let r = run(s);
190
+ assert!(!provedFn(&r, "Ship.update"), "{r:?}");
191
+ }
192
+
193
+ #[test]
194
+ fn a_field_read_twice_in_the_update_stays_shared() {
195
+ let s = SHIP.replace("self.ship.update(dt)", "self.ship.update(self.ship.x)");
196
+ let r = run(&format!("{s}fun go() -> S = mkS().step(1)\n"));
197
+ assert!(!provedFn(&r, "Ship.update"), "{r:?}");
198
+ }
199
+
200
+ #[test]
201
+ fn a_field_read_in_another_function_stays_shared() {
202
+ let r = run(&format!("{SHIP}fun peek(s: S) -> Ship = s.ship\nfun go() -> S = mkS().step(1)\n"));
203
+ assert!(!provedFn(&r, "Ship.update"), "{r:?}");
204
+ }
205
+
206
+ #[test]
207
+ fn explain_text_names_the_reason() {
208
+ let r = run(&format!("{CELL}fun go() -> Int =\n c := mk()\n d := bump(c)\n c.n + d.n\n"));
209
+ assert!(why(&r, "bump").contains("shared") || why(&r, "bump").contains("used"), "{r:?}");
210
+ }
compiler/wasm-codegen/tests/wasm_codegen/e2e_mem/unique_spread.rs CHANGED
@@ -62,17 +62,18 @@ fun adv(s: Cell) -> Cell = Cell(..s, x: s.x + 1)
62
62
  fun main() -> Int =
63
63
  s := Cell(x: 1, y: 7)
64
64
  t := adv(s)
65
- t.x * 100 + t.y
65
+ t.x * 100 + t.y + s.y
66
66
  ";
67
67
 
68
- /// A non-`own` record whose spread is flagged `unique` is written in place.
68
+ /// A non-`own` record whose spread is flagged `unique` is written in place. `s` is read after the
69
+ /// call, so the proof leaves the spread a copy and the flag is what turns it on.
69
70
  #[test]
70
71
  fn unique_flag_reuses_object() {
71
72
  let p = format!("{PRE}{SPREAD}");
72
73
  let a = structNewCount("u_plain", &p, false);
73
74
  let b = structNewCount("u_flag", &p, true);
74
75
  assert_eq!(a, b + 1, "plain {a} struct.new, unique {b}");
75
- assert_eq!(runInt("u_run", &p, true), 207);
76
+ assert_eq!(runInt("u_run", &p, true), 214);
76
77
  }
77
78
 
78
79
  /// The hazard check still applies: y reads x after x was overwritten.
tests/fbip/fuzz/gen.pl CHANGED
@@ -23,7 +23,7 @@ sub iexpr {
23
23
  }
24
24
  my @stmts;
25
25
  for my $n (1..(6+r(12))) {
26
- my $k = r(30);
26
+ my $k = r(42);
27
27
  my $s;
28
28
  my $V = pick(@vs); my $V2 = pick(@vs); my $W = pick(@ws);
29
29
  my ($nvn, $nwn) = ("v$nv", "w$nw");
@@ -44,6 +44,14 @@ for my $n (1..(6+r(12))) {
44
44
  elsif ($k==13) { $s = "$W.p.inc()"; }
45
45
  elsif ($k==14) { $s = "repl($W, $V)"; }
46
46
  elsif ($k==15) { $s = "bump(bump($V))"; }
47
+ elsif ($k==30) { $s = "bump(pass($V, $V2))"; }
48
+ elsif ($k==31) { $s = "pass(bump($V), bump($V2))"; }
49
+ elsif ($k==32) { $s = "pass(bump($V), $V)"; }
50
+ elsif ($k==33) { $s = "spin($V, ".r(4).")"; }
51
+ elsif ($k==34) { $s = "spin2($V, ".r(4).")"; }
52
+ elsif ($k==35) { $s = "spin3($V, ".r(3).")"; }
53
+ 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
+ elsif ($k==37) { $s = "0.until(".r(4).").fold($W.p, |acc, i| ".pick("acc.inc()", "pass(acc, acc)", "P(..acc, a: i)").")"; }
47
55
  else { $isv = 0; }
48
56
  if ($isv) { push @stmts, "$nvn := $s"; push @vs, $nvn; $nv++; next; }
49
57
  if ($k==16) { $s = "Q(p: $V, n: ".r(4).")"; }
@@ -53,7 +61,11 @@ for my $n (1..(6+r(12))) {
53
61
  elsif ($k==20) { $s = "$W.bumped()"; }
54
62
  elsif ($k==21) { $s = "wrap($V)"; }
55
63
  elsif ($k==22) { $s = "ys.at(".r(2).")"; }
64
+ elsif ($k==38) { $s = "Q(..$W, p: bump($W.p))"; }
65
+ elsif ($k==39) { $s = "Q(..$W, p.a: ".iexpr().")"; }
66
+ 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
+ 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())"); }
56
- if ($k >= 16 && $k <= 22) { push @stmts, "$nwn := $s"; push @ws, $nwn; $nw++; next; }
68
+ if (($k >= 16 && $k <= 22) || ($k >= 38 && $k <= 41)) { push @stmts, "$nwn := $s"; push @ws, $nwn; $nw++; next; }
57
69
  if ($k==23) { $s = "m.p = $V"; }
58
70
  elsif ($k==24) { $s = "m.p = m.p.inc()"; }
59
71
  elsif ($k==25) { $s = "m.p = pass(m.p, $V)"; }
@@ -99,6 +111,17 @@ fun repl(w: Q, p: P) -> P =
99
111
 
100
112
  fun wrap(p: P) -> Q = Q(p: p, n: 0)
101
113
 
114
+ fun spin(p: P, n: Int) -> P = if n == 0 then p else spin(p.inc(), n - 1)
115
+
116
+ fun spin2(p: P, n: Int) -> P = if n == 0 then p else spin2(P(..p, a: p.a + 1), n - 1)
117
+
118
+ fun spin3(p: P, n: Int) -> P =
119
+ if n == 0
120
+ p
121
+ else
122
+ r := spin3(p.inc(), n - 1)
123
+ P(..r, b: p.a)
124
+
102
125
  test "fuzz"
103
126
  v0 := P(a: 1, b: 2, tag: "x")
104
127
  v1 := P(a: 3, b: 4, tag: "y")
tests/fbip/last_use_moves.plum ADDED
@@ -0,0 +1,101 @@
1
+ import std/Int
2
+ import std/Str
3
+
4
+ # A value handed on at its last use keeps the in-place proof. `fip fun` makes the compiler check
5
+ # it: every spread in a `fip fun` must be proved in place or the file does not compile. The
6
+ # hostile cases use plain fns (a shared caller would break the proof of a `fip fun`) and check the
7
+ # values: a wrong proof writes through a value someone still holds. Names are unique per
8
+ # scenario because the proof resolves methods and fields by name.
9
+ struct Cnt(label: Str, n: Int)
10
+
11
+ struct Ship(name: Str, x: Int, y: Int) =
12
+ fip fun lmUpdate(self, dt: Int) -> Ship = Ship(..self, x: self.x + dt)
13
+
14
+ struct World(ship: Ship, score: Int) =
15
+ fip fun lmStep(self, dt: Int) -> World = World(..self, ship: self.ship.lmUpdate(dt), score: self.score + 1)
16
+
17
+ fun lmWorld() -> World = World(ship: Ship(name: "s", x: 0, y: 5), score: 0)
18
+
19
+ fip fun lmPath(w: World) -> World = World(..w, ship.x: 7)
20
+
21
+ # a rebinding whose source is not used again
22
+ fip fun lmBump(c: Cnt) -> Cnt = Cnt(..c, n: c.n + 1)
23
+
24
+ fun lmRebind() -> Int =
25
+ c := Cnt(label: "a", n: 1)
26
+ d := lmBump(c)
27
+ d.n
28
+
29
+ # a nested argument
30
+ fun lmRead(c: Cnt) -> Int = c.n
31
+
32
+ # a tail-recursive argument, and a tail-recursive state loop
33
+ fip fun lmSpin(c: Cnt, i: Int) -> Cnt = if i == 0 then c else lmSpin(Cnt(..c, n: c.n + 1), i - 1)
34
+
35
+ # a fold accumulator
36
+ fun lmBumpF(c: Cnt) -> Cnt = Cnt(..c, n: c.n + 1)
37
+
38
+ fun lmFold(k: Int) -> Cnt = 0.until(k).fold(Cnt(label: "a", n: 0), |acc, i| lmBumpF(acc))
39
+
40
+ fun lmFoldSpread(k: Int) -> Cnt = 0.until(k).fold(Cnt(label: "a", n: 0), |acc, i| Cnt(..acc, n: acc.n + i))
41
+
42
+ # ---- hostile: the old value is still there afterwards ----
43
+ fun lmBumpS(c: Cnt) -> Cnt = Cnt(..c, n: c.n + 1)
44
+
45
+ fun lmBoth(a: Cnt, b: Cnt) -> Int = a.n * 10 + b.n
46
+
47
+ fun lmKeep(c: Cnt, i: Int) -> Int =
48
+ if i == 0
49
+ c.n
50
+ else
51
+ lmKeep(lmBumpS(c), i - 1) + c.n
52
+
53
+ # the hand-over of a field, and of a path
54
+ test "moves: a field handed to its own update"
55
+ w := lmWorld().lmStep(3).lmStep(4)
56
+ assert w.ship.x == 7
57
+ assert w.score == 2
58
+
59
+ test "moves: a path in a spread"
60
+ w := lmPath(lmWorld())
61
+ assert w.ship.x == 7
62
+ assert w.ship.y == 5
63
+
64
+ test "moves: rebinding"
65
+ assert lmRebind() == 2
66
+
67
+ test "moves: nested argument"
68
+ assert lmRead(lmBump(lmBump(Cnt(label: "a", n: 0)))) == 2
69
+
70
+ test "moves: tail-recursive state"
71
+ assert lmSpin(Cnt(label: "a", n: 0), 50).n == 50
72
+
73
+ test "moves: fold accumulator"
74
+ assert lmFold(20).n == 20
75
+ assert lmFoldSpread(5).n == 10
76
+
77
+ test "hostile: a read after the move"
78
+ c := Cnt(label: "a", n: 1)
79
+ d := lmBumpS(c)
80
+ assert c.n == 1
81
+ assert d.n == 2
82
+
83
+ test "hostile: a read after the move in one branch"
84
+ c := Cnt(label: "a", n: 1)
85
+ d := if c.n > 0 then lmBumpS(c) else c
86
+ assert c.n == 1
87
+ assert d.n == 2
88
+
89
+ test "hostile: a capture before the move"
90
+ c := Cnt(label: "a", n: 1)
91
+ f := || c.n
92
+ d := lmBumpS(c)
93
+ assert f() == 1
94
+ assert d.n == 2
95
+
96
+ test "hostile: the same value moved twice"
97
+ c := Cnt(label: "a", n: 1)
98
+ assert lmBoth(lmBumpS(c), lmBumpS(c)) == 22
99
+
100
+ test "hostile: a value read after the recursive call"
101
+ assert lmKeep(Cnt(label: "a", n: 1), 2) == 6
tests/fbip/last_use_shared.plum ADDED
@@ -0,0 +1,88 @@
1
+ import std/Int
2
+ import std/Str
3
+ import std/Slice
4
+
5
+ # Fields moved out of an owner (`S(..s, ship: s.ship.update(dt))`) stay copies when the owner or
6
+ # the field is shared. The values are checked: a wrong proof writes through the old owner. Field
7
+ # and method names here are used by no other file's `fip fun`, because the proof is per name.
8
+ struct Hull(name: Str, hx: Int) =
9
+ fun hullUp(self, dt: Int) -> Hull = Hull(..self, hx: self.hx + dt)
10
+
11
+ struct Fleet(hull: Hull, count: Int) =
12
+ fun fleetStep(self, dt: Int) -> Fleet = Fleet(..self, hull: self.hull.hullUp(dt))
13
+
14
+ fun mkFleet() -> Fleet = Fleet(hull: Hull(name: "h", hx: 0), count: 0)
15
+
16
+ # a field moved into another field
17
+ struct Duo(left: Hull, right: Hull) =
18
+ fun duoSwap(self, dt: Int) -> Duo = Duo(..self, right: self.left.hullUp(dt))
19
+
20
+ # the field read twice in one update
21
+ struct Pair2(item: Hull, tag: Int) =
22
+ fun pairGrow(self) -> Pair2 = Pair2(..self, item: self.item.hullUp(self.item.hx), tag: self.item.hx)
23
+
24
+ # a path in a spread whose owner is read afterwards
25
+ fun pathKeep(f: Fleet) -> Int =
26
+ g := Fleet(..f, hull.hx: 9)
27
+ f.hull.hx * 100 + g.hull.hx
28
+
29
+ # a read-only method on the owner, in another field of the same update, looks at the moved field
30
+ # after it was written: it must still see the old object. The fns are free (a `..self` spread is
31
+ # not written in place) and `rdSeen` is recursive so it stays a call.
32
+ struct RdShip(name: Str, rx: Int)
33
+
34
+ fun rdUp(s: RdShip, d: Int) -> RdShip = RdShip(..s, rx: s.rx + d)
35
+
36
+ struct RdWorld(ship: RdShip, seen: Int) =
37
+ fun rdSeen(self) -> Int = self.rdSeenN(2)
38
+ fun rdSeenN(self, k: Int) -> Int = if k > 0 then self.rdSeenN(k - 1) else self.ship.rx
39
+
40
+ fun rdStep(w: RdWorld) -> RdWorld = RdWorld(..w, ship: rdUp(w.ship, 1), seen: w.rdSeen())
41
+
42
+ fun rdStepFirst(w: RdWorld) -> RdWorld = RdWorld(..w, seen: w.rdSeen(), ship: rdUp(w.ship, 1))
43
+
44
+ fun rdStepArg(w: RdWorld) -> RdWorld = RdWorld(..w, ship: rdUp(w.ship, w.rdSeen() + 5))
45
+
46
+ test "shared owner: the old fleet keeps its hull"
47
+ f := mkFleet()
48
+ g := f.fleetStep(5)
49
+ assert f.hull.hx == 0
50
+ assert g.hull.hx == 5
51
+
52
+ test "shared owner: stepped twice from one value"
53
+ f := mkFleet()
54
+ a := f.fleetStep(1)
55
+ b := f.fleetStep(2)
56
+ assert a.hull.hx == 1
57
+ assert b.hull.hx == 2
58
+ assert f.hull.hx == 0
59
+
60
+ test "moved into another field: both keep their value"
61
+ h := Hull(name: "a", hx: 1)
62
+ d := Duo(left: h, right: h).duoSwap(10)
63
+ assert d.left.hx == 1
64
+ assert d.right.hx == 11
65
+ assert h.hx == 1
66
+
67
+ test "read twice in one update"
68
+ p := Pair2(item: Hull(name: "a", hx: 3), tag: 0).pairGrow()
69
+ assert p.item.hx == 6
70
+ assert p.tag == 3
71
+
72
+ test "path: the owner read after the update"
73
+ assert pathKeep(mkFleet()) == 9
74
+
75
+ # contents of a Slice and an Array are never moved
76
+ test "contents of a Slice are shared"
77
+ xs := Slice[Hull]()
78
+ xs.push(Hull(name: "a", hx: 1))
79
+ h := xs.at(0).hullUp(5)
80
+ assert xs.at(0).hx == 1
81
+ assert h.hx == 6
82
+
83
+ test "moved field: a method on the owner in another field sees the old ship"
84
+ w := RdWorld(ship: RdShip(name: "s", rx: 0), seen: 0)
85
+ assert rdStep(w).seen == 0
86
+ assert rdStep(RdWorld(ship: RdShip(name: "s", rx: 0), seen: 0)).ship.rx == 1
87
+ assert rdStepFirst(RdWorld(ship: RdShip(name: "s", rx: 0), seen: 0)).seen == 0
88
+ assert rdStepArg(RdWorld(ship: RdShip(name: "s", rx: 0), seen: 0)).ship.rx == 5