plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
2e20166
— Peter John
2026-11-16T13:10:41+05:30
the screen in place again in std's delivery fold (user: "Fix the lost in place"): the fold steps one copy of the screen a tick delivered, made by a new built-in, `@copy(x)` (a shallow copy of a struct, another object with the same field values; it takes a type parameter, where no spread can name the type), in `Delivery.deliverTo` and `dispatchTo`: the game keeps the screen it had (`Game.screens`, `Game.initial`), and the copy is the fold's alone, so every step of the tick is unique; compiler: `@copy` in compile_builtins and native, the checker accepts a struct or a type parameter (`identity::checkCopyArgs`, an instantiation checked too: `g(3)` is an error), codegen copies field by field with one `struct.new` (a flat struct is its value; anything else is a compile error, `intrinsics::compileCopyFnBody`); the uniqueness pass: `@copy(..)` is fresh and its argument only read, and every field of the copied type (for a type parameter, of each implementer of its first bound) is shared (`copiedFields`); read-only parameters through calls (`readOnlyParams`, a worklist over callers: a parameter only read, as a field read's object, a read-only receiver, a match that only reads it, or a bare argument of parameters every target only reads; the screen's `view` hands `self` to the fused copies of its closures, so `s.view()` and `s.hud(..)` in `eventInto` no longer keep the slice; a parameter of a `@native` or extern body is never read-only, as `Slice.push` keeps what it is given); a field of a fresh value is fresh while the field is unique (`self.advance(dt).state`: `analyse` builds and solves again with a field distrusted when the proof finds it shared), and such a read no longer makes the field shared; a value moved into a constructor beside values that only read it (`Next(state: self, then: [if self.over then StartOver])`); a local bound once and used once stands for its value in `passes` (`deal`'s `withOrbs`), so `reduce` passes its `self` back and `self.reduce(a).followed(a)` hands `followed` a unique screen; Orbit Runner: `PlayingScreen.reduce` 3 in place (steer, scored and hit, whose field values are now written in declaration order; `StartOver` copies, out of order with `best` reading `score`), `newMine`, `at` and the derived `stepped`, none needing a `$unique` version (the old `reduce$unique` 3 were steer, `PlayAgain`'s spread, which is gone, and scored); 27 spreads in place where there were 22; Balloon Pop as before (its `act` reads `self` after handing it to `reduce`); not restored: R3's `Mine.step`, `Mine.put` and `Orb.put$unique` (a step is one spread of the list's head, `List.head`, which std's read-only walks `all`, `filter` and `next` hand to closures and results; the same allocation a step as before); benchmarks/screen_views (minimums, before and after on b9032ece): orbit update 11.4 and 11.3 ms, paint 129.1 and 129.0 ms, checksum 946756219 unchanged, scale update view 22.1 and 22.0 ms, paint view 328.6 and 328.7 ms, spread 333.3 and 331.3 ms, checksum 502378645; compile time: the in-place pass about 2.5 times as long (debug, Orbit Runner 183 to 480 ms: 9 version rounds where there were 5, each about 30% dearer), in the backlog; the wasm is the same build after build; tests: core uniqueness_fold_test (a copy of a shared value, the copied type's fields shared through a known type and a bound, a receiver read through another fn, a field of a fresh value, a local used once, a native body), checker `copy_takes_structs` and `copy_rejects_what_is_no_struct`, tests/core/copy.plum (in the three sweep modes), game_in_place_test's Orbit Runner expectations, driver `gameStartingFromAConstantActorCopies` (the reduction is in place in the copy, never in `Stress.Start`), the built-in lists of the checker and the LSP; docs: language.md (the built-ins table, Copies), std.md, game.md (the fold's copy), backlog (what the fold still copies, the cost)
- compiler/checker/src/identity.rs +24 -0
- compiler/checker/src/infer.rs +1 -0
- compiler/checker/tests/checker/features/identity.rs +21 -0
- compiler/checker/tests/checker/traits_tests.rs +1 -1
- compiler/cli/tests/cli/game_in_place_test.rs +12 -9
- compiler/core/src/compile_builtins.rs +11 -0
- compiler/core/src/native.rs +3 -0
- compiler/core/src/uniqueness.rs +471 -78
- compiler/core/tests/core/main.rs +1 -0
- compiler/core/tests/core/uniqueness_fold_test.rs +103 -0
- compiler/driver/tests/driver_tests.rs +4 -2
- compiler/lsp/src/main.rs +2 -2
- compiler/wasm-codegen/src/emit.rs +2 -0
- compiler/wasm-codegen/src/intrinsics.rs +46 -0
- docs/backlog.md +1 -1
- docs/game.md +1 -1
- docs/language.md +12 -0
- docs/std.md +2 -1
- examples/games/orbitrunner/screens/PlayingScreen.plum +2 -2
- std/game/ScreenSlice.plum +5 -3
- tests/core/copy.plum +72 -0
compiler/checker/src/identity.rs
CHANGED
|
@@ -26,6 +26,30 @@ pub(crate) fn checkSameArgs(name: &str, params: &[PlumType], binds: &Binds, ctx:
|
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
28
|
|
|
29
|
+
/// For a call of `@copy`: an error when its argument type (after `binds`) is known and is not
|
|
30
|
+
/// a struct (a declaration with one variant of its own name). A type parameter passes here and
|
|
31
|
+
/// each instantiation is checked when codegen compiles `@copy` for it.
|
|
32
|
+
pub(crate) fn checkCopyArgs(name: &str, params: &[PlumType], binds: &Binds, ctx: &CheckCtx) -> Result<(), String> {
|
|
33
|
+
if name != plum_core::compile_builtins::COPY_FN {
|
|
34
|
+
return Ok(());
|
|
35
|
+
}
|
|
36
|
+
let Some(p) = params.first() else { return Ok(()) };
|
|
37
|
+
let t = substVars(p, binds);
|
|
38
|
+
let ok = match &t {
|
|
39
|
+
PlumType::TParam(_) | PlumType::TVar(_) => true,
|
|
40
|
+
PlumType::TNamed(n) | PlumType::TApp(n, _) => {
|
|
41
|
+
let vs: Vec<_> = ctx.enum_variants.variantsOf(n).collect();
|
|
42
|
+
matches!(vs.as_slice(), [(v, _)] if *v == n)
|
|
43
|
+
}
|
|
44
|
+
_ => false,
|
|
45
|
+
};
|
|
46
|
+
if ok {
|
|
47
|
+
Ok(())
|
|
48
|
+
} else {
|
|
49
|
+
Err(format!("@copy makes a shallow copy of a struct, and {t} is not one"))
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
29
53
|
fn whyNotHeap(t: &PlumType, ctx: &CheckCtx) -> Option<&'static str> {
|
|
30
54
|
match t {
|
|
31
55
|
PlumType::TInt | PlumType::TFloat | PlumType::TBool | PlumType::TByte | PlumType::TUnit => {
|
compiler/checker/src/infer.rs
CHANGED
|
@@ -685,6 +685,7 @@ pub(crate) fn inferExprInner(
|
|
|
685
685
|
checkCallArgs(&label, ¶m_types, &call.args, required, env, ctx, &mut binds)?;
|
|
686
686
|
checkUnpinned(&call.name, &call.args, &call_map, ¶m_types, &ret, &binds, ctx)?;
|
|
687
687
|
crate::identity::checkSameArgs(&call.name, ¶m_types, &binds, ctx)?;
|
|
688
|
+
crate::identity::checkCopyArgs(&call.name, ¶m_types, &binds, ctx)?;
|
|
688
689
|
recordCall(None, &call.name, call_map);
|
|
689
690
|
Ok(substVars(&ret, &binds))
|
|
690
691
|
}
|
compiler/checker/tests/checker/features/identity.rs
CHANGED
|
@@ -81,3 +81,24 @@ fn the_old_module_is_gone() {
|
|
|
81
81
|
assert!(run("primitive Main =\n fun f(a: Boxed) -> Bool = ref.same(a, a)\n").is_err());
|
|
82
82
|
run("primitive Main =\n fun same(a: Int, b: Int) -> Bool = a == b\n\n fun f() -> Bool = same(1, 2)\n").unwrap();
|
|
83
83
|
}
|
|
84
|
+
|
|
85
|
+
/// `@copy(x)`: a shallow copy of a struct, flat or boxed; a generic argument is checked per
|
|
86
|
+
/// instantiation.
|
|
87
|
+
#[test]
|
|
88
|
+
fn copy_takes_structs() {
|
|
89
|
+
run("primitive Main =\n fun f(a: Boxed, b: Flat, d: Dog, s: Str) -> Boxed =\n _ := @copy(b)\n _ := @copy(d)\n _ := @copy(s)\n @copy(a)\n").unwrap();
|
|
90
|
+
run("primitive Main =\n fun g<T>(a: T) -> T = @copy(a)\n\n fun f(b: Boxed) -> Boxed = g(b)\n").unwrap();
|
|
91
|
+
run("primitive Main =\n fun g<S: Named>(a: S) -> S = @copy(a)\n\n fun f(d: Dog) -> Dog = g(d)\n").unwrap();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
#[test]
|
|
95
|
+
fn copy_rejects_what_is_no_struct() {
|
|
96
|
+
for (ty, arg) in [("Tree", "Leaf"), ("Named", "d"), ("Int", "3"), ("List<Int>", "[1]")] {
|
|
97
|
+
let e = run(&format!("primitive Main =\n fun f(d: Named) -> {ty} = @copy({arg})\n")).unwrap_err();
|
|
98
|
+
assert!(e.contains("@copy makes a shallow copy of a struct"), "{arg}: {e}");
|
|
99
|
+
}
|
|
100
|
+
let e = run("primitive Main =\n fun g<T>(a: T) -> T = @copy(a)\n\n fun f() -> Int = g(3)\n").unwrap_err();
|
|
101
|
+
assert!(e.contains("@copy makes a shallow copy of a struct, and Int is not one"), "{e}");
|
|
102
|
+
let e = run("primitive Main =\n fun f(a: Boxed) -> Boxed = @copy(a, a)\n").unwrap_err();
|
|
103
|
+
assert!(e.contains("@copy takes one value, e.g. @copy(x)"), "{e}");
|
|
104
|
+
}
|
compiler/checker/tests/checker/traits_tests.rs
CHANGED
|
@@ -573,7 +573,7 @@ fn compileTimeBuiltins() {
|
|
|
573
573
|
s: Str := @typeName(Int)
|
|
574
574
|
Pre.show(s)
|
|
575
575
|
");
|
|
576
|
-
fails("primitive Main[App] =\n fun main() =\n Pre.show(@nope(Int))\n", "unknown built-in @nope; the built-ins are @typeName, @sameRef, @memSize, @memGrow, @memStoreF32, @memStoreI32, @memStoreU8, @memLoadF32, @memLoadI32, @memLoadU8");
|
|
576
|
+
fails("primitive Main[App] =\n fun main() =\n Pre.show(@nope(Int))\n", "unknown built-in @nope; the built-ins are @typeName, @sameRef, @copy, @memSize, @memGrow, @memStoreF32, @memStoreI32, @memStoreU8, @memLoadF32, @memLoadI32, @memLoadU8");
|
|
577
577
|
fails("primitive Main[App] =
|
|
578
578
|
fun main() =
|
|
579
579
|
x := 1
|
compiler/cli/tests/cli/game_in_place_test.rs
CHANGED
|
@@ -3,17 +3,17 @@
|
|
|
3
3
|
//! proved. A change that makes the game, a screen or the tick's values shared (another
|
|
4
4
|
//! reference kept across a tick) turns one of them into a copy and fails here, naming it.
|
|
5
5
|
//!
|
|
6
|
-
//! Orbit Runner's
|
|
6
|
+
//! Orbit Runner's reductions are in place again since std's fold copies the screen once as it
|
|
7
|
+
//! enters (`@copy` in `Delivery.deliverTo`): every step of the tick is then unique, so
|
|
8
|
+
//! `PlayingScreen.reduce` (3: steer, scored, hit; `StartOver` copies, its field values written
|
|
9
|
+
//! out of declaration order) and `newMine` need no `$unique` version, which they had when only the
|
|
7
|
-
//!
|
|
10
|
+
//! reductions dispatched from inside `reduce` were unique. Its derived `stepped` is in place too.
|
|
8
|
-
//! Since a slice's `act` returns its follow-ups (`then`), std's fold steps them
|
|
9
|
-
//! (`Delivery.actIn<A, S>`), and the uniqueness pass makes no unique version of a generic
|
|
10
|
-
//! instantiation, so they copy; the delivery's own trail is updated in place.
|
|
11
11
|
//!
|
|
12
12
|
//! `Mine.step` (1), `Mine.put` (1) and `Orb.put$unique` (1) went on 2026-11-16 (R3): an orb
|
|
13
|
-
//! and a mine hold their `Motion`, so a step is one spread of `self`
|
|
13
|
+
//! and a mine hold their `Motion`, so a step is one spread of `self`, a copy as `self` is
|
|
14
|
-
//!
|
|
14
|
+
//! the head of the list it is stepped in (`List.head`, which std's read-only walks `all`,
|
|
15
|
-
//!
|
|
15
|
+
//! `filter` and `next` hand to closures and results), where it was that copy and then one or
|
|
16
|
-
//!
|
|
16
|
+
//! two in-place writes to it: the same allocation a step.
|
|
17
17
|
|
|
18
18
|
use std::collections::BTreeMap;
|
|
19
19
|
use std::process::Command;
|
|
@@ -65,6 +65,9 @@ const TICK: &[(&str, usize)] = &[
|
|
|
65
65
|
fn orbitRunnerKeepsItsInPlaceSpreads() {
|
|
66
66
|
let mut want = TICK.to_vec();
|
|
67
67
|
want.extend([
|
|
68
|
+
("PlayingScreen.reduce", 3),
|
|
69
|
+
("PlayingScreen.at", 1),
|
|
70
|
+
("PlayingScreen.stepped", 1),
|
|
68
71
|
("PlayingScreen.deal", 1),
|
|
69
72
|
("PlayingScreen.newOrb", 1),
|
|
70
73
|
("PlayingScreen.newMine", 1),
|
compiler/core/src/compile_builtins.rs
CHANGED
|
@@ -26,6 +26,12 @@ pub const BUILTINS: &[(&str, Takes, &str)] = &[
|
|
|
26
26
|
// Only for heap types (`plum_checker::identity`); a variable passed to it is never
|
|
27
27
|
// updated in place (`uniqueness`).
|
|
28
28
|
(SAME_REF, Takes::Values(2), "@sameRef(a, b)"),
|
|
29
|
+
// `@copy(x)`: a shallow copy of the struct `x`, another object with the same field values
|
|
30
|
+
// (one `struct.new`; a flat struct is copied by value already). Only for structs
|
|
31
|
+
// (`plum_checker::identity`; a generic argument is checked per instantiation by codegen).
|
|
32
|
+
// The copy is a value no one else holds, so the uniqueness pass may update it in place;
|
|
33
|
+
// its fields stay shared with `x`'s (`uniqueness`).
|
|
34
|
+
(COPY, Takes::Values(1), "@copy(x)"),
|
|
29
35
|
// The program's linear memory: one growable wasm memory (16 pages of 64 KiB to start),
|
|
30
36
|
// exported to the host as "memory", present only in a program that uses one of these.
|
|
31
37
|
// Addresses are byte offsets; every access is little-endian and traps out of bounds.
|
|
@@ -48,10 +54,15 @@ pub const BUILTINS: &[(&str, Takes, &str)] = &[
|
|
|
48
54
|
pub const SAME_REF: &str = "sameRef";
|
|
49
55
|
/// The name of `@sameRef`'s calls and of its declaration.
|
|
50
56
|
pub const SAME_REF_FN: &str = "@sameRef";
|
|
57
|
+
/// `@copy` without its `@`.
|
|
58
|
+
pub const COPY: &str = "copy";
|
|
59
|
+
/// The name of `@copy`'s calls and of its declaration.
|
|
60
|
+
pub const COPY_FN: &str = "@copy";
|
|
51
61
|
|
|
52
62
|
/// What a value built-in is declared as: `(name, type parameters, parameter types, result)`.
|
|
53
63
|
const DECLS: &[(&str, &[&str], &[&str], &str)] = &[
|
|
54
64
|
(SAME_REF_FN, &["T"], &["T", "T"], "Bool"),
|
|
65
|
+
(COPY_FN, &["T"], &["T"], "T"),
|
|
55
66
|
("@memSize", &[], &[], "Int"),
|
|
56
67
|
("@memGrow", &[], &["Int"], "Int"),
|
|
57
68
|
("@memStoreF32", &[], &["Int", "Float"], "Unit"),
|
compiler/core/src/native.rs
CHANGED
|
@@ -64,6 +64,8 @@ pub enum Native {
|
|
|
64
64
|
TypeName,
|
|
65
65
|
/// `@sameRef(a, b)`: one `ref.eq`.
|
|
66
66
|
SameRef,
|
|
67
|
+
/// `@copy(x)`: a shallow copy of a struct, one `struct.new` of its fields.
|
|
68
|
+
Copy,
|
|
67
69
|
/// A linear-memory built-in (`@memSize`, `@memLoadI32`, ...).
|
|
68
70
|
Mem,
|
|
69
71
|
}
|
|
@@ -95,6 +97,7 @@ const TABLE: &[(&str, Native)] = &[
|
|
|
95
97
|
("Array.equal", Native::Array),
|
|
96
98
|
("Str.typeName", Native::TypeName),
|
|
97
99
|
("@sameRef", Native::SameRef),
|
|
100
|
+
("@copy", Native::Copy),
|
|
98
101
|
("@memSize", Native::Mem),
|
|
99
102
|
("@memGrow", Native::Mem),
|
|
100
103
|
("@memStoreF32", Native::Mem),
|
compiler/core/src/uniqueness.rs
CHANGED
|
@@ -508,6 +508,9 @@ struct An {
|
|
|
508
508
|
/// Methods whose `self` is only read: used as the object of field reads and field writes, or
|
|
509
509
|
/// as the receiver of other such methods, never returned, stored, passed on or captured.
|
|
510
510
|
ro: HashSet<usize>,
|
|
511
|
+
/// Parameters their fn only reads (`readOnlyParams`): `self` of the methods in `ro`, and any
|
|
512
|
+
/// other parameter that is only read, through calls too.
|
|
513
|
+
roParams: HashSet<(usize, usize)>,
|
|
511
514
|
/// Per unit, the spreads of closures passed to a parameter that is never called (see
|
|
512
515
|
/// `stripDeadFnArgs`): each runs only as a spread of its type in the specialised copies given.
|
|
513
516
|
deadSpreads: Vec<Vec<DeadSpread>>,
|
|
@@ -547,6 +550,10 @@ struct An {
|
|
|
547
550
|
/// Variable checks in progress, and whether one of them has been answered by assuming it holds.
|
|
548
551
|
active: RefCell<HashSet<(usize, String, bool, bool)>>,
|
|
549
552
|
assumed: std::cell::Cell<bool>,
|
|
553
|
+
/// Field keys a read `g(..).f` of a fresh value may not take over (see `analyse`).
|
|
554
|
+
distrust: HashSet<String>,
|
|
555
|
+
/// Field keys `fresh` took a read `g(..).f` as fresh on: each must be proved unique.
|
|
556
|
+
trustedReads: RefCell<HashSet<String>>,
|
|
550
557
|
}
|
|
551
558
|
|
|
552
559
|
struct DeadSpread {
|
|
@@ -651,18 +658,47 @@ impl An {
|
|
|
651
658
|
let mut tails = vec![];
|
|
652
659
|
collectTails(b, &mut tails) && !tails.is_empty() && tails.iter().all(|t| self.fresh(t))
|
|
653
660
|
}
|
|
661
|
+
// `@copy(x)`: a new object (its fields stay shared: `copiedFields`).
|
|
662
|
+
ExprKind::FnCall(c) if c.name == crate::compile_builtins::COPY_FN => true,
|
|
654
663
|
ExprKind::FnCall(c) => self.isFree(&c.name).is_some_and(|g| self.fresh_ret.borrow().contains(&g)),
|
|
655
664
|
ExprKind::Attribute(a) => match &a.attr {
|
|
656
665
|
AttrKind::Method(c) => {
|
|
657
666
|
let cands = self.cands(c);
|
|
658
667
|
!cands.is_empty() && cands.iter().all(|g| self.fresh_ret.borrow().contains(g))
|
|
659
668
|
}
|
|
669
|
+
// A field of a fresh value (`self.advance(dt).state`): nothing else holds the object,
|
|
670
|
+
// so the field's value is unshared when the field is unique. Taken as fresh unless
|
|
671
|
+
// the field was found shared before; `analyse` checks each one taken.
|
|
672
|
+
AttrKind::Field(f) => {
|
|
673
|
+
if !self.fresh(&a.object) {
|
|
660
|
-
|
|
674
|
+
return false;
|
|
675
|
+
}
|
|
676
|
+
let keys = self.freshFieldKeys(&a.object, f);
|
|
677
|
+
if keys.is_empty() || keys.iter().any(|k| self.distrust.contains(k)) {
|
|
678
|
+
return false;
|
|
679
|
+
}
|
|
680
|
+
self.trustedReads.borrow_mut().extend(keys);
|
|
681
|
+
true
|
|
682
|
+
}
|
|
661
683
|
},
|
|
662
684
|
_ => false,
|
|
663
685
|
}
|
|
664
686
|
}
|
|
665
687
|
|
|
688
|
+
/// The keys a field `f` of the fresh value `o` may be: of `o`'s type when `o` is a
|
|
689
|
+
/// constructor, otherwise of every type with a field `f`.
|
|
690
|
+
fn freshFieldKeys(&self, o: &Expr, f: &str) -> Vec<String> {
|
|
691
|
+
if let ExprKind::ClassCall(c) = &o.kind {
|
|
692
|
+
if let Some(t) = self.owner.get(&c.type_name) {
|
|
693
|
+
return vec![fieldKey(t, f)];
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
let mut types: Vec<&String> =
|
|
697
|
+
self.enums.iter().filter(|(k, names)| self.owner.get(*k) == Some(*k) && names.iter().any(|n| n == f)).map(|(k, _)| k).collect();
|
|
698
|
+
types.sort();
|
|
699
|
+
types.into_iter().map(|t| fieldKey(t, f)).collect()
|
|
700
|
+
}
|
|
701
|
+
|
|
666
702
|
/// The methods a call `x.m(..)` may run. With the receiver's type known (`FnCall.recv`, set
|
|
667
703
|
/// from the checker's types) that is `Type.m` alone, and nothing when the type declares no
|
|
668
704
|
/// such method (a builtin: the call is not a direct call of known fns). Otherwise every
|
|
@@ -1026,6 +1062,9 @@ impl An {
|
|
|
1026
1062
|
if x == "self" && self.ro.contains(&unit) {
|
|
1027
1063
|
return Err("`self` of a read-only method: its callers keep using it".to_string());
|
|
1028
1064
|
}
|
|
1065
|
+
if self.units[unit].params.iter().position(|p| p.name == x).is_some_and(|j| self.roParams.contains(&(unit, j))) {
|
|
1066
|
+
return Err(format!("`{x}` is a parameter its fn only reads: its callers keep using it"));
|
|
1067
|
+
}
|
|
1029
1068
|
if caseTouches(c, k, x) {
|
|
1030
1069
|
return Err(format!("`{x}` is still used in the arm that takes it apart"));
|
|
1031
1070
|
}
|
|
@@ -1333,6 +1372,63 @@ impl<'a> Scan<'a> {
|
|
|
1333
1372
|
found
|
|
1334
1373
|
}
|
|
1335
1374
|
|
|
1375
|
+
/// Does `e` use the variable only to read it: each use the object of a field read, the receiver
|
|
1376
|
+
/// of read-only methods or an argument of read-only parameters (`An.roParams`), none in a
|
|
1377
|
+
/// closure? (No use at all counts.)
|
|
1378
|
+
fn onlyReads(&self, e: &Expr) -> bool {
|
|
1379
|
+
let an = self.an;
|
|
1380
|
+
let v = self.v;
|
|
1381
|
+
let (mut uses, mut reads, mut bad) = (0usize, 0usize, false);
|
|
1382
|
+
walkExpr(e, &mut |n| {
|
|
1383
|
+
if let Node::E(x) = n {
|
|
1384
|
+
match &x.kind {
|
|
1385
|
+
_ if isVar(x, v) => uses += 1,
|
|
1386
|
+
ExprKind::FnCall(c) if c.name == crate::compile_builtins::COPY_FN => {
|
|
1387
|
+
reads += c.args.iter().filter(|a| isVar(argExpr(a), v)).count();
|
|
1388
|
+
}
|
|
1389
|
+
ExprKind::Attribute(a) if isVar(&a.object, v) => match &a.attr {
|
|
1390
|
+
AttrKind::Field(_) => reads += 1,
|
|
1391
|
+
AttrKind::Method(c) => {
|
|
1392
|
+
let cands = an.cands(c);
|
|
1393
|
+
if !cands.is_empty() && cands.iter().all(|g| an.ro.contains(g)) {
|
|
1394
|
+
reads += 1;
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
},
|
|
1398
|
+
ExprKind::Closure(_) => {
|
|
1399
|
+
let mut f = false;
|
|
1400
|
+
walkExpr(x, &mut |m| {
|
|
1401
|
+
if let Node::E(y) = m {
|
|
1402
|
+
f |= isVar(y, v);
|
|
1403
|
+
}
|
|
1404
|
+
!f
|
|
1405
|
+
});
|
|
1406
|
+
bad |= f;
|
|
1407
|
+
}
|
|
1408
|
+
_ => {}
|
|
1409
|
+
}
|
|
1410
|
+
if let Some(targets) = an.callTargets(x) {
|
|
1411
|
+
let args: Vec<&Expr> = match &x.kind {
|
|
1412
|
+
ExprKind::FnCall(c) if c.name == crate::compile_builtins::COPY_FN => vec![],
|
|
1413
|
+
ExprKind::FnCall(c) => c.args.iter().map(argExpr).filter(|y| isVar(y, v)).collect(),
|
|
1414
|
+
ExprKind::Attribute(a) => match &a.attr {
|
|
1415
|
+
AttrKind::Method(c) => c.args.iter().map(argExpr).filter(|y| isVar(y, v)).collect(),
|
|
1416
|
+
_ => vec![],
|
|
1417
|
+
},
|
|
1418
|
+
_ => vec![],
|
|
1419
|
+
};
|
|
1420
|
+
for y in args {
|
|
1421
|
+
if targets.iter().all(|(t, given)| given.iter().enumerate().any(|(i, a)| a.is_some_and(|a| a.id == y.id) && an.roParams.contains(&(*t, i)))) {
|
|
1422
|
+
reads += 1;
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
!bad
|
|
1428
|
+
});
|
|
1429
|
+
!bad && uses == reads
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1336
1432
|
fn mentionsStmts(&self, ss: &[Stmt]) -> bool {
|
|
1337
1433
|
ss.iter().any(|s| self.mentionsStmt(s))
|
|
1338
1434
|
}
|
|
@@ -1629,13 +1725,27 @@ impl<'a> Scan<'a> {
|
|
|
1629
1725
|
self.failWith(|| format!("`{v}` is compared by identity (`@sameRef`), so it is never updated in place"));
|
|
1630
1726
|
return;
|
|
1631
1727
|
}
|
|
1728
|
+
// `@copy(v)` reads `v`'s fields into a new object and keeps nothing of `v` itself.
|
|
1729
|
+
if c.name == crate::compile_builtins::COPY_FN {
|
|
1730
|
+
for (k, a) in c.args.iter().enumerate() {
|
|
1731
|
+
let e = argExpr(a);
|
|
1732
|
+
if !self.bare(e) {
|
|
1733
|
+
let lv = live || c.args[k + 1..].iter().any(|x| self.mentions(argExpr(x)));
|
|
1734
|
+
self.expr(e, false, lv);
|
|
1735
|
+
}
|
|
1736
|
+
}
|
|
1737
|
+
return;
|
|
1738
|
+
}
|
|
1632
1739
|
for (k, a) in c.args.iter().enumerate() {
|
|
1633
1740
|
let e = argExpr(a);
|
|
1634
1741
|
let lv = live || c.args[k + 1..].iter().any(|x| self.mentions(argExpr(x)));
|
|
1635
1742
|
if self.bare(e) {
|
|
1743
|
+
// Handed to a parameter the callee only reads: a read, like a field read.
|
|
1744
|
+
let read = g.is_some_and(|g| self.an.paramPos(g, c, k).is_some_and(|j| self.an.roParams.contains(&(g, j))));
|
|
1745
|
+
let ok = read
|
|
1636
|
-
|
|
1746
|
+
|| bareCount == 1
|
|
1637
|
-
|
|
1747
|
+
&& !lv
|
|
1638
|
-
|
|
1748
|
+
&& g.is_some_and(|g| self.an.paramPos(g, c, k).is_some_and(|j| self.an.handOk(g, j)));
|
|
1639
1749
|
if !ok {
|
|
1640
1750
|
self.failWith(|| format!("`{v}` is passed to `{}`, which may keep it or the caller reads it afterwards", c.name));
|
|
1641
1751
|
}
|
|
@@ -1674,7 +1784,9 @@ impl<'a> Scan<'a> {
|
|
|
1674
1784
|
let e = argExpr(x);
|
|
1675
1785
|
let lv = live || c.args[k + 1..].iter().any(|y| self.mentions(argExpr(y)));
|
|
1676
1786
|
if self.bare(e) {
|
|
1787
|
+
let read = !cands.is_empty()
|
|
1788
|
+
&& cands.iter().all(|&g| self.an.units[g].hasSelf != isType && self.an.methodParam(g, c, Some(k)).is_some_and(|j| self.an.roParams.contains(&(g, j))));
|
|
1677
|
-
if !handOver(self, Some(k), lv) {
|
|
1789
|
+
if !read && !handOver(self, Some(k), lv) {
|
|
1678
1790
|
self.failWith(|| format!("`{v}` is passed to method `{}`, which may keep it or the caller reads it afterwards", c.name));
|
|
1679
1791
|
}
|
|
1680
1792
|
} else {
|
|
@@ -1727,8 +1839,12 @@ impl<'a> Scan<'a> {
|
|
|
1727
1839
|
let others = cc.fields.iter().enumerate().any(|(i, x)| i != k && self.mentions(&x.value));
|
|
1728
1840
|
let lv = live || spreadMentions || others;
|
|
1729
1841
|
// The last use of `v`, moved into the field: the object now holds it alone. Whether
|
|
1730
|
-
// that keeps the field unique is `varWrites`' business.
|
|
1842
|
+
// that keeps the field unique is `varWrites`' business. The other values may still
|
|
1843
|
+
// read `v` (`Next(state: self, then: [if self.over then StartOver])`): a read keeps
|
|
1844
|
+
// nothing, whichever runs first.
|
|
1845
|
+
let othersRead = cc.fields.iter().enumerate().all(|(i, x)| i == k || self.onlyReads(&x.value));
|
|
1846
|
+
let movable = !live && !spreadMentions && othersRead;
|
|
1731
|
-
if self.bare(&fa.value) &&
|
|
1847
|
+
if self.bare(&fa.value) && movable && !self.strict {
|
|
1732
1848
|
continue;
|
|
1733
1849
|
}
|
|
1734
1850
|
self.operand(&fa.value, lv, || format!("`{v}` is stored in field `{}`", fa.name));
|
|
@@ -1800,12 +1916,11 @@ fn fieldsOf(enums: &HashMap<String, Vec<String>>, t: &str) -> Option<Vec<String>
|
|
|
1800
1916
|
pub fn markUnique(src: &mut Source) -> UniqueReport {
|
|
1801
1917
|
// The analysis tables are keyed by node id; simplify and drive leave new nodes unnumbered.
|
|
1802
1918
|
numberIds(src);
|
|
1919
|
+
let mut distrust: HashSet<String> = HashSet::new();
|
|
1803
|
-
let (versions, solved) = versionCallers(src);
|
|
1920
|
+
let (versions, solved) = versionCallers(src, &mut distrust);
|
|
1804
1921
|
// The versions' last analysis, when the program has not changed since.
|
|
1805
1922
|
let an = solved.unwrap_or_else(|| {
|
|
1806
|
-
|
|
1923
|
+
analyse(src, &mut distrust)
|
|
1807
|
-
solve(&an);
|
|
1808
|
-
an
|
|
1809
1924
|
});
|
|
1810
1925
|
// Report and mark.
|
|
1811
1926
|
let mut report = UniqueReport { versions, ..UniqueReport::default() };
|
|
@@ -2085,7 +2200,23 @@ fn varTypes(u: &Unit) -> HashMap<String, Option<String>> {
|
|
|
2085
2200
|
const SHADOW_MARK: &str = "\u{0}shadow";
|
|
2086
2201
|
|
|
2087
2202
|
|
|
2203
|
+
/// `build` and `solve`, again while a field read `g(..).f` was taken as fresh (`An.fresh`) on a
|
|
2204
|
+
/// field the proof then found shared: that field is distrusted from then on (`distrust` keeps
|
|
2205
|
+
/// what was learnt across the calls of one `markUnique`). Each round only takes freshness away,
|
|
2206
|
+
/// so it ends.
|
|
2207
|
+
fn analyse(src: &Source, distrust: &mut HashSet<String>) -> An {
|
|
2208
|
+
loop {
|
|
2209
|
+
let an = crate::timing::time("build", || build(src, distrust));
|
|
2210
|
+
crate::timing::time("solve", || solve(&an));
|
|
2211
|
+
let wrong: Vec<String> = an.trustedReads.borrow().iter().filter(|k| !an.uf.borrow().contains(*k)).cloned().collect();
|
|
2212
|
+
if wrong.is_empty() {
|
|
2213
|
+
return an;
|
|
2214
|
+
}
|
|
2215
|
+
distrust.extend(wrong);
|
|
2216
|
+
}
|
|
2217
|
+
}
|
|
2218
|
+
|
|
2088
|
-
fn build(src: &Source) -> An {
|
|
2219
|
+
fn build(src: &Source, distrust: &HashSet<String>) -> An {
|
|
2089
2220
|
let mut units: Vec<Unit> = Vec::new();
|
|
2090
2221
|
let mut enums: HashMap<String, Vec<String>> = HashMap::new();
|
|
2091
2222
|
let mut nameCount: HashMap<String, usize> = HashMap::new();
|
|
@@ -2294,6 +2425,7 @@ fn build(src: &Source) -> An {
|
|
|
2294
2425
|
poisonAll: false,
|
|
2295
2426
|
spreads: vec![],
|
|
2296
2427
|
ro: HashSet::new(),
|
|
2428
|
+
roParams: HashSet::new(),
|
|
2297
2429
|
deadSpreads: vec![],
|
|
2298
2430
|
arrayFresh: HashSet::new(),
|
|
2299
2431
|
live: vec![],
|
|
@@ -2309,6 +2441,8 @@ fn build(src: &Source) -> An {
|
|
|
2309
2441
|
mutTypes,
|
|
2310
2442
|
active: RefCell::new(HashSet::new()),
|
|
2311
2443
|
assumed: std::cell::Cell::new(false),
|
|
2444
|
+
distrust: distrust.clone(),
|
|
2445
|
+
trustedReads: RefCell::new(HashSet::new()),
|
|
2312
2446
|
};
|
|
2313
2447
|
stripDeadFnArgs(&mut an);
|
|
2314
2448
|
an.live = liveUnits(&an, src);
|
|
@@ -2320,7 +2454,8 @@ fn build(src: &Source) -> An {
|
|
|
2320
2454
|
_ => {}
|
|
2321
2455
|
}
|
|
2322
2456
|
}
|
|
2457
|
+
an.roParams = crate::timing::time("ro params", || readOnlyParams(&an));
|
|
2323
|
-
an.ro = readOnlySelf(&an);
|
|
2458
|
+
an.ro = readOnlySelf(&an, &an.roParams);
|
|
2324
2459
|
an.reuseCands = reuseCandidates(&an);
|
|
2325
2460
|
// Fresh-return fns: greatest fixpoint.
|
|
2326
2461
|
let mut fr: HashSet<usize> = an.freeIdx.values().copied().collect();
|
|
@@ -2410,7 +2545,11 @@ fn build(src: &Source) -> An {
|
|
|
2410
2545
|
binders.push((j, n.to_string()));
|
|
2411
2546
|
Some(j)
|
|
2412
2547
|
};
|
|
2548
|
+
// A local bound once and used once (`withOrbs := ..fold(fresh, ..)` then
|
|
2549
|
+
// `..fold(withOrbs, ..)`): no one else can hold it, so it stands for its value.
|
|
2413
|
-
|
|
2550
|
+
let mut flat = flat;
|
|
2551
|
+
let mut seenLocals: HashSet<String> = HashSet::new();
|
|
2552
|
+
while let Some(e) = flat.pop() {
|
|
2414
2553
|
if an.fresh(e) {
|
|
2415
2554
|
continue;
|
|
2416
2555
|
}
|
|
@@ -2418,6 +2557,10 @@ fn build(src: &Source) -> An {
|
|
|
2418
2557
|
ps.push(j);
|
|
2419
2558
|
continue;
|
|
2420
2559
|
}
|
|
2560
|
+
if let Some(v) = varName(e).and_then(|n| if seenLocals.insert(n.to_string()) { singleUseLocal(u, n) } else { None }) {
|
|
2561
|
+
flat.push(v);
|
|
2562
|
+
continue;
|
|
2563
|
+
}
|
|
2421
2564
|
// `Map.glue(l, r)`, which returns `l`, `r` or a fresh map.
|
|
2422
2565
|
match an.callTargets(e) {
|
|
2423
2566
|
Some(targets) => {
|
|
@@ -2434,7 +2577,11 @@ fn build(src: &Source) -> An {
|
|
|
2434
2577
|
Some(a) if an.fresh(a) => {}
|
|
2435
2578
|
Some(a) => match ofParam(a, &mut binders) {
|
|
2436
2579
|
Some(j) => ps.push(j),
|
|
2580
|
+
// What `h` returns of it is this fn's result: look at its value.
|
|
2581
|
+
None => match varName(a).and_then(|n| if seenLocals.insert(n.to_string()) { singleUseLocal(u, n) } else { None }) {
|
|
2582
|
+
Some(v) => flat.push(v),
|
|
2437
|
-
|
|
2583
|
+
None => ok = false,
|
|
2584
|
+
},
|
|
2438
2585
|
},
|
|
2439
2586
|
None => ok = false,
|
|
2440
2587
|
}
|
|
@@ -2469,12 +2616,132 @@ fn build(src: &Source) -> An {
|
|
|
2469
2616
|
an.passBinders.clear();
|
|
2470
2617
|
}
|
|
2471
2618
|
collectFacts(&mut an);
|
|
2619
|
+
for (key, why) in copiedFields(&an, src) {
|
|
2620
|
+
an.ufWhy.borrow_mut().entry(key.clone()).or_insert(why);
|
|
2621
|
+
an.badField.insert(key);
|
|
2622
|
+
}
|
|
2472
2623
|
let (host, hostMain) = hostShared(&an, src);
|
|
2473
2624
|
an.escaped.extend(host);
|
|
2474
2625
|
an.hostMain = hostMain;
|
|
2475
2626
|
an
|
|
2476
2627
|
}
|
|
2477
2628
|
|
|
2629
|
+
/// The value of `n` when it is a local of `u` declared once (`n := v`, in no loop), never assigned
|
|
2630
|
+
/// again, bound by no pattern or closure parameter and mentioned once after: its one use then
|
|
2631
|
+
/// holds the value alone, as if `v` were written there.
|
|
2632
|
+
fn singleUseLocal<'u>(u: &'u Unit, n: &str) -> Option<&'u Expr> {
|
|
2633
|
+
if u.params.iter().any(|p| p.name == n) {
|
|
2634
|
+
return None;
|
|
2635
|
+
}
|
|
2636
|
+
let mut value: Option<&Expr> = None;
|
|
2637
|
+
let (mut binds, mut uses, mut bad) = (0usize, 0usize, false);
|
|
2638
|
+
walkBlock(&u.block, &mut |node| {
|
|
2639
|
+
match node {
|
|
2640
|
+
Node::S(Stmt { kind: StmtKind::Assign(a), .. }) => {
|
|
2641
|
+
for t in &a.targets {
|
|
2642
|
+
if matches!(t, AssignTarget::Var(v) if v == n) {
|
|
2643
|
+
binds += 1;
|
|
2644
|
+
if a.declare && a.targets.len() == 1 && a.values.len() == 1 {
|
|
2645
|
+
value = Some(&a.values[0]);
|
|
2646
|
+
} else {
|
|
2647
|
+
bad = true;
|
|
2648
|
+
}
|
|
2649
|
+
}
|
|
2650
|
+
}
|
|
2651
|
+
}
|
|
2652
|
+
Node::S(Stmt { kind: StmtKind::While(_), .. }) => {
|
|
2653
|
+
let mut inLoop = false;
|
|
2654
|
+
if let Node::S(s) = node {
|
|
2655
|
+
walkStmt(s, &mut |m| {
|
|
2656
|
+
if let Node::S(Stmt { kind: StmtKind::Assign(a), .. }) = m {
|
|
2657
|
+
inLoop |= a.targets.iter().any(|t| matches!(t, AssignTarget::Var(v) if v == n));
|
|
2658
|
+
}
|
|
2659
|
+
!inLoop
|
|
2660
|
+
});
|
|
2661
|
+
}
|
|
2662
|
+
bad |= inLoop;
|
|
2663
|
+
}
|
|
2664
|
+
Node::S(Stmt { kind: StmtKind::Match(m), .. }) => {
|
|
2665
|
+
bad |= m.cases.iter().any(|c| c.patterns.iter().any(|p| {
|
|
2666
|
+
let mut names = vec![];
|
|
2667
|
+
crate::visit::patternBinders(p, &mut names);
|
|
2668
|
+
names.iter().any(|x| x == n)
|
|
2669
|
+
}));
|
|
2670
|
+
}
|
|
2671
|
+
Node::E(e) => match &e.kind {
|
|
2672
|
+
_ if isVar(e, n) => uses += 1,
|
|
2673
|
+
ExprKind::Closure(c) => bad |= c.params.iter().any(|p| p == n),
|
|
2674
|
+
ExprKind::Bind(b) => {
|
|
2675
|
+
bad |= b.case.patterns.iter().any(|p| {
|
|
2676
|
+
let mut names = vec![];
|
|
2677
|
+
crate::visit::patternBinders(p, &mut names);
|
|
2678
|
+
names.iter().any(|x| x == n)
|
|
2679
|
+
})
|
|
2680
|
+
}
|
|
2681
|
+
_ => {}
|
|
2682
|
+
},
|
|
2683
|
+
_ => {}
|
|
2684
|
+
}
|
|
2685
|
+
!bad
|
|
2686
|
+
});
|
|
2687
|
+
if bad || binds != 1 || uses != 1 {
|
|
2688
|
+
return None;
|
|
2689
|
+
}
|
|
2690
|
+
value
|
|
2691
|
+
}
|
|
2692
|
+
|
|
2693
|
+
/// The fields `@copy(x)` shares between `x` and its copy, which then has a second holder: every
|
|
2694
|
+
/// field of `x`'s type, when it is known; of every type implementing the first bound of `x`'s type
|
|
2695
|
+
/// parameter (the program's types after `trait_defaults::expandSupertraits`, so a subtrait's
|
|
2696
|
+
/// implementers are among them), when it is one; of every type otherwise. With the reason.
|
|
2697
|
+
fn copiedFields(an: &An, src: &Source) -> Vec<(String, String)> {
|
|
2698
|
+
let mut out = vec![];
|
|
2699
|
+
for (ui, u) in an.units.iter().enumerate() {
|
|
2700
|
+
if u.kind != Kind::Fn {
|
|
2701
|
+
continue;
|
|
2702
|
+
}
|
|
2703
|
+
let mut args: Vec<&Expr> = vec![];
|
|
2704
|
+
walkBlock(&u.block, &mut |n| {
|
|
2705
|
+
if let Node::E(Expr { kind: ExprKind::FnCall(c), .. }) = n {
|
|
2706
|
+
if c.name == crate::compile_builtins::COPY_FN {
|
|
2707
|
+
args.extend(c.args.first().map(argExpr));
|
|
2708
|
+
}
|
|
2709
|
+
}
|
|
2710
|
+
true
|
|
2711
|
+
});
|
|
2712
|
+
for x in args {
|
|
2713
|
+
let types: Vec<String> = match an.ownerOf(ui, x) {
|
|
2714
|
+
Some(t) => vec![t],
|
|
2715
|
+
None => {
|
|
2716
|
+
let f = match &src.items[u.itemIdx] {
|
|
2717
|
+
Item::Fn(f) => Some(f),
|
|
2718
|
+
_ => None,
|
|
2719
|
+
};
|
|
2720
|
+
// The declared type of a parameter, when it is one of the fn's bounded generics.
|
|
2721
|
+
let bound = varName(x).zip(f).and_then(|(n, f)| {
|
|
2722
|
+
let p = f.params.iter().find(|p| p.name == n)?;
|
|
2723
|
+
let ParamType::Type(t) = &p.ty else { return None };
|
|
2724
|
+
f.bounds.iter().find(|(g, _)| *g == t.name).and_then(|(_, bs)| bs.first()).map(|b| b.name.clone())
|
|
2725
|
+
});
|
|
2726
|
+
src.items
|
|
2727
|
+
.iter()
|
|
2728
|
+
.filter_map(|i| match i {
|
|
2729
|
+
Item::Enum(e) if bound.as_ref().is_none_or(|b| e.implements.iter().any(|t| &t.name == b)) => Some(e.name.clone()),
|
|
2730
|
+
_ => None,
|
|
2731
|
+
})
|
|
2732
|
+
.collect()
|
|
2733
|
+
}
|
|
2734
|
+
};
|
|
2735
|
+
for t in types {
|
|
2736
|
+
for f in fieldsOf(&an.enums, &t).unwrap_or_default() {
|
|
2737
|
+
out.push((fieldKey(&t, &f), format!("`@copy` in {} shares it with the copy", u.label)));
|
|
2738
|
+
}
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
}
|
|
2742
|
+
out
|
|
2743
|
+
}
|
|
2744
|
+
|
|
2478
2745
|
/// The units the program can run, found from its entry points by name (a method call of known
|
|
2479
2746
|
/// receiver type by type as well). Everything the compiler itself may call stays an entry point:
|
|
2480
2747
|
/// exports, lowered tests, `IMPLICIT` methods, constants, and all of std except specialised copies,
|
|
@@ -3114,8 +3381,6 @@ fn readsBefore(b: &Block, spread: NodeId, o: &str, g: &str, out: &mut Vec<NodeId
|
|
|
3114
3381
|
}
|
|
3115
3382
|
}
|
|
3116
3383
|
|
|
3117
|
-
/// The methods whose `self` is only read (see `An.ro`): a greatest fixpoint, since a method may
|
|
3118
|
-
/// call another read-only one on `self`.
|
|
3119
3384
|
/// Does `p` hold an uppercase name that is no type or variant? Codegen binds it like a lowercase
|
|
3120
3385
|
/// one, but `patternBinders` does not list it.
|
|
3121
3386
|
fn oddName(an: &An, p: &CasePattern) -> bool {
|
|
@@ -3191,77 +3456,201 @@ fn selfMatchReads(an: &An, ro: &HashSet<usize>, c: &Case, k: usize) -> bool {
|
|
|
3191
3456
|
!handed
|
|
3192
3457
|
}
|
|
3193
3458
|
|
|
3459
|
+
/// The methods whose `self` is only read (see `An.ro`), out of `readOnlyParams`.
|
|
3460
|
+
fn readOnlySelf(an: &An, params: &HashSet<(usize, usize)>) -> HashSet<usize> {
|
|
3461
|
+
(0..an.units.len()).filter(|&g| an.units[g].kind == Kind::Fn && an.units[g].method && an.units[g].hasSelf && params.contains(&(g, 0))).collect()
|
|
3462
|
+
}
|
|
3463
|
+
|
|
3464
|
+
/// The parameters (`self` among them, as parameter 0 of a method) that their fn only reads: each
|
|
3465
|
+
/// use is the object of a field read or a field write, the receiver of methods whose `self` is
|
|
3466
|
+
/// only read, a `match` that only reads it (`selfMatchReads`), or a bare argument of a direct call
|
|
3467
|
+
/// whose every target only reads that parameter too. Never returned, stored, bound to another
|
|
3468
|
+
/// name, rebound or captured by a closure. A greatest fixpoint, since fns call each other. A call
|
|
3469
|
+
/// that hands such a parameter a unique value leaves it unique: nothing the callee does keeps it.
|
|
3470
|
+
/// (Fusion turns a closure's captured `self` into an argument of the specialised copy, so a
|
|
3471
|
+
/// method like a screen's `view`, which maps over a range with a closure reading `self.clock`,
|
|
3472
|
+
/// is read-only through that copy's parameter.)
|
|
3194
|
-
fn
|
|
3473
|
+
fn readOnlyParams(an: &An) -> HashSet<(usize, usize)> {
|
|
3474
|
+
let mut ro: HashSet<(usize, usize)> = HashSet::new();
|
|
3475
|
+
for (g, u) in an.units.iter().enumerate() {
|
|
3476
|
+
// A body the compiler or the host supplies (`@native`, an extern) shows no uses: it may
|
|
3477
|
+
// keep anything it is given (`Slice.push`). `@copy`'s argument is handled by name.
|
|
3478
|
+
let opaque = u.block.stmts.is_empty() || u.block.stmts.iter().any(|s| matches!(s.kind, StmtKind::Native));
|
|
3479
|
+
if u.kind == Kind::Fn && !opaque {
|
|
3480
|
+
for (j, p) in u.params.iter().enumerate() {
|
|
3481
|
+
if p.plain {
|
|
3482
|
+
ro.insert((g, j));
|
|
3483
|
+
}
|
|
3484
|
+
}
|
|
3485
|
+
}
|
|
3486
|
+
}
|
|
3487
|
+
let mut selfRo = readOnlySelf(an, &ro);
|
|
3488
|
+
// Who calls whom: a unit is asked again only when a fn it may call lost a parameter.
|
|
3489
|
+
let mut callers: Vec<Vec<usize>> = vec![vec![]; an.units.len()];
|
|
3490
|
+
for (g, u) in an.units.iter().enumerate() {
|
|
3491
|
+
if u.kind != Kind::Fn {
|
|
3492
|
+
continue;
|
|
3493
|
+
}
|
|
3195
|
-
|
|
3494
|
+
let mut callees: HashSet<usize> = HashSet::new();
|
|
3495
|
+
walkBlock(&u.block, &mut |n| {
|
|
3496
|
+
if let Node::E(e) = n {
|
|
3497
|
+
if let ExprKind::Attribute(a) = &e.kind {
|
|
3498
|
+
if let AttrKind::Method(c) = &a.attr {
|
|
3499
|
+
callees.extend(an.cands(c));
|
|
3500
|
+
}
|
|
3501
|
+
}
|
|
3502
|
+
if let Some(ts) = an.callTargets(e) {
|
|
3503
|
+
callees.extend(ts.into_iter().map(|(t, _)| t));
|
|
3504
|
+
}
|
|
3505
|
+
}
|
|
3506
|
+
true
|
|
3507
|
+
});
|
|
3508
|
+
for c in callees {
|
|
3509
|
+
callers[c].push(g);
|
|
3510
|
+
}
|
|
3511
|
+
}
|
|
3196
|
-
|
|
3512
|
+
let mut queue: Vec<usize> = (0..an.units.len()).filter(|&g| an.units[g].kind == Kind::Fn).collect();
|
|
3513
|
+
let mut queued: HashSet<usize> = queue.iter().copied().collect();
|
|
3197
|
-
|
|
3514
|
+
while let Some(g) = queue.pop() {
|
|
3515
|
+
queued.remove(&g);
|
|
3198
|
-
let mut
|
|
3516
|
+
let mut changed = false;
|
|
3517
|
+
for j in 0..an.units[g].params.len() {
|
|
3518
|
+
if ro.contains(&(g, j)) && !paramOnlyRead(an, &ro, &selfRo, g, j) {
|
|
3519
|
+
ro.remove(&(g, j));
|
|
3520
|
+
changed = true;
|
|
3521
|
+
}
|
|
3522
|
+
}
|
|
3523
|
+
if changed {
|
|
3524
|
+
selfRo.remove(&g);
|
|
3199
|
-
|
|
3525
|
+
for &c in &callers[g] {
|
|
3526
|
+
if queued.insert(c) {
|
|
3527
|
+
queue.push(c);
|
|
3528
|
+
}
|
|
3529
|
+
}
|
|
3530
|
+
// `match self` and binder reads of any unit may lean on `selfRo` through `cands`
|
|
3531
|
+
// only, which `callers` covers.
|
|
3532
|
+
}
|
|
3533
|
+
}
|
|
3534
|
+
ro
|
|
3535
|
+
}
|
|
3536
|
+
|
|
3537
|
+
/// Does fn `g` only read its parameter `j` (see `readOnlyParams`)?
|
|
3538
|
+
fn paramOnlyRead(an: &An, ro: &HashSet<(usize, usize)>, selfRo: &HashSet<usize>, g: usize, j: usize) -> bool {
|
|
3539
|
+
let u = &an.units[g];
|
|
3540
|
+
let name = u.params[j].name.as_str();
|
|
3541
|
+
let isP = |e: &Expr| isVar(e, name);
|
|
3200
|
-
|
|
3542
|
+
let mut all: Vec<NodeId> = vec![];
|
|
3201
|
-
|
|
3543
|
+
let mut allowed: HashSet<NodeId> = HashSet::new();
|
|
3202
|
-
|
|
3544
|
+
let mut captured: HashSet<NodeId> = HashSet::new();
|
|
3545
|
+
let mut rebound = false;
|
|
3546
|
+
// `self` keeps `selfMatchReads` as it was; another parameter's match is a read only when
|
|
3547
|
+
// every binder is only read too: one whose field leaves the arm (into a constructor, as a
|
|
3548
|
+
// result) takes the parameter apart, which its callers may want to hand over uniquely.
|
|
3549
|
+
let isSelf = u.method && u.hasSelf && j == 0;
|
|
3550
|
+
let matchReads = |c: &Case, k: usize| {
|
|
3551
|
+
selfMatchReads(an, selfRo, c, k)
|
|
3552
|
+
&& (isSelf || {
|
|
3553
|
+
let mut bs = vec![];
|
|
3554
|
+
crate::visit::patternBinders(&c.patterns[k], &mut bs);
|
|
3555
|
+
bs.iter().all(|b| an.binderReadOnly(c, k, b))
|
|
3556
|
+
})
|
|
3557
|
+
};
|
|
3558
|
+
let bindsP = |p: &CasePattern| {
|
|
3559
|
+
let mut names = vec![];
|
|
3560
|
+
crate::visit::patternBinders(p, &mut names);
|
|
3561
|
+
names.iter().any(|n| n == name)
|
|
3562
|
+
};
|
|
3203
|
-
|
|
3563
|
+
walkBlock(&u.block, &mut |n| {
|
|
3204
|
-
|
|
3564
|
+
match n {
|
|
3565
|
+
Node::E(e) => {
|
|
3205
|
-
|
|
3566
|
+
match &e.kind {
|
|
3206
|
-
|
|
3567
|
+
_ if isP(e) => all.push(e.id),
|
|
3568
|
+
ExprKind::Bind(b) => {
|
|
3569
|
+
rebound |= b.case.patterns.iter().any(|p| bindsP(p));
|
|
3207
|
-
|
|
3570
|
+
if isP(&b.value) && b.case.patterns.len() == 1 && matchReads(&b.case, 0) {
|
|
3208
|
-
if selfMatchReads(an, &ro, &b.case, 0) {
|
|
3209
|
-
|
|
3571
|
+
allowed.insert(b.value.id);
|
|
3210
|
-
|
|
3572
|
+
}
|
|
3573
|
+
}
|
|
3574
|
+
ExprKind::Attribute(a) if isP(&a.object) => match &a.attr {
|
|
3575
|
+
AttrKind::Field(_) => {
|
|
3576
|
+
allowed.insert(a.object.id);
|
|
3211
3577
|
}
|
|
3212
|
-
ExprKind::Attribute(a) if matches!(a.object.kind, ExprKind::Self_) => match &a.attr {
|
|
3213
|
-
|
|
3578
|
+
AttrKind::Method(c) => {
|
|
3579
|
+
let cands = an.cands(c);
|
|
3580
|
+
if !cands.is_empty() && cands.iter().all(|x| selfRo.contains(x)) {
|
|
3214
3581
|
allowed.insert(a.object.id);
|
|
3215
3582
|
}
|
|
3583
|
+
}
|
|
3584
|
+
},
|
|
3216
|
-
|
|
3585
|
+
ExprKind::Closure(cl) => {
|
|
3217
|
-
let cands = an.cands(c);
|
|
3218
|
-
|
|
3586
|
+
rebound |= cl.params.iter().any(|p| p == name);
|
|
3587
|
+
walkExpr(e, &mut |m| {
|
|
3588
|
+
if let Node::E(x) = m {
|
|
3589
|
+
if isP(x) {
|
|
3219
|
-
|
|
3590
|
+
captured.insert(x.id);
|
|
3220
3591
|
}
|
|
3221
3592
|
}
|
|
3222
|
-
},
|
|
3223
|
-
ExprKind::Closure(_) => walkExpr(e, &mut |m| {
|
|
3224
|
-
if let Node::E(Expr { kind: ExprKind::Self_, id, .. }) = m {
|
|
3225
|
-
captured.insert(*id);
|
|
3226
|
-
}
|
|
3227
3593
|
true
|
|
3228
|
-
})
|
|
3594
|
+
})
|
|
3595
|
+
}
|
|
3229
|
-
|
|
3596
|
+
_ => {}
|
|
3597
|
+
}
|
|
3598
|
+
// A bare argument of a direct call: read-only when every fn the call may run only
|
|
3599
|
+
// reads the parameter it lands in.
|
|
3600
|
+
let args: Vec<&Expr> = match &e.kind {
|
|
3601
|
+
ExprKind::FnCall(c) if c.name == crate::compile_builtins::COPY_FN => {
|
|
3602
|
+
for x in c.args.iter().map(argExpr).filter(|x| isP(x)) {
|
|
3603
|
+
allowed.insert(x.id);
|
|
3604
|
+
}
|
|
3605
|
+
vec![]
|
|
3606
|
+
}
|
|
3607
|
+
ExprKind::FnCall(c) => c.args.iter().map(argExpr).filter(|x| isP(x)).collect(),
|
|
3608
|
+
ExprKind::Attribute(a) => match &a.attr {
|
|
3609
|
+
AttrKind::Method(c) => c.args.iter().map(argExpr).filter(|x| isP(x)).collect(),
|
|
3610
|
+
_ => vec![],
|
|
3230
3611
|
},
|
|
3612
|
+
_ => vec![],
|
|
3613
|
+
};
|
|
3614
|
+
if !args.is_empty() {
|
|
3231
|
-
|
|
3615
|
+
if let Some(targets) = an.callTargets(e) {
|
|
3232
|
-
for
|
|
3616
|
+
for x in args {
|
|
3233
|
-
|
|
3617
|
+
let ok = targets.iter().all(|(t, given)| {
|
|
3234
|
-
|
|
3618
|
+
given.iter().enumerate().any(|(i, a)| a.is_some_and(|a| a.id == x.id) && ro.contains(&(*t, i)))
|
|
3619
|
+
});
|
|
3620
|
+
if ok {
|
|
3235
|
-
|
|
3621
|
+
allowed.insert(x.id);
|
|
3236
|
-
}
|
|
3237
3622
|
}
|
|
3238
3623
|
}
|
|
3239
3624
|
}
|
|
3240
|
-
// `match self` reads its fields, unless an arm may take `self` apart to build
|
|
3241
|
-
// from it (a constructor of the matched variant in tail position, or a binder
|
|
3242
|
-
// handed on: then the method may want `self` unique).
|
|
3243
|
-
Node::S(Stmt { kind: StmtKind::Match(m), .. }) => {
|
|
3244
|
-
for (k, sub) in m.subjects.iter().enumerate() {
|
|
3245
|
-
if matches!(sub.kind, ExprKind::Self_) && m.cases.iter().all(|c| selfMatchReads(an, &ro, c, k)) {
|
|
3246
|
-
allowed.insert(sub.id);
|
|
3247
|
-
|
|
3625
|
+
}
|
|
3626
|
+
}
|
|
3627
|
+
Node::S(Stmt { kind: StmtKind::Assign(asg), .. }) => {
|
|
3628
|
+
for t in &asg.targets {
|
|
3629
|
+
match t {
|
|
3630
|
+
AssignTarget::Field(o, _) if isP(o) => {
|
|
3631
|
+
allowed.insert(o.id);
|
|
3248
3632
|
}
|
|
3633
|
+
AssignTarget::Var(v) if v == name => rebound = true,
|
|
3634
|
+
_ => {}
|
|
3249
3635
|
}
|
|
3250
|
-
_ => {}
|
|
3251
3636
|
}
|
|
3252
|
-
true
|
|
3253
|
-
});
|
|
3254
|
-
if allSelf.iter().any(|id| !allowed.contains(id) || captured.contains(id)) {
|
|
3255
|
-
drop.push(g);
|
|
3256
3637
|
}
|
|
3638
|
+
// `match p` reads its fields, unless an arm may take `p` apart to build from it (a
|
|
3639
|
+
// constructor of the matched variant in tail position, or a binder handed on: then the
|
|
3640
|
+
// fn may want `p` unique).
|
|
3641
|
+
Node::S(Stmt { kind: StmtKind::Match(m), .. }) => {
|
|
3642
|
+
rebound |= m.cases.iter().any(|c| c.patterns.iter().any(|p| bindsP(p)));
|
|
3643
|
+
for (k, sub) in m.subjects.iter().enumerate() {
|
|
3644
|
+
if isP(sub) && m.cases.iter().all(|c| matchReads(c, k)) {
|
|
3645
|
+
allowed.insert(sub.id);
|
|
3646
|
+
}
|
|
3647
|
+
}
|
|
3648
|
+
}
|
|
3649
|
+
_ => {}
|
|
3257
3650
|
}
|
|
3258
|
-
if drop.is_empty() {
|
|
3259
|
-
|
|
3651
|
+
true
|
|
3260
|
-
|
|
3652
|
+
});
|
|
3261
|
-
for g in drop {
|
|
3262
|
-
|
|
3653
|
+
!rebound && all.iter().all(|id| allowed.contains(id) && !captured.contains(id))
|
|
3263
|
-
}
|
|
3264
|
-
}
|
|
3265
3654
|
}
|
|
3266
3655
|
|
|
3267
3656
|
/// Every field a pattern binds (at any depth) may now be held by its binder as well.
|
|
@@ -3541,6 +3930,12 @@ fn collectFacts(an: &mut An) {
|
|
|
3541
3930
|
}
|
|
3542
3931
|
if let AttrKind::Field(f) = &x.attr {
|
|
3543
3932
|
reads.push((nodeKey(e.id), a.fieldKeys(ui, &x.object, f)));
|
|
3933
|
+
// `g().f` of a fresh value (a constructor, a call that always returns a fresh
|
|
3934
|
+
// one): nothing else holds the object, which dies here, so the read takes
|
|
3935
|
+
// the field over (`self.advance(dt).state`).
|
|
3936
|
+
if a.fresh(&x.object) {
|
|
3937
|
+
allowed.insert(nodeKey(e.id));
|
|
3938
|
+
}
|
|
3544
3939
|
// `T.f` without a call is the static `f` as a value: its callers are
|
|
3545
3940
|
// unknown, as a free fn's are when it is named as a value.
|
|
3546
3941
|
if let ExprKind::TypeName(t) = &x.object.kind {
|
|
@@ -3977,7 +4372,7 @@ fn versionPlan(an: &An) -> Vec<(usize, Vec<(usize, NodeId)>)> {
|
|
|
3977
4372
|
|
|
3978
4373
|
/// Makes the unique versions that pay off, and returns the notes for `--explain-fusion`, and the
|
|
3979
4374
|
/// solved analysis of the program it leaves, when it has one.
|
|
3980
|
-
fn versionCallers(src: &mut Source) -> (Vec<String>, Option<An>) {
|
|
4375
|
+
fn versionCallers(src: &mut Source, distrust: &mut HashSet<String>) -> (Vec<String>, Option<An>) {
|
|
3981
4376
|
let nFns = src.items.iter().filter(|i| matches!(i, Item::Fn(_))).count();
|
|
3982
4377
|
let budget = (nFns / 8).max(16);
|
|
3983
4378
|
let mut made: HashMap<String, String> = HashMap::new();
|
|
@@ -3985,8 +4380,7 @@ fn versionCallers(src: &mut Source) -> (Vec<String>, Option<An>) {
|
|
|
3985
4380
|
let mut cut = false;
|
|
3986
4381
|
let mut last: Option<An> = None;
|
|
3987
4382
|
for round in 0..VERSION_ROUNDS {
|
|
3988
|
-
let an =
|
|
4383
|
+
let an = analyse(src, distrust);
|
|
3989
|
-
solve(&an);
|
|
3990
4384
|
let plan = versionPlan(&an);
|
|
3991
4385
|
if plan.is_empty() {
|
|
3992
4386
|
last = Some(an);
|
|
@@ -4050,8 +4444,7 @@ fn versionCallers(src: &mut Source) -> (Vec<String>, Option<An>) {
|
|
|
4050
4444
|
}
|
|
4051
4445
|
// Keep a version only when its code proves more spreads than the original's, or it hands
|
|
4052
4446
|
// values to a kept version.
|
|
4053
|
-
let an =
|
|
4447
|
+
let an = analyse(src, distrust);
|
|
4054
|
-
solve(&an);
|
|
4055
4448
|
let byKey: HashMap<String, usize> = an.units.iter().enumerate().filter(|(_, u)| u.kind == Kind::Fn).map(|(i, u)| (unitKey(u), i)).collect();
|
|
4056
4449
|
let mut keep: HashSet<usize> = HashSet::new();
|
|
4057
4450
|
let mut pairs = vec![];
|
compiler/core/tests/core/main.rs
CHANGED
|
@@ -28,6 +28,7 @@ mod tests_lower_test;
|
|
|
28
28
|
mod traits_parse_test;
|
|
29
29
|
mod trmc_test;
|
|
30
30
|
mod enum_checks_test;
|
|
31
|
+
mod uniqueness_fold_test;
|
|
31
32
|
mod uniqueness_moves_test;
|
|
32
33
|
mod uniqueness_reuse_test;
|
|
33
34
|
mod uniqueness_test;
|
compiler/core/tests/core/uniqueness_fold_test.rs
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
//! What std's delivery fold needs of the uniqueness proof to step a screen in place (std/game's
|
|
2
|
+
//! `Delivery`, `Next`, `Folded`): a value made unique once by `@copy` as it enters the fold, a
|
|
3
|
+
//! receiver that a read-only method reads through another fn, a field taken out of a fresh
|
|
4
|
+
//! value, a value stored beside reads of itself, and a local that stands for its value.
|
|
5
|
+
#![allow(non_snake_case)]
|
|
6
|
+
use plum_core::uniqueness::{markUnique, UniqueReport};
|
|
7
|
+
|
|
8
|
+
fn run(src: &str) -> UniqueReport {
|
|
9
|
+
let mut s = plum_test_support::parseRawSource(src);
|
|
10
|
+
markUnique(&mut s)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/// Whether the spread `label` (`Type.fn:line`) is proved; it must be one the report has.
|
|
14
|
+
fn proved(r: &UniqueReport, label: &str) -> bool {
|
|
15
|
+
assert!(r.proved.iter().any(|p| p == label) || r.unproved.iter().any(|(l, _)| l == label), "no spread {label}: {r:?}");
|
|
16
|
+
r.proved.iter().any(|p| p == label)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
fn reason<'a>(r: &'a UniqueReport, label: &str) -> &'a str {
|
|
20
|
+
r.unproved.iter().find(|(l, _)| l == label).map(|(_, m)| m.as_str()).unwrap_or("<none>")
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const PRE: &str = "struct Pt(x: Int, y: Int)\nstruct World(s: Pt, n: Int)\nstruct Next(state: Pt, n: Int)\n";
|
|
24
|
+
|
|
25
|
+
/// A shared value copied once: the copy is the callee's alone, so its spread is in place.
|
|
26
|
+
#[test]
|
|
27
|
+
fn aCopyOfASharedValueIsUnique() {
|
|
28
|
+
let r = run(&format!(
|
|
29
|
+
"{PRE}primitive Main =\n fun step(p: Pt) -> Pt = Pt(..p, x: 1)\n\n fun go(p: Pt) -> Pt = Main.step(@copy(p))\n\n fun keep(p: Pt) -> Pt =\n q := Main.go(p)\n p\n"
|
|
30
|
+
));
|
|
31
|
+
assert!(proved(&r, "Main.step:5"), "{r:?}");
|
|
32
|
+
let r = run(&format!(
|
|
33
|
+
"{PRE}primitive Main =\n fun step(p: Pt) -> Pt = Pt(..p, x: 1)\n\n fun go(p: Pt) -> Pt = Main.step(p)\n\n fun keep(p: Pt) -> Pt =\n q := Main.go(p)\n p\n"
|
|
34
|
+
));
|
|
35
|
+
assert!(!proved(&r, "Main.step:5"), "{r:?}");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/// The copy shares its fields with the original: a field of the copied type is shared from then
|
|
39
|
+
/// on, of the known type and, for a type parameter, of every implementer of its bound.
|
|
40
|
+
#[test]
|
|
41
|
+
fn aCopyMakesTheCopiedTypesFieldsShared() {
|
|
42
|
+
let tick = " fun step(p: Pt) -> Pt = Pt(..p, x: 1)\n\n fun tick(w: World) -> World =\n w.s = Main.step(w.s)\n w\n\n fun mk() -> World = World(s: Pt(x: 0, y: 0), n: 0)\n";
|
|
43
|
+
let r = run(&format!("{PRE}primitive Main =\n{tick}"));
|
|
44
|
+
assert!(proved(&r, "Main.step:5"), "{r:?}");
|
|
45
|
+
let r = run(&format!("{PRE}primitive Main =\n{tick}\n fun dup(w: World) -> World = @copy(w)\n"));
|
|
46
|
+
assert!(!proved(&r, "Main.step:5"), "{r:?}");
|
|
47
|
+
assert!(reason(&r, "Main.step:5").contains("field `s` may be shared"), "{}", reason(&r, "Main.step:5"));
|
|
48
|
+
let traits = "trait Tr =\n fun n(self) -> Int\nstruct A[Tr](s: Pt, k: Int) =\n fun n(self) -> Int = self.k\nstruct B(s: Pt, k: Int)\n";
|
|
49
|
+
let body = "primitive Main =\n fun step(p: Pt) -> Pt = Pt(..p, x: 1)\n\n fun tickA(a: A) -> A =\n a.s = Main.step(a.s)\n a\n\n fun mk() -> A = A(s: Pt(x: 0, y: 0), k: 0)\n";
|
|
50
|
+
let r = run(&format!("{PRE}{traits}{body}"));
|
|
51
|
+
assert!(proved(&r, "Main.step:10"), "{r:?}");
|
|
52
|
+
let r = run(&format!("{PRE}{traits}{body}\n fun dup<S: Tr>(x: S) -> S = @copy(x)\n"));
|
|
53
|
+
assert!(!proved(&r, "Main.step:10"), "{r:?}");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/// `x.look()` with `x` used after it: `look` hands `self` to a fn that only reads it, so
|
|
57
|
+
/// nothing keeps `x` and the spread after it is in place. One that keeps it blocks the spread.
|
|
58
|
+
#[test]
|
|
59
|
+
fn aReceiverReadThroughAnotherFnIsNotKept() {
|
|
60
|
+
let r = run(
|
|
61
|
+
"struct Pt(x: Int, y: Int) =\n fun look(self) -> Int = Main.peek(self)\n\
|
|
62
|
+
primitive Main =\n fun peek(p: Pt) -> Int = p.x\n\n fun go() -> Pt =\n t := Pt(x: 0, y: 0)\n n := t.look()\n Pt(..t, y: n)\n",
|
|
63
|
+
);
|
|
64
|
+
assert!(proved(&r, "Main.go:6"), "{r:?}");
|
|
65
|
+
let r = run(
|
|
66
|
+
"struct Pt(x: Int, y: Int) =\n fun look(self) -> Box = Main.keep(self)\nstruct Box(p: Pt)\n\
|
|
67
|
+
primitive Main =\n fun keep(p: Pt) -> Box = Box(p: p)\n\n fun go() -> Pt =\n t := Pt(x: 0, y: 0)\n b := t.look()\n Pt(..t, y: b.p.x)\n",
|
|
68
|
+
);
|
|
69
|
+
assert!(!proved(&r, "Main.go:7"), "{r:?}");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/// `Main.wrap(t).state`: the field of a fresh value, which nothing else holds, is the reader's
|
|
73
|
+
/// alone while the field is unique; stored beside a read of itself (`n: p.x`), `p` is still
|
|
74
|
+
/// moved in. Once the field is written with a shared value anywhere, the read is no longer fresh.
|
|
75
|
+
#[test]
|
|
76
|
+
fn aFieldOfAFreshValueIsUniqueWhileTheFieldIs() {
|
|
77
|
+
let base = "primitive Main =\n fun wrap(p: Pt) -> Next = Next(state: p, n: p.x)\n\n fun step(p: Pt) -> Pt = Pt(..p, x: 1)\n\n fun go() -> Pt =\n t := Pt(x: 0, y: 0)\n Main.step(Main.wrap(t).state)\n";
|
|
78
|
+
let r = run(&format!("{PRE}{base}"));
|
|
79
|
+
assert!(proved(&r, "Main.step:7"), "{r:?}");
|
|
80
|
+
let r = run(&format!("{PRE}{base}\n fun leak(w: World) -> Next = Main.wrap(w.s)\n"));
|
|
81
|
+
assert!(!proved(&r, "Main.step:7"), "{r:?}");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/// A fn whose result is a local bound once and used once returns what that local's value
|
|
85
|
+
/// returns: here a fresh value, through a fn that passes its parameter back.
|
|
86
|
+
#[test]
|
|
87
|
+
fn aLocalUsedOnceStandsForItsValue() {
|
|
88
|
+
let fns = " fun id(p: Pt) -> Pt = p\n\n fun step(p: Pt) -> Pt = Pt(..p, x: 1)\n\n fun go(n: Int) -> Pt = Main.step(Main.mk(n))\n";
|
|
89
|
+
let r = run(&format!("{PRE}primitive Main =\n{fns}\n fun mk(n: Int) -> Pt =\n p := Pt(x: n, y: 0)\n Main.id(p)\n"));
|
|
90
|
+
assert!(proved(&r, "Main.step:7"), "{r:?}");
|
|
91
|
+
let r = run(&format!(
|
|
92
|
+
"{PRE}primitive Main =\n{fns}\n fun mk(n: Int) -> Pt =\n p := Pt(x: n, y: 0)\n w := World(s: p, n: 1)\n Main.id(p)\n"
|
|
93
|
+
));
|
|
94
|
+
assert!(!proved(&r, "Main.step:7"), "{r:?}");
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/// A body the compiler supplies (`@native`) shows no uses of its parameters, and may keep them
|
|
98
|
+
/// (`Slice.push`): handing a value to one is never a read, so the spread after it copies.
|
|
99
|
+
#[test]
|
|
100
|
+
fn aNativeBodyMayKeepWhatItIsGiven() {
|
|
101
|
+
let r = run("struct Pt(x: Int, y: Int)\nprimitive Main =\n fun keep(p: Pt) = @native\n\n fun go() -> Pt =\n t := Pt(x: 0, y: 0)\n Main.keep(t)\n Pt(..t, y: 1)\n");
|
|
102
|
+
assert!(!proved(&r, "Main.go:5"), "{r:?}");
|
|
103
|
+
}
|
compiler/driver/tests/driver_tests.rs
CHANGED
|
@@ -231,11 +231,13 @@ const FRESH_ACTOR: &str = "Stress(label: \"s\", t: 0, n: 0)";
|
|
|
231
231
|
const SPREAD_T: &str = "Stress(..self, t: self.t + 1)";
|
|
232
232
|
const DRAW_N: &str = "io.printLn(\"{self.n}\")";
|
|
233
233
|
|
|
234
|
-
/// The game holds the constant itself:
|
|
234
|
+
/// The game holds the constant itself: std's fold steps a copy of the screen (`@copy` in
|
|
235
|
+
/// `Delivery.deliverTo`), so the reduction is written in place into that copy and never into
|
|
236
|
+
/// `Stress.Start`.
|
|
235
237
|
#[test]
|
|
236
238
|
fn gameStartingFromAConstantActorCopies() {
|
|
237
239
|
let info = check(&gameSource("g_const", "Stress.Start", SPREAD_T, DRAW_N), &PassOptions::default()).expect("checks");
|
|
238
|
-
assert!(
|
|
240
|
+
assert!(spreadInPlace(&info, "Stress", "reduce"));
|
|
239
241
|
}
|
|
240
242
|
|
|
241
243
|
/// A reducer may hand the game the constant on any tick, and the next tick would write into it.
|
compiler/lsp/src/main.rs
CHANGED
|
@@ -1068,7 +1068,7 @@ mod tests {
|
|
|
1068
1068
|
}
|
|
1069
1069
|
|
|
1070
1070
|
/// Completion scanners get a char index: after "é😀" the client's column 6 is char 5.
|
|
1071
|
-
/// After `@` the built-ins are offered: `@typeName`, `@sameRef`, the eight `@mem..` and
|
|
1071
|
+
/// After `@` the built-ins are offered: `@typeName`, `@sameRef`, `@copy`, the eight `@mem..` and
|
|
1072
1072
|
/// `@native`, each replacing what was typed from the `@` on.
|
|
1073
1073
|
#[test]
|
|
1074
1074
|
fn builtinsAreOfferedAfterAt() {
|
|
@@ -1079,7 +1079,7 @@ mod tests {
|
|
|
1079
1079
|
let items = completion::builtinItems(line, 3, start, col);
|
|
1080
1080
|
let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
|
|
1081
1081
|
let want = [
|
|
1082
|
-
"@typeName", "@sameRef", "@memSize", "@memGrow", "@memStoreI32", "@memLoadI32", "@memStoreU8",
|
|
1082
|
+
"@typeName", "@sameRef", "@copy", "@memSize", "@memGrow", "@memStoreI32", "@memLoadI32", "@memStoreU8",
|
|
1083
1083
|
"@memLoadU8", "@memStoreF32", "@memLoadF32", "@native",
|
|
1084
1084
|
];
|
|
1085
1085
|
assert_eq!(labels.len(), want.len(), "{labels:?}");
|
compiler/wasm-codegen/src/emit.rs
CHANGED
|
@@ -30,6 +30,8 @@ impl<'a> Emit<'a> {
|
|
|
30
30
|
let body = if crate::intrinsics::isTypeNameFn(f) {
|
|
31
31
|
compileFnBody(&crate::intrinsics::typeNameBody(f, &u.subst), &ctx, state, &uref)
|
|
32
32
|
.map_err(|e| format!("{e} (in '{}')", u.name))?
|
|
33
|
+
} else if crate::intrinsics::isCopyFn(f) {
|
|
34
|
+
crate::intrinsics::compileCopyFnBody(&u.subst, &ctx.enum_variants)?
|
|
33
35
|
} else {
|
|
34
36
|
match compileIntrinsicFnBody(f, &u.subst) {
|
|
35
37
|
Some(body) => body,
|
compiler/wasm-codegen/src/intrinsics.rs
CHANGED
|
@@ -12,6 +12,8 @@ pub(crate) fn compileIntrinsicFnBody(f: &ast::Fn, subst: &Subst) -> Option<Vec<u
|
|
|
12
12
|
match plum_core::native::native(f)? {
|
|
13
13
|
Native::Mem => compileMemIntrinsicFnBody(f),
|
|
14
14
|
Native::SameRef => compileSameFnBody(subst),
|
|
15
|
+
// `emit::compileUnitBodies` compiles it with the struct's fields (`compileCopyFnBody`).
|
|
16
|
+
Native::Copy => None,
|
|
15
17
|
Native::Op(op) => Some(compileNativeFnBody(f, op)),
|
|
16
18
|
Native::Array => compileArrayIntrinsicFnBody(f, subst),
|
|
17
19
|
// `emit::compileUnitBodies` compiles its body as a string literal.
|
|
@@ -66,6 +68,50 @@ pub(crate) fn compileSameFnBody(subst: &Subst) -> Option<Vec<u8>> {
|
|
|
66
68
|
Some(body)
|
|
67
69
|
}
|
|
68
70
|
|
|
71
|
+
/// Whether `f` is `@copy<T>` (`plum_core::compile_builtins`).
|
|
72
|
+
pub(crate) fn isCopyFn(f: &ast::Fn) -> bool {
|
|
73
|
+
plum_core::native::native(f) == Some(plum_core::native::Native::Copy)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/// The body of `@copy<T>(x)` for one `T`: a flat struct is its leaves as they are (a value
|
|
77
|
+
/// has no identity, so that is a copy); a boxed struct is a new struct of its type with each
|
|
78
|
+
/// field read off `x` (its type tag first, when it has one). Any other `T` (an enum, a trait
|
|
79
|
+
/// object, a builtin) is an error: the checker lets a type parameter through, so this is
|
|
80
|
+
/// where an instantiation that is no struct is caught.
|
|
81
|
+
pub(crate) fn compileCopyFnBody(subst: &Subst, variants: &plum_checker::EnumVariants) -> Result<Vec<u8>, String> {
|
|
82
|
+
let t = subst.get("T").ok_or("codegen: @copy without its type")?;
|
|
83
|
+
let mut body = vec![0u8];
|
|
84
|
+
if valueFieldsOf(t).is_some() {
|
|
85
|
+
for local in 0..leafCount(t) {
|
|
86
|
+
Instruction::LocalGet(local).encode(&mut body);
|
|
87
|
+
}
|
|
88
|
+
Instruction::End.encode(&mut body);
|
|
89
|
+
return Ok(body);
|
|
90
|
+
}
|
|
91
|
+
let g = gcTypes();
|
|
92
|
+
let name = match t {
|
|
93
|
+
PlumType::TNamed(n) | PlumType::TApp(n, _) => n.as_str(),
|
|
94
|
+
_ => "",
|
|
95
|
+
};
|
|
96
|
+
let fields = variants.variantsOf(name).collect::<Vec<_>>();
|
|
97
|
+
let (Some(idx), [(v, info)]) = (g.classIdx(t), fields.as_slice()) else {
|
|
98
|
+
return Err(format!("@copy copies a struct, and {t} is not one"));
|
|
99
|
+
};
|
|
100
|
+
if *v != name || g.isTraitObject(t) {
|
|
101
|
+
return Err(format!("@copy copies a struct, and {t} is not one"));
|
|
102
|
+
}
|
|
103
|
+
let base = g.fieldBase(idx);
|
|
104
|
+
g.emitTag(idx, &mut body);
|
|
105
|
+
for i in 0..info.field_types.len() as u32 {
|
|
106
|
+
Instruction::LocalGet(0).encode(&mut body);
|
|
107
|
+
Instruction::RefCastNonNull(HeapType::Concrete(idx)).encode(&mut body);
|
|
108
|
+
Instruction::StructGet { struct_type_index: idx, field_index: base + i }.encode(&mut body);
|
|
109
|
+
}
|
|
110
|
+
Instruction::StructNew(idx).encode(&mut body);
|
|
111
|
+
Instruction::End.encode(&mut body);
|
|
112
|
+
Ok(body)
|
|
113
|
+
}
|
|
114
|
+
|
|
69
115
|
/// After a value of wasm type `vt` is pushed: makes it an `eqref` for `ref.eq`. A concrete
|
|
70
116
|
/// heap type already is one; an `anyref` (a trait object, a closure) is cast.
|
|
71
117
|
pub(crate) fn castToEq(vt: &ValType, body: &mut Vec<u8>) {
|
docs/backlog.md
CHANGED
|
@@ -8,7 +8,7 @@ The retained scene tree was replaced by master's screen view in functional form:
|
|
|
8
8
|
|
|
9
9
|
- **A `match` on a nullary variant inside a closure in a function body matches every value.** `xs.fold(0, |s, e| match e` with an arm `B => s + 1` counts every element; the same match in a named function, or in a closure in a test, is right, and a variant with fields (`A(n) =>`) is right. std/game works around it (the matches are in methods: `Game.travelled`, `Game.redone`). Repro: `fun count(xs: List<E>) -> Int = xs.fold(0, |s, e| match e` / `B => s + 1` / `_ => s)` with `enum E = A(n: Int) | B | C`, `count([C])` gives 1.
|
|
10
10
|
- **Pass re-check failures met on the way** (fixed in std, not in the compiler): fusion devirtualising `s.frames().onDemand()` on a `Screen` with one implementer mistypes the fused call (std matches on `frames()` instead); dead-code removal is reverted when it removes every type a downcast to a trait could match (it met `Container as c`, which master has since folded into `view` too).
|
|
11
|
-
- **
|
|
11
|
+
- **What std's delivery fold still copies** (the screen is in place since 2026-11-16, `@copy` in `Delivery.deliverTo`: Orbit Runner's `PlayingScreen.reduce` 3, `newMine`, `at` and the derived `stepped`; timings unchanged, orbit update 11.3 ms and paint 129.0 ms, checksum 946756219): Orbit Runner's `StartOver` spread (its field values are written out of declaration order and `best` reads `score`, which comes first); Balloon Pop's `reduce` and its helpers, whose `act` reads `self.clock` and `self.assets` after handing `self` to `reduce` (`Next(state: self.reduce(a), then: [Popped(at: self.clock)])`), so `self` is still live there; an orb's and a mine's `step` (R3: one spread of `self`, the head of the list it is stepped in, `List.head`, which std's read-only walks `List.all`, `filter` and `next` hand to closures and results, and `Ticker.input` binds out of a field read; the screen's `mines` and `orbs` are also handed to the view's upcasts). The proof the fold needed: read-only parameters through calls (`readOnlyParams`: a screen's `view` hands `self` to the fused copies of its closures), a field taken out of a fresh value (`self.advance(dt).state`, rechecked by `analyse` when the field turns out shared), a value stored beside reads of itself (`Next(state: self, then: [if self.over ..])`), a local used once standing for its value in `passes`. The cost: the in-place pass takes about 2.5 times as long (debug, Orbit Runner 183 to 480 ms): 9 version rounds where there were 5, each about 30% dearer.
|
|
12
12
|
- **A program with no `Sized` or `Touch` view drops the dead code pass**: std's `Views.touchOf`, `sizedHit` and `missesArea` match `Touch as t` and `Sized as s` on a `View`, and once the pass has dropped every type that is one, the re-check calls each match impossible ("no type is both a View and a Touch"). Every game has such a view, so only a minimal test program meets it. A trait default's copy is told apart since 2026-11-16 (`defaultPositions` reads the trait's declarations), but these are statics.
|
|
13
13
|
- **Master's other games** (`clockwork`, `menu`) are not ported.
|
|
14
14
|
- **The view's cost**: each frame makes the view's list and items. `benchmarks/screen_views` (`orbit.plum`, `scale.plum`, master's drivers) times it; not yet run against master. Master's stepping walk makes the view once more a tick and each actor's view; this branch's `stepped` makes neither, so the two `update` timings are not the same work (`scale.plum`'s header says so).
|
docs/game.md
CHANGED
|
@@ -365,7 +365,7 @@ A screen with rules is a `ScreenSlice<A>` (`std/game/ScreenSlice`), as in Redux
|
|
|
365
365
|
| `held(self, h: Held) -> Option<A>` | None | the action for what is held after the tick's events, every tick |
|
|
366
366
|
| `tick(self, dt) -> Option<A>` | None | the tick action |
|
|
367
367
|
|
|
368
|
-
**What follows from an action** is a value `act` returns, `Next<S, A>(state: S, then: List<A> = Nil, cmds: List<Cmd> = Nil)`: a screen with nothing more to say writes `reduce` alone, and one that has writes `act` (and keeps `reduce` for the plain state changes, or not). Each action std delivers is acted on as it is made, and then each action of its `then`, in order, each with its own `then` first; so the next mapping and the next action see what they did. Orbit Runner's rules return what happened as actions (`then: [if caught.points > 0 then Scored(points: caught.points), if hit then Hit]`), and `PlayAgain` on the game over panel is followed by `StartOver` at once (`then: [if self.over then StartOver]`). The delivery is a fold over the slice (`Delivery.deliverTo`, which keeps the actions and the commands in a value, `Trail`), and the kit's `dispatch` runs the same fold (`Delivery.dispatchTo`). A test calls `reduce` or `act` itself: `s.act(Keyed).then`. An action enum that lists `Show` (std/Str) has its `toStr` derived, so a test can compare the actions sent as text (`"Steer(1.0, -1.0) Tick(0.016) Scored(10)"`). How a game of screens with actions of different types is typed: `Screen` has `deliver`, and `ScreenSlice<A>` gives it a default of its own that delivers the tick as `A`s ([language.md](language.md#inheritance)).
|
|
368
|
+
**What follows from an action** is a value `act` returns, `Next<S, A>(state: S, then: List<A> = Nil, cmds: List<Cmd> = Nil)`: a screen with nothing more to say writes `reduce` alone, and one that has writes `act` (and keeps `reduce` for the plain state changes, or not). Each action std delivers is acted on as it is made, and then each action of its `then`, in order, each with its own `then` first; so the next mapping and the next action see what they did. Orbit Runner's rules return what happened as actions (`then: [if caught.points > 0 then Scored(points: caught.points), if hit then Hit]`), and `PlayAgain` on the game over panel is followed by `StartOver` at once (`then: [if self.over then StartOver]`). The delivery is a fold over the slice (`Delivery.deliverTo`, which keeps the actions and the commands in a value, `Trail`), and the kit's `dispatch` runs the same fold (`Delivery.dispatchTo`). The game keeps the screen it had (its screens, and the ones a rewind starts from), so the fold starts from a copy of it (`@copy`, one a tick delivered, [language.md](language.md#copies)): the copy is the fold's alone, and each `reduce` of the tick updates it in place, Orbit Runner's steering, scoring and hits among them. A test calls `reduce` or `act` itself: `s.act(Keyed).then`. An action enum that lists `Show` (std/Str) has its `toStr` derived, so a test can compare the actions sent as text (`"Steer(1.0, -1.0) Tick(0.016) Scored(10)"`). How a game of screens with actions of different types is typed: `Screen` has `deliver`, and `ScreenSlice<A>` gives it a default of its own that delivers the tick as `A`s ([language.md](language.md#inheritance)).
|
|
369
369
|
|
|
370
370
|
## Input and the tick as actions
|
|
371
371
|
|
docs/language.md
CHANGED
|
@@ -906,6 +906,7 @@ primitive Demo[App] =
|
|
|
906
906
|
|---|---|
|
|
907
907
|
| `@typeName(T)` | the name of the type `T` as a `Str`, without type arguments: `@typeName(Button<Msg>)` is `"Button"`. The compiler evaluates it while it compiles. With a generic `T` it is the type of each instantiation, and `@typeName(Self)` in a trait's default is each implementer's own name (see [Statics](#statics)). |
|
|
908
908
|
| `@sameRef(a, b)` | whether `a` and `b` are the very same object, not just equal ones, as a `Bool`. See [Reference identity](#reference-identity). |
|
|
909
|
+
| `@copy(x)` | a shallow copy of the struct `x`: another object with the same field values. See [Copies](#copies). |
|
|
909
910
|
| `@memSize()` | the size of the program's linear memory in bytes, as an `Int`. See [Linear memory](#linear-memory). |
|
|
910
911
|
| `@memGrow(pages)` | adds `pages` 64 KiB pages to the memory; gives the old page count, or -1 when it can't grow. |
|
|
911
912
|
| `@memStoreI32(addr, v)` | stores the low 32 bits of the `Int` `v` at byte `addr`. |
|
|
@@ -931,6 +932,17 @@ Both arguments have the same type, and it must be a type whose values live on th
|
|
|
931
932
|
|
|
932
933
|
In-place updates never fool it: the compiler never updates a variable passed to `@sameRef` in place, so a method that changes a field of it always returns another object.
|
|
933
934
|
|
|
935
|
+
### Copies
|
|
936
|
+
|
|
937
|
+
```plum
|
|
938
|
+
b := @copy(a) # Box(..a): equal to `a`, and another object
|
|
939
|
+
@sameRef(a.items, b.items) # true: the fields are not copied
|
|
940
|
+
```
|
|
941
|
+
|
|
942
|
+
`@copy(x)` makes a new object of `x`'s struct with the same field values, as `T(..x)` does when `x` is a `T`; it also takes a type parameter (`fun f<S: Screen>(s: S) -> S = @copy(s)`), where no spread can name the type. Its argument must be a struct: an enum, a trait object, a function or a scalar is an error, and so is a generic instantiated with one (found when that instantiation is compiled). A flat struct is a value, and its copy is that value.
|
|
943
|
+
|
|
944
|
+
A copy is what a value that others hold needs before a run of in-place updates: no one else holds the copy, so the updates after it are written in place, where updates of the shared value would each copy. std's game loop copies the screen once as a tick's delivery starts (the game keeps the screen it had), and each action of the tick then updates the copy in place. The fields are shared with `x`, so the compiler takes every field of the copied type (of every type a type parameter's bound allows) as shared from then on.
|
|
945
|
+
|
|
934
946
|
### Linear memory
|
|
935
947
|
|
|
936
948
|
The `@mem` built-ins read and write the program's linear memory: one growable wasm memory, 16 pages of 64 KiB to start, exported to the host as `memory`. It exists only in a program that uses one of them. Addresses are byte offsets from 0; every access is little-endian and stops the program when it is out of bounds.
|
docs/std.md
CHANGED
|
@@ -16,7 +16,7 @@ The [game engine](game.md) has its own page.
|
|
|
16
16
|
| [`Json`](#json) | reading and writing JSON |
|
|
17
17
|
| [`Decimal`](#decimal) | exact decimal numbers, to and from `Float` |
|
|
18
18
|
| [`Os`, `Http`](#files-and-network) | files and the network |
|
|
19
|
-
| [`Time`, `Random`, `Uuid`, `Base64`, `Aabb`, `@sameRef`](#utilities) | utilities |
|
|
19
|
+
| [`Time`, `Random`, `Uuid`, `Base64`, `Aabb`, `@sameRef`, `@copy`](#utilities) | utilities |
|
|
20
20
|
| [`Test`](#testing) | helpers for tests |
|
|
21
21
|
| [`game/Screen`, `game/ScreenSlice`](#game-screens-and-slices) | a game's screens, each with its own state, actions and reducer |
|
|
22
22
|
|
|
@@ -262,6 +262,7 @@ primitive Demo[App] =
|
|
|
262
262
|
- **`Base64`** (`import std/encoding/Base64`): `Base64.encode(data)` and `Base64.decode(text)` (a `Result`; whitespace and missing padding are fine, data after padding and a last group of one character are `Err(InvalidBase64)`), the URL alphabet `Base64.encodeUrl(data)` (no padding unless `pad` is true) and `Base64.decodeUrl(text)`, and the line-wrapped `Base64.encodePem` and `Base64.encodeMime`
|
|
263
263
|
- **`Aabb`:** an axis-aligned box, corners included: `Aabb.of(x, y, w, h)`, `width`, `height`, `center`, `overlaps`, `contains`, `containsPoint`, `union`, `distSq`, `rayEntry`
|
|
264
264
|
- **Reference identity:** the built-in `@sameRef(a, b)` is true when `a` and `b` are the very same object, not just equal ones (see [Built-ins](language.md#built-ins)); there is nothing to import. A persistent structure uses it to keep what didn't change, and a test can use it to tell which of the actors a screen holds a press landed on (a game's pressable items say what a press means instead, `Presses<A>`; see [the game engine](game.md))
|
|
265
|
+
- **Copies:** the built-in `@copy(x)` is a shallow copy of a struct, another object with the same field values (see [Copies](language.md#copies)). std's game loop copies the screen once a tick so that the tick's actions update it in place (`Delivery.deliverTo`).
|
|
265
266
|
- **Linear memory:** the built-ins `@memSize`, `@memGrow`, `@memStoreI32`, `@memLoadI32`, `@memStoreU8`, `@memLoadU8`, `@memStoreF32` and `@memLoadF32` read and write the program's wasm memory (see [Built-ins](language.md#linear-memory))
|
|
266
267
|
- **`io.args()`:** the program's arguments as a `Slice<Str>`: what follows `--` in `plum run app.plum -- a b`, or a built executable's own arguments (empty under `plum test` and in the browser)
|
|
267
268
|
- **`io.nowMicros()`:** a wall clock in microseconds since the Unix epoch, as a `Float`, on every host
|
examples/games/orbitrunner/screens/PlayingScreen.plum
CHANGED
|
@@ -108,8 +108,8 @@ struct PlayingScreen[ScreenSlice<PlayAction>, Steps](
|
|
|
108
108
|
ring := Ring.at(self.ship.at.x + Sheet.Size / 2.0, self.ship.at.y + Sheet.Size / 2.0)
|
|
109
109
|
ended := lives <= 0
|
|
110
110
|
PlayingScreen(
|
|
111
|
-
..self, lives: lives, rings: self.rings.append([ring]), over: self.over || ended, ship: self.ship.hurtFor(Ship.HurtTime),
|
|
112
|
-
best: if ended then self.best.max(self.score) else self.best
|
|
111
|
+
..self, best: if ended then self.best.max(self.score) else self.best, lives: lives, over: self.over || ended,
|
|
112
|
+
ship: self.ship.hurtFor(Ship.HurtTime), rings: self.rings.append([ring]))
|
|
113
113
|
StartOver =>
|
|
114
114
|
PlayingScreen(..self, best: self.best.max(self.score), score: 0, lives: PlayingScreen.StartLives, over: false).deal()
|
|
115
115
|
|
std/game/ScreenSlice.plum
CHANGED
|
@@ -144,10 +144,12 @@ struct Delivery(input: Input, dt: Float, before: Held, camera: Viewport, pixels:
|
|
|
144
144
|
fun stepScreen<S: Screen>(self, s: S) -> S = if s.steps() then s.stepped(self.dt) else s
|
|
145
145
|
|
|
146
146
|
# One tick of the slice `s`, as `deliver` describes: a fold of its events, its `held`
|
|
147
|
-
# and its `tick` over the slice.
|
|
147
|
+
# and its `tick` over the slice. The game keeps `s` (its screens, and the ones a rewind
|
|
148
|
+
# starts from), so the fold steps a copy of it (`@copy`, one per tick delivered): the
|
|
149
|
+
# copy is the fold's alone, and each step may update it in place.
|
|
148
150
|
fun deliverTo<A, S: ScreenSlice<A>>(s: S, d: Delivery) -> Delivered =
|
|
149
151
|
none: Trail<A> := Trail()
|
|
150
|
-
afterEvents := d.eventsInto<A, S>(s, none, d.input.events)
|
|
152
|
+
afterEvents := d.eventsInto<A, S>(@copy(s), none, d.input.events)
|
|
151
153
|
match afterEvents
|
|
152
154
|
Folded(cur, trail) => d.heldInto<A, S>(cur, trail)
|
|
153
155
|
|
|
@@ -205,7 +207,7 @@ struct Delivery(input: Input, dt: Float, before: Held, camera: Viewport, pixels:
|
|
|
205
207
|
# std/game/TestRig's `dispatch` runs.
|
|
206
208
|
fun dispatchTo<A, S: ScreenSlice<A>>(s: S, a: A) -> Delivered =
|
|
207
209
|
none: Trail<A> := Trail()
|
|
208
|
-
Delivery.done<A, S>(Delivery.actIn<A, S>(s, none, a))
|
|
210
|
+
Delivery.done<A, S>(Delivery.actIn<A, S>(@copy(s), none, a))
|
|
209
211
|
|
|
210
212
|
# The slice `s` with `a` stepped into it, and then each action of its `then`.
|
|
211
213
|
fun actIn<A, S: ScreenSlice<A>>(s: S, trail: Trail<A>, a: A) -> Folded<S, A> =
|
tests/core/copy.plum
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Float
|
|
3
|
+
import std/Str
|
|
4
|
+
import std/Bool
|
|
5
|
+
import std/math/Vec2
|
|
6
|
+
import std/Test
|
|
7
|
+
|
|
8
|
+
# `@copy(x)`: a shallow copy of a struct, another object with the same field values. The
|
|
9
|
+
# sweep runs this file with the default, `--no-fbip` and `--no-fusion`: an in-place update
|
|
10
|
+
# of the copy must never show in the original.
|
|
11
|
+
|
|
12
|
+
struct Inner(n: Int, tag: Str)
|
|
13
|
+
|
|
14
|
+
struct Cell(label: Str, n: Int, inner: Inner) =
|
|
15
|
+
fun bumped(self) -> Cell = Cell(..self, n: self.n + 1)
|
|
16
|
+
|
|
17
|
+
trait Counted =
|
|
18
|
+
fun count(self) -> Int
|
|
19
|
+
fun bumped(self) -> Self
|
|
20
|
+
|
|
21
|
+
struct Tally[Counted](n: Int, label: Str) =
|
|
22
|
+
fun count(self) -> Int = self.n
|
|
23
|
+
fun bumped(self) -> Tally = Tally(..self, n: self.n + 1)
|
|
24
|
+
|
|
25
|
+
primitive Copies =
|
|
26
|
+
fun fresh() -> Cell = Cell(label: "a", n: 1, inner: Inner(n: 7, tag: "i"))
|
|
27
|
+
|
|
28
|
+
# `c` copied, and the copy stepped as a fold steps it: in place when it may be.
|
|
29
|
+
fun steppedCopy(c: Cell, k: Int) -> Cell = Copies.stepAll(@copy(c), k)
|
|
30
|
+
|
|
31
|
+
fun stepAll(c: Cell, k: Int) -> Cell = if k == 0 then c else Copies.stepAll(c.bumped(), k - 1)
|
|
32
|
+
|
|
33
|
+
# A generic copy: each instantiation copies its own struct.
|
|
34
|
+
fun bumpedCopy<S: Counted>(s: S) -> S = @copy(s).bumped()
|
|
35
|
+
|
|
36
|
+
primitive CopyTest[UnitTest] =
|
|
37
|
+
# a copy is equal field by field and is another object; its fields are the same objects
|
|
38
|
+
fun aCopyIsAnotherObjectWithTheSameFields() =
|
|
39
|
+
a := Copies.fresh()
|
|
40
|
+
b := @copy(a)
|
|
41
|
+
assert !@sameRef(a, b)
|
|
42
|
+
assert b.label == "a" && b.n == 1
|
|
43
|
+
assert @sameRef(a.inner, b.inner)
|
|
44
|
+
assert @sameRef(a.label, b.label)
|
|
45
|
+
|
|
46
|
+
# the copy stepped (in place, with fbip) leaves the original as it was
|
|
47
|
+
fun steppingTheCopyLeavesTheOriginal() =
|
|
48
|
+
a := Copies.fresh()
|
|
49
|
+
b := Copies.steppedCopy(a, 3)
|
|
50
|
+
assert b.n == 4
|
|
51
|
+
assert a.n == 1
|
|
52
|
+
c := Copies.steppedCopy(a, 0)
|
|
53
|
+
assert c.n == 1 && !@sameRef(a, c)
|
|
54
|
+
|
|
55
|
+
# a generic copy over a trait's implementer
|
|
56
|
+
fun aGenericCopyCopiesTheInstantiation() =
|
|
57
|
+
t := Tally(n: 2, label: "t")
|
|
58
|
+
u := Copies.bumpedCopy(t)
|
|
59
|
+
assert u.count() == 3
|
|
60
|
+
assert t.count() == 2
|
|
61
|
+
|
|
62
|
+
# a flat struct is a value: its copy is equal
|
|
63
|
+
fun aFlatStructCopiesItsValue() =
|
|
64
|
+
v := Vec2(x: 1.0, y: 2.0)
|
|
65
|
+
w := @copy(v)
|
|
66
|
+
assert w.x == 1.0 && w.y == 2.0
|
|
67
|
+
|
|
68
|
+
# a `Str` is a struct too
|
|
69
|
+
fun aStrCopyIsEqual() =
|
|
70
|
+
s := "plum"
|
|
71
|
+
t := @copy(s)
|
|
72
|
+
assert t == s
|