plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
a6cfb1c
— Peter John
2026-11-07T09:53:56+05:30
Simpler language: compile a second version for unique callers, and proof fixes
- AGENTS.md +5 -9
- compiler/core/src/uniqueness.rs +566 -24
- compiler/core/tests/core/main.rs +1 -0
- compiler/core/tests/core/uniqueness_test.rs +4 -1
- compiler/core/tests/core/uniqueness_versions_test.rs +205 -0
- compiler/driver/src/lib.rs +4 -0
- compiler/game/tests/fixtures/state_draw_keeps.plum +23 -0
- compiler/game/tests/fixtures/state_main_alias.plum +21 -0
- compiler/game/tests/host_test.rs +12 -0
- compiler/wasm-codegen/src/module.rs +2 -1
- compiler/wasm-codegen/tests/wasm_codegen/e2e_mem/unique_inplace.rs +2 -1
- compiler/wasm-codegen/tests/wasm_codegen/e2e_mem/unique_spread.rs +2 -1
- tests/fbip/fuzz/gen.pl +61 -1
- tests/fbip/versions.plum +134 -0
AGENTS.md
CHANGED
|
@@ -8,16 +8,12 @@ Do not use git worktrees or feature branches. Work directly on `master` in the m
|
|
|
8
8
|
|
|
9
9
|
Run `compiler/scripts/test-all.sh`. It builds, runs every test executable (not just the Plum sweep, even when only `.plum` files changed), then runs `target/debug/plum test std examples tests` with the default, `--no-fbip` and `--no-fusion`, and ends with `ALL PASSED` or `FAILED: <n>`. A change to `std` can break Rust tests that the sweep never runs.
|
|
10
10
|
|
|
11
|
-
##
|
|
12
|
-
|
|
13
|
-
When orchestrating subagents (superlite runs or otherwise), don't keep reusing one long-lived agent across tasks or runs. Before sending an agent another task, check its accumulated context: once it approaches 75% of its context window (about 150k tokens of 200k), give the next task to a fresh agent instead (superlite: let `dispatch` pick, or spawn a fresh implementer with the prime). An agent kept alive by repeated compaction forgets what it read and works slower.
|
|
11
|
+
## Models
|
|
14
12
|
|
|
15
|
-
|
|
13
|
+
Use Opus for all work on this repo: implementing, reviewing and fixing, because it catches more bugs. This includes superlite runs: pass `model: opus` on every superlite agent (`superlite:implementer`, `superlite:package-reviewer`, the fixers), overriding its tiers and its "never pass model" rule. Don't use Sonnet or Haiku tiers here.
|
|
16
14
|
|
|
17
|
-
|
|
15
|
+
## Subagents
|
|
18
16
|
|
|
19
|
-
``
|
|
20
|
-
cargo clean-all -y
|
|
21
|
-
```
|
|
17
|
+
When orchestrating subagents (superlite runs or otherwise), don't keep reusing one long-lived agent across tasks or runs. Before sending an agent another task, check its accumulated context: once it approaches 75% of its context window (about 150k tokens of 200k), give the next task to a fresh agent instead (superlite: let `dispatch` pick, or spawn a fresh implementer with the prime). An agent kept alive by repeated compaction forgets what it read and works slower.
|
|
22
18
|
|
|
23
|
-
|
|
19
|
+
Never stop or cancel an agent because it hit a context limit, and don't tell agents to stop near one: let it finish the task it has. The limit above only decides who gets the next task.
|
compiler/core/src/uniqueness.rs
CHANGED
|
@@ -20,8 +20,9 @@
|
|
|
20
20
|
//! then counts as fresh to a caller only when the argument handed in for that parameter is
|
|
21
21
|
//! itself fresh, or is the very variable the result is assigned back to (`v = g(v)`), and
|
|
22
22
|
//! the parameter is unique and never stored inside the callee. A callee reached with one
|
|
23
|
-
//! unique and one shared argument is not unique
|
|
23
|
+
//! unique and one shared argument is not unique itself, but `versionCallers` gives the unique
|
|
24
|
+
//! calls their own copy, `f$unique`, when that copy proves more spreads; `--explain-fusion`
|
|
24
|
-
//!
|
|
25
|
+
//! names both and says which call blocked the original.
|
|
25
26
|
//!
|
|
26
27
|
//! * A method whose `self` is only read (`ro`: field reads, field writes, calls of other `ro`
|
|
27
28
|
//! methods; never returned, stored, passed on or captured) does not block a receiver. What
|
|
@@ -31,7 +32,10 @@
|
|
|
31
32
|
//! operators) are never proved: their callers are unknown.
|
|
32
33
|
//!
|
|
33
34
|
//! Parameters and fields are solved as a greatest fixpoint (assume unique, remove what
|
|
35
|
+
//! fails, repeat). Code the program cannot reach from its entry points takes no part (`liveUnits`).
|
|
34
|
-
//!
|
|
36
|
+
//!
|
|
37
|
+
//! The invariant: when a spread writes in place, the variable holds the only reference to the
|
|
38
|
+
//! object anything can still read, and what the values do cannot tell that from a copy.
|
|
35
39
|
use crate::ast::*;
|
|
36
40
|
use crate::rename::renameStmts;
|
|
37
41
|
use std::cell::RefCell;
|
|
@@ -43,6 +47,8 @@ pub struct UniqueReport {
|
|
|
43
47
|
pub unproved: Vec<(String, String)>,
|
|
44
48
|
/// A verdict per spread inside a `fip fun` (empty when there is none).
|
|
45
49
|
pub fipSites: Vec<SiteVerdict>,
|
|
50
|
+
/// The unique versions kept (`f$unique`), and why any were not made.
|
|
51
|
+
pub versions: Vec<String>,
|
|
46
52
|
}
|
|
47
53
|
|
|
48
54
|
/// One spread of a `fip fun`, and whether it was proved in place.
|
|
@@ -356,6 +362,30 @@ pub fn inPlaceHazard(src: &str, fields: &[FieldArg]) -> bool {
|
|
|
356
362
|
false
|
|
357
363
|
}
|
|
358
364
|
|
|
365
|
+
/// Does `e` use `v` other than to read one of its fields?
|
|
366
|
+
fn usesBeyondFieldReads(e: &Expr, v: &str) -> bool {
|
|
367
|
+
let (mut uses, mut reads) = (0usize, 0usize);
|
|
368
|
+
walkExpr(e, &mut |n| {
|
|
369
|
+
if let Node::E(x) = n {
|
|
370
|
+
if isVar(x, v) {
|
|
371
|
+
uses += 1;
|
|
372
|
+
} else if let ExprKind::Attribute(a) = &x.kind {
|
|
373
|
+
if matches!(a.attr, AttrKind::Field(_)) && isVar(&a.object, v) {
|
|
374
|
+
reads += 1;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
true
|
|
379
|
+
});
|
|
380
|
+
uses != reads
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/// A value whose evaluation neither sees nor changes anything: it may run at any point.
|
|
384
|
+
fn isConstantLike(e: &Expr) -> bool {
|
|
385
|
+
matches!(&e.kind, ExprKind::Int(_) | ExprKind::Float(_) | ExprKind::BoolLit(_) | ExprKind::Var(_) | ExprKind::Self_)
|
|
386
|
+
|| matches!(&e.kind, ExprKind::String(s) if s.parts.iter().all(|p| !matches!(p, StringPart::Interp(_))))
|
|
387
|
+
}
|
|
388
|
+
|
|
359
389
|
// ---------- units ----------
|
|
360
390
|
|
|
361
391
|
struct UParam {
|
|
@@ -393,6 +423,8 @@ struct Unit {
|
|
|
393
423
|
struct Site {
|
|
394
424
|
caller: usize,
|
|
395
425
|
callee: usize,
|
|
426
|
+
/// The id of the call expression (a method call's is its `Attribute`'s).
|
|
427
|
+
node: NodeId,
|
|
396
428
|
/// Argument per callee parameter.
|
|
397
429
|
args: Vec<Option<Expr>>,
|
|
398
430
|
assignBack: Option<AssignTarget>,
|
|
@@ -453,6 +485,12 @@ struct An {
|
|
|
453
485
|
deadSpreads: Vec<Vec<DeadSpread>>,
|
|
454
486
|
/// `Array` methods that always return a new array.
|
|
455
487
|
arrayFresh: HashSet<usize>,
|
|
488
|
+
/// Per unit, can the program run it? What only unreachable code does (a helper of `test` blocks,
|
|
489
|
+
/// in a build) must not make the rest copy.
|
|
490
|
+
live: Vec<bool>,
|
|
491
|
+
/// The game's `gameUpdate` and `main`, when `gameUpdate` may take its state uniquely so far: `solve`
|
|
492
|
+
/// also needs `main`'s result to be unshared.
|
|
493
|
+
hostMain: Option<(usize, usize)>,
|
|
456
494
|
/// Reads `o.f` that move field `f` out of `o` while `o`'s one spread overwrites `f` (see
|
|
457
495
|
/// `collectMoves`), by node id.
|
|
458
496
|
moveReads: HashMap<NodeId, String>,
|
|
@@ -475,6 +513,8 @@ struct An {
|
|
|
475
513
|
/// Types whose spreads codegen always copies, with the reason: a generic type, and one variant of
|
|
476
514
|
/// an enum (the source's type is the enum, not the variant).
|
|
477
515
|
copyTypes: HashMap<String, String>,
|
|
516
|
+
/// Types and variants with a `mut` field.
|
|
517
|
+
mutTypes: HashSet<String>,
|
|
478
518
|
/// Variable checks in progress, and whether one of them has been answered by assuming it holds.
|
|
479
519
|
active: RefCell<HashSet<(usize, String, bool, bool)>>,
|
|
480
520
|
assumed: std::cell::Cell<bool>,
|
|
@@ -801,7 +841,25 @@ impl An {
|
|
|
801
841
|
if let Some(why) = self.copyTypes.get(&cc.type_name) {
|
|
802
842
|
return Some(why.clone());
|
|
803
843
|
}
|
|
844
|
+
if inPlaceHazard(v, &cc.fields) {
|
|
804
|
-
|
|
845
|
+
return Some(format!("a field value reads `{v}` after an earlier field overwrote it"));
|
|
846
|
+
}
|
|
847
|
+
// A copy reads the fields it keeps as it goes, in declaration order: a value that writes a `mut`
|
|
848
|
+
// field of `v` (through `v` itself, or a read-only method) comes too late for it, not in place.
|
|
849
|
+
if self.mutTypes.contains(&cc.type_name) && cc.fields.iter().any(|f| usesBeyondFieldReads(&f.value, v)) {
|
|
850
|
+
return Some(format!("`{}` has `mut` fields and a field value uses `{v}`", cc.type_name));
|
|
851
|
+
}
|
|
852
|
+
// A copy runs the values in declaration order and an in-place write as written: the two may
|
|
853
|
+
// only differ when at least two values can observe each other.
|
|
854
|
+
if let Some(declared) = self.enums.get(&cc.type_name) {
|
|
855
|
+
let at = |f: &FieldArg| declared.iter().position(|n| *n == f.name);
|
|
856
|
+
let outOfOrder = cc.fields.windows(2).any(|w| at(&w[0]) > at(&w[1]));
|
|
857
|
+
let busy = cc.fields.iter().filter(|f| !isConstantLike(&f.value)).count();
|
|
858
|
+
if outOfOrder && busy >= 2 {
|
|
859
|
+
return Some("field values written out of declaration order may affect each other".to_string());
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
None
|
|
805
863
|
}
|
|
806
864
|
|
|
807
865
|
fn spreadProved(&self, s: &SpreadSite) -> bool {
|
|
@@ -816,6 +874,17 @@ impl An {
|
|
|
816
874
|
}
|
|
817
875
|
|
|
818
876
|
/// Does this call-site argument pass a value that is unshared and dead in the caller?
|
|
877
|
+
/// Does `site` hand a unique value to parameter `j` of `g`?
|
|
878
|
+
fn siteArg(&self, site: &Site, g: usize, j: usize) -> Result<(), String> {
|
|
879
|
+
match &site.args[j] {
|
|
880
|
+
Some(e) => self.argOk(site, e),
|
|
881
|
+
None => match &self.units[g].params[j].default {
|
|
882
|
+
Some(d) if matches!(&d.kind, ExprKind::ClassCall(_)) => Ok(()),
|
|
883
|
+
_ => Err("a call omits the argument".to_string()),
|
|
884
|
+
},
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
|
|
819
888
|
fn argOk(&self, site: &Site, e: &Expr) -> Result<(), String> {
|
|
820
889
|
if self.fresh(e) {
|
|
821
890
|
return Ok(());
|
|
@@ -1260,10 +1329,11 @@ fn fieldsOf(enums: &HashMap<String, Vec<String>>, t: &str) -> Option<Vec<String>
|
|
|
1260
1329
|
pub fn markUnique(src: &mut Source) -> UniqueReport {
|
|
1261
1330
|
// The analysis tables are keyed by node id; simplify and drive leave new nodes unnumbered.
|
|
1262
1331
|
numberIds(src);
|
|
1332
|
+
let versions = versionCallers(src);
|
|
1263
1333
|
let an = build(src);
|
|
1264
1334
|
solve(&an);
|
|
1265
1335
|
// Report and mark.
|
|
1266
|
-
let mut report = UniqueReport::default();
|
|
1336
|
+
let mut report = UniqueReport { versions, ..UniqueReport::default() };
|
|
1267
1337
|
let isFip = |ui: usize| matches!(&src.items[an.units[ui].itemIdx], Item::Fn(f) if f.is_fip);
|
|
1268
1338
|
let mut verdicts: Vec<(usize, NodeId, &'static str, Result<(), String>)> = Vec::new();
|
|
1269
1339
|
let mut okVars: Vec<HashSet<String>> = vec![HashSet::new(); an.units.len()];
|
|
@@ -1328,7 +1398,8 @@ pub fn markUnique(src: &mut Source) -> UniqueReport {
|
|
|
1328
1398
|
_ => {}
|
|
1329
1399
|
}
|
|
1330
1400
|
for (_, node, what, result) in verdicts.iter().filter(|v| v.0 == ui) {
|
|
1401
|
+
// Not in the body: a spread of a parameter's default, which `fip fun` does not cover.
|
|
1331
|
-
let span = spans.get(node).copied()
|
|
1402
|
+
let Some(span) = spans.get(node).copied() else { continue };
|
|
1332
1403
|
report.fipSites.push(SiteVerdict { itemIdx: u.itemIdx, span, what, result: result.clone() });
|
|
1333
1404
|
}
|
|
1334
1405
|
for (_, span, result) in copied.iter().filter(|c| c.0 == ui) {
|
|
@@ -1502,6 +1573,12 @@ fn build(src: &Source) -> An {
|
|
|
1502
1573
|
}),
|
|
1503
1574
|
}
|
|
1504
1575
|
}
|
|
1576
|
+
// A parameter's default runs in the fn, before its body: `fun f(h: H = H(p: Base))` stores `Base`,
|
|
1577
|
+
// and `fun f(c: C = g(Base))` calls `g`. The proof must see that like any other code.
|
|
1578
|
+
for u in &mut units {
|
|
1579
|
+
let defaults: Vec<Stmt> = u.params.iter().filter_map(|p| p.default.clone()).map(|d| Stmt::Expr(d, 0, 0)).collect();
|
|
1580
|
+
u.block.stmts.splice(0..0, defaults);
|
|
1581
|
+
}
|
|
1505
1582
|
// A fn-typed parameter named like a free fn (`keep` in `find(self, keep: fn(T) -> Bool)`)
|
|
1506
1583
|
// shadows that fn in the whole body: its `keep(h)` is a closure call, not a call of the free
|
|
1507
1584
|
// fn `keep`. Only that body is affected, so rename the name there to one nothing defines
|
|
@@ -1595,6 +1672,14 @@ fn build(src: &Source) -> An {
|
|
|
1595
1672
|
}
|
|
1596
1673
|
}
|
|
1597
1674
|
}
|
|
1675
|
+
let mut mutTypes: HashSet<String> = HashSet::new();
|
|
1676
|
+
for item in &src.items {
|
|
1677
|
+
let Item::Enum(e) = item else { continue };
|
|
1678
|
+
for v in e.variants.iter().filter(|v| v.mut_fields.iter().any(|m| *m)) {
|
|
1679
|
+
mutTypes.insert(v.name.clone());
|
|
1680
|
+
mutTypes.insert(e.name.clone());
|
|
1681
|
+
}
|
|
1682
|
+
}
|
|
1598
1683
|
let varTy: Vec<HashMap<String, Option<String>>> = units.iter().map(varTypes).collect();
|
|
1599
1684
|
let mut an = An {
|
|
1600
1685
|
units,
|
|
@@ -1617,6 +1702,8 @@ fn build(src: &Source) -> An {
|
|
|
1617
1702
|
ro: HashSet::new(),
|
|
1618
1703
|
deadSpreads: vec![],
|
|
1619
1704
|
arrayFresh: HashSet::new(),
|
|
1705
|
+
live: vec![],
|
|
1706
|
+
hostMain: None,
|
|
1620
1707
|
moveReads: HashMap::new(),
|
|
1621
1708
|
moves: vec![],
|
|
1622
1709
|
varWrites: vec![],
|
|
@@ -1625,10 +1712,12 @@ fn build(src: &Source) -> An {
|
|
|
1625
1712
|
fieldTy,
|
|
1626
1713
|
varTy,
|
|
1627
1714
|
copyTypes,
|
|
1715
|
+
mutTypes,
|
|
1628
1716
|
active: RefCell::new(HashSet::new()),
|
|
1629
1717
|
assumed: std::cell::Cell::new(false),
|
|
1630
1718
|
};
|
|
1631
1719
|
stripDeadFnArgs(&mut an);
|
|
1720
|
+
an.live = liveUnits(&an, src);
|
|
1632
1721
|
for (i, u) in an.units.iter().enumerate() {
|
|
1633
1722
|
match u.label.as_str() {
|
|
1634
1723
|
"Array.push" | "Array.resize" | "Array.init" | "Array.filled" => {
|
|
@@ -1723,11 +1812,82 @@ fn build(src: &Source) -> An {
|
|
|
1723
1812
|
}
|
|
1724
1813
|
an.passes = passes;
|
|
1725
1814
|
collectFacts(&mut an);
|
|
1726
|
-
let host = hostShared(&an, src);
|
|
1815
|
+
let (host, hostMain) = hostShared(&an, src);
|
|
1727
1816
|
an.escaped.extend(host);
|
|
1817
|
+
an.hostMain = hostMain;
|
|
1728
1818
|
an
|
|
1729
1819
|
}
|
|
1730
1820
|
|
|
1821
|
+
/// The units the program can run, found from its entry points by name (a method call of known
|
|
1822
|
+
/// receiver type by type as well). Everything the compiler itself may call stays an entry point:
|
|
1823
|
+
/// exports, lowered tests, `IMPLICIT` methods, constants, and all of std except specialised copies,
|
|
1824
|
+
/// whose code is only there for their callers. A `fip fun` is one too: its guarantee is checked whether
|
|
1825
|
+
/// or not anything calls it. A program with no `main`, game entry, export or test keeps every unit.
|
|
1826
|
+
fn liveUnits(an: &An, src: &Source) -> Vec<bool> {
|
|
1827
|
+
let isEntry = |u: &Unit| -> bool {
|
|
1828
|
+
match &src.items[u.itemIdx] {
|
|
1829
|
+
Item::Fn(f) => f.is_export || f.is_test || (f.type_param.is_none() && ["main", crate::game_entry::GAME_UPDATE, crate::game_entry::GAME_DRAW].contains(&f.name.as_str())),
|
|
1830
|
+
Item::Test(_) => true,
|
|
1831
|
+
_ => false,
|
|
1832
|
+
}
|
|
1833
|
+
};
|
|
1834
|
+
if !an.units.iter().any(isEntry) {
|
|
1835
|
+
return vec![true; an.units.len()];
|
|
1836
|
+
}
|
|
1837
|
+
let mut free: HashMap<&str, Vec<usize>> = HashMap::new();
|
|
1838
|
+
let mut methods: HashMap<&str, Vec<usize>> = HashMap::new();
|
|
1839
|
+
for (i, u) in an.units.iter().enumerate().filter(|(_, u)| u.kind == Kind::Fn) {
|
|
1840
|
+
if u.ty.is_some() { &mut methods } else { &mut free }.entry(u.name.as_str()).or_default().push(i);
|
|
1841
|
+
}
|
|
1842
|
+
let mut live = vec![false; an.units.len()];
|
|
1843
|
+
let mut work: Vec<usize> = vec![];
|
|
1844
|
+
for (i, u) in an.units.iter().enumerate() {
|
|
1845
|
+
let inStd = |f: &Fn| f.file.starts_with("std/") || f.file.contains("/std/");
|
|
1846
|
+
let root = isEntry(u)
|
|
1847
|
+
|| u.kind != Kind::Fn
|
|
1848
|
+
|| IMPLICIT.contains(&u.name.as_str())
|
|
1849
|
+
|| matches!(&src.items[u.itemIdx], Item::Fn(f) if f.is_fip || (inStd(f) && !f.name.contains("$c")));
|
|
1850
|
+
if root {
|
|
1851
|
+
live[i] = true;
|
|
1852
|
+
work.push(i);
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
while let Some(i) = work.pop() {
|
|
1856
|
+
let mut found: Vec<usize> = vec![];
|
|
1857
|
+
let mut visit = |n: Node| {
|
|
1858
|
+
let Node::E(e) = n else { return true };
|
|
1859
|
+
match &e.kind {
|
|
1860
|
+
ExprKind::Var(x) => found.extend(free.get(x.as_str()).into_iter().flatten()),
|
|
1861
|
+
ExprKind::FnCall(c) => found.extend(free.get(c.name.as_str()).into_iter().flatten()),
|
|
1862
|
+
ExprKind::Attribute(a) => match &a.attr {
|
|
1863
|
+
AttrKind::Method(c) => {
|
|
1864
|
+
// A method call may also reach a free fn of that name.
|
|
1865
|
+
found.extend(free.get(c.name.as_str()).into_iter().flatten());
|
|
1866
|
+
let all = methods.get(c.name.as_str()).map_or(&[][..], |v| v.as_slice());
|
|
1867
|
+
let typed: Vec<usize> = all.iter().copied().filter(|&g| c.recv.is_some() && an.units[g].ty == c.recv).collect();
|
|
1868
|
+
found.extend(if typed.is_empty() { all.to_vec() } else { typed });
|
|
1869
|
+
}
|
|
1870
|
+
AttrKind::Field(f) => {
|
|
1871
|
+
if matches!(a.object.kind, ExprKind::TypeName(_)) {
|
|
1872
|
+
found.extend(methods.get(f.as_str()).into_iter().flatten());
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
},
|
|
1876
|
+
_ => {}
|
|
1877
|
+
}
|
|
1878
|
+
true
|
|
1879
|
+
};
|
|
1880
|
+
walkBlock(&an.units[i].block, &mut visit);
|
|
1881
|
+
for g in found {
|
|
1882
|
+
if !live[g] {
|
|
1883
|
+
live[g] = true;
|
|
1884
|
+
work.push(g);
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
}
|
|
1888
|
+
live
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1731
1891
|
/// The fn-typed parameters that do nothing: of specialised copies (`name$cN`, see `closure_spec`),
|
|
1732
1892
|
/// never called, and handed on only to other such parameters. A greatest fixpoint, since a recursive
|
|
1733
1893
|
/// copy hands the parameter to itself.
|
|
@@ -1829,7 +1989,8 @@ fn stripDeadFnArgs(an: &mut An) {
|
|
|
1829
1989
|
};
|
|
1830
1990
|
for (k, arg) in args.iter_mut().enumerate() {
|
|
1831
1991
|
let Arg::Positional(x) = arg else { break };
|
|
1992
|
+
// Only a value with nothing to run: another expression has effects and uses of its own.
|
|
1832
|
-
if matches!(x.kind, ExprKind::
|
|
1993
|
+
if !matches!(x.kind, ExprKind::Closure(_) | ExprKind::Var(_)) || !argIsDead(an, &dead, &view, k) {
|
|
1833
1994
|
continue;
|
|
1834
1995
|
}
|
|
1835
1996
|
walkExpr(x, &mut |n| {
|
|
@@ -1854,23 +2015,95 @@ fn stripDeadFnArgs(an: &mut An) {
|
|
|
1854
2015
|
/// look unique for want of a caller. `gameDraw`'s never is: the host keeps the state for the next
|
|
1855
2016
|
/// frame. `gameUpdate`'s is unique only when each state the host can hold is unshared, since the
|
|
1856
2017
|
/// host gives up the old state for `update`'s result: `main`'s result and every result of the game's
|
|
1857
|
-
/// `update` must be fresh, or `update`'s own `self`. Returns the entry points to treat as escaped
|
|
2018
|
+
/// `update` must be fresh, or `update`'s own `self`. Returns the entry points to treat as escaped,
|
|
2019
|
+
/// and, when all rests on a result of `main` that is a local, what `solve` must still check.
|
|
1858
|
-
fn hostShared(an: &An, src: &Source) -> Vec<usize> {
|
|
2020
|
+
fn hostShared(an: &An, src: &Source) -> (Vec<usize>, Option<(usize, usize)>) {
|
|
1859
2021
|
let find = |name: &str| an.units.iter().position(|u| u.kind == Kind::Fn && u.free && u.name == name);
|
|
1860
2022
|
let mut out: Vec<usize> = find(crate::game_entry::GAME_DRAW).into_iter().collect();
|
|
1861
|
-
let Some(gu) = find(crate::game_entry::GAME_UPDATE) else { return out };
|
|
2023
|
+
let Some(gu) = find(crate::game_entry::GAME_UPDATE) else { return (out, None) };
|
|
1862
2024
|
let ty = match &src.items[an.units[gu].itemIdx] {
|
|
1863
2025
|
Item::Fn(f) => f.returns.as_ref().map(|t| t.name.clone()),
|
|
1864
2026
|
_ => None,
|
|
1865
2027
|
};
|
|
1866
2028
|
let update = an.units.iter().position(|u| u.method && u.name == "update" && u.ty == ty);
|
|
1867
2029
|
let fresh = an.fresh_ret.borrow();
|
|
2030
|
+
let main = find("main");
|
|
1868
|
-
let
|
|
2031
|
+
let mainFresh = main.is_some_and(|m| fresh.contains(&m));
|
|
1869
2032
|
let updateOk = update.is_some_and(|g| fresh.contains(&g) || an.passes.get(&g).is_some_and(|ps| ps == &[0]));
|
|
2033
|
+
let drawKeeps = find(crate::game_entry::GAME_DRAW).is_none_or(|d| {
|
|
2034
|
+
let mut seen = HashSet::new();
|
|
2035
|
+
let state = an.units[d].params.iter().position(|p| p.ty == ty);
|
|
2036
|
+
state.is_none_or(|j| mayKeep(an, d, j, &mut seen))
|
|
2037
|
+
});
|
|
1870
|
-
if
|
|
2038
|
+
if main.is_none() || !updateOk || drawKeeps {
|
|
1871
2039
|
out.push(gu);
|
|
2040
|
+
return (out, None);
|
|
1872
2041
|
}
|
|
2042
|
+
(out, if mainFresh { None } else { main.map(|m| (gu, m)) })
|
|
2043
|
+
}
|
|
2044
|
+
|
|
2045
|
+
/// May parameter `j` of `g` outlive the call: be stored, captured, returned, or handed to code this
|
|
2046
|
+
/// cannot follow? Reading its fields, writing them, copying it with a spread and passing it to a fn
|
|
2047
|
+
/// that doesn't keep it are all safe. A cycle of calls keeps nothing that its members don't.
|
|
2048
|
+
fn mayKeep(an: &An, g: usize, j: usize, seen: &mut HashSet<(usize, usize)>) -> bool {
|
|
2049
|
+
if !seen.insert((g, j)) {
|
|
2050
|
+
return false;
|
|
2051
|
+
}
|
|
2052
|
+
let u = &an.units[g];
|
|
2053
|
+
let Some(name) = u.params.get(j).map(|p| p.name.as_str()) else { return true };
|
|
2054
|
+
let (mut uses, mut safe, mut captured) = (0usize, 0usize, false);
|
|
2055
|
+
let mut calls: Vec<(usize, usize)> = vec![];
|
|
2056
|
+
walkBlock(&u.block, &mut |n| {
|
|
2057
|
+
match n {
|
|
2058
|
+
Node::S(Stmt { kind: StmtKind::Assign(a), .. }) => {
|
|
2059
|
+
safe += a.targets.iter().filter(|t| matches!(t, AssignTarget::Field(o, _) if isVar(o, name))).count();
|
|
2060
|
+
}
|
|
2061
|
+
Node::E(e) => match &e.kind {
|
|
2062
|
+
ExprKind::Var(_) | ExprKind::Self_ if isVar(e, name) => uses += 1,
|
|
2063
|
+
ExprKind::Closure(_) => {
|
|
2064
|
+
walkExpr(e, &mut |m| {
|
|
2065
|
+
captured |= matches!(m, Node::E(x) if isVar(x, name));
|
|
1873
|
-
|
|
2066
|
+
true
|
|
2067
|
+
});
|
|
2068
|
+
}
|
|
2069
|
+
ExprKind::ClassCall(c) => {
|
|
2070
|
+
safe += c.spread.as_ref().is_some_and(|s| isVar(s, name)) as usize;
|
|
2071
|
+
}
|
|
2072
|
+
ExprKind::Attribute(a) if matches!(a.attr, AttrKind::Field(_)) => safe += isVar(&a.object, name) as usize,
|
|
2073
|
+
ExprKind::FnCall(_) | ExprKind::Attribute(_) => {
|
|
2074
|
+
let Some(targets) = an.callTargets(e) else { return true };
|
|
2075
|
+
let mut here = vec![];
|
|
2076
|
+
let mut counted = 0;
|
|
2077
|
+
for (k, (t, args)) in targets.iter().enumerate() {
|
|
2078
|
+
let at: Vec<usize> = (0..args.len()).filter(|&i| args[i].is_some_and(|x| isVar(x, name))).collect();
|
|
2079
|
+
if k == 0 {
|
|
2080
|
+
counted = at.len();
|
|
2081
|
+
}
|
|
2082
|
+
here.extend(at.into_iter().map(|i| (*t, i)));
|
|
2083
|
+
}
|
|
2084
|
+
safe += counted;
|
|
2085
|
+
calls.extend(here);
|
|
2086
|
+
}
|
|
2087
|
+
_ => {}
|
|
2088
|
+
},
|
|
2089
|
+
_ => {}
|
|
2090
|
+
}
|
|
2091
|
+
true
|
|
2092
|
+
});
|
|
2093
|
+
captured || uses != safe || calls.into_iter().any(|(t, i)| mayKeep(an, t, i, seen))
|
|
2094
|
+
}
|
|
2095
|
+
|
|
2096
|
+
/// Is every result of `main` fresh, or a local that nothing else holds (`game := ..; game`)?
|
|
2097
|
+
fn mainResultUnique(an: &An, main: usize) -> bool {
|
|
2098
|
+
let mut tails = vec![];
|
|
2099
|
+
collectTails(&an.units[main].block, &mut tails)
|
|
2100
|
+
&& !tails.is_empty()
|
|
2101
|
+
&& tails.iter().all(|e| {
|
|
2102
|
+
an.fresh(e)
|
|
2103
|
+
|| varName(e).is_some_and(|v| {
|
|
2104
|
+
!an.units[main].params.iter().any(|p| p.name == v) && an.varOk(main, v).is_ok()
|
|
2105
|
+
})
|
|
2106
|
+
})
|
|
1874
2107
|
}
|
|
1875
2108
|
|
|
1876
2109
|
/// The key of a node in the analysis tables. Unnumbered (id 0) nodes would all collide.
|
|
@@ -1896,7 +2129,7 @@ fn nodeKey(id: NodeId) -> NodeId {
|
|
|
1896
2129
|
fn collectMoves(a: &An, _spreads: &[SpreadSite]) -> (HashMap<NodeId, String>, Vec<(String, usize, NodeId)>) {
|
|
1897
2130
|
let mut reads: HashMap<NodeId, String> = HashMap::new();
|
|
1898
2131
|
let mut moves: Vec<(String, usize, NodeId)> = vec![];
|
|
1899
|
-
for (ui, u) in a.units.iter().enumerate() {
|
|
2132
|
+
for (ui, u) in a.units.iter().enumerate().filter(|(ui, _)| a.live[*ui]) {
|
|
1900
2133
|
let mut order = 0usize;
|
|
1901
2134
|
let mut fieldReads: HashMap<(String, String), usize> = HashMap::new();
|
|
1902
2135
|
let mut varCount: HashMap<String, usize> = HashMap::new();
|
|
@@ -2128,7 +2361,7 @@ fn collectFacts(an: &mut An) {
|
|
|
2128
2361
|
let mut reads: Vec<(NodeId, Vec<String>)> = vec![];
|
|
2129
2362
|
let mut allowed: HashSet<NodeId> = HashSet::new();
|
|
2130
2363
|
let a: &An = an;
|
|
2131
|
-
for (ui, u) in a.units.iter().enumerate() {
|
|
2364
|
+
for (ui, u) in a.units.iter().enumerate().filter(|(ui, _)| a.live[*ui]) {
|
|
2132
2365
|
let mut abMap: HashMap<NodeId, AssignTarget> = HashMap::new();
|
|
2133
2366
|
let mut inClosure: HashSet<NodeId> = HashSet::new();
|
|
2134
2367
|
// First pass: assign-back targets and closure membership.
|
|
@@ -2328,6 +2561,7 @@ fn collectFacts(an: &mut An) {
|
|
|
2328
2561
|
sites.push(Site {
|
|
2329
2562
|
caller: ui,
|
|
2330
2563
|
callee: g,
|
|
2564
|
+
node: e.id,
|
|
2331
2565
|
args,
|
|
2332
2566
|
assignBack: abMap.get(&nodeKey(e.id)).cloned().filter(|t| match t {
|
|
2333
2567
|
AssignTarget::Field(o, f) => {
|
|
@@ -2395,6 +2629,7 @@ fn collectFacts(an: &mut An) {
|
|
|
2395
2629
|
sites.push(Site {
|
|
2396
2630
|
caller: ui,
|
|
2397
2631
|
callee: g,
|
|
2632
|
+
node: e.id,
|
|
2398
2633
|
args,
|
|
2399
2634
|
assignBack: abMap.get(&nodeKey(e.id)).cloned().filter(|t| match t {
|
|
2400
2635
|
AssignTarget::Field(o, f) => {
|
|
@@ -2485,14 +2720,7 @@ fn solve(an: &An) {
|
|
|
2485
2720
|
let mut why: Option<String> = None;
|
|
2486
2721
|
let mut okFrom: Option<usize> = None;
|
|
2487
2722
|
for site in an.sites.iter().filter(|s| s.callee == g) {
|
|
2488
|
-
|
|
2723
|
+
match an.siteArg(site, g, j) {
|
|
2489
|
-
Some(e) => an.argOk(site, e),
|
|
2490
|
-
None => match &an.units[g].params[j].default {
|
|
2491
|
-
Some(d) if matches!(&d.kind, ExprKind::ClassCall(_)) => Ok(()),
|
|
2492
|
-
_ => Err("a call omits the argument".to_string()),
|
|
2493
|
-
},
|
|
2494
|
-
};
|
|
2495
|
-
match r {
|
|
2496
2724
|
Err(m) => {
|
|
2497
2725
|
let from = &an.units[site.caller].label;
|
|
2498
2726
|
if why.is_none() {
|
|
@@ -2510,6 +2738,13 @@ fn solve(an: &An) {
|
|
|
2510
2738
|
removeUp.push(((g, j), w));
|
|
2511
2739
|
}
|
|
2512
2740
|
}
|
|
2741
|
+
if let Some((gu, main)) = an.hostMain {
|
|
2742
|
+
if an.up.borrow().iter().any(|k| k.0 == gu) && !mainResultUnique(an, main) {
|
|
2743
|
+
let up = an.up.borrow();
|
|
2744
|
+
let held = up.iter().filter(|k| k.0 == gu);
|
|
2745
|
+
removeUp.extend(held.map(|&k| (k, "the host holds a state `main` may share".to_string())));
|
|
2746
|
+
}
|
|
2747
|
+
}
|
|
2513
2748
|
// Fields poisoned by spreads that are not proved.
|
|
2514
2749
|
let mut poisoned: HashSet<String> = HashSet::new();
|
|
2515
2750
|
for s in &an.spreads {
|
|
@@ -2559,3 +2794,310 @@ fn solve(an: &An) {
|
|
|
2559
2794
|
}
|
|
2560
2795
|
an.clearCache();
|
|
2561
2796
|
}
|
|
2797
|
+
|
|
2798
|
+
// ---------- unique versions ----------
|
|
2799
|
+
|
|
2800
|
+
/// A fn called with both unique and shared values gets a second copy for the unique calls.
|
|
2801
|
+
/// The copy is `f$unique`; the shared calls keep `f`. One copy per fn, so recursion and mutual
|
|
2802
|
+
/// recursion never multiply versions: a call inside `f$unique` that hands over a unique value
|
|
2803
|
+
/// goes to `g$unique`, whatever the depth.
|
|
2804
|
+
pub const VERSION_SUFFIX: &str = "$unique";
|
|
2805
|
+
const VERSION_ROUNDS: usize = 12;
|
|
2806
|
+
|
|
2807
|
+
fn unitKey(u: &Unit) -> String {
|
|
2808
|
+
match &u.ty {
|
|
2809
|
+
Some(t) => format!("{t}.{}", u.name),
|
|
2810
|
+
None => u.name.clone(),
|
|
2811
|
+
}
|
|
2812
|
+
}
|
|
2813
|
+
|
|
2814
|
+
/// Points the call with id `node` in item `itemIdx` at `name`. False when it is not found exactly
|
|
2815
|
+
/// once (a duplicated id: the call is left alone).
|
|
2816
|
+
fn retarget(src: &mut Source, itemIdx: usize, node: NodeId, name: &str) -> bool {
|
|
2817
|
+
let mut seen = 0;
|
|
2818
|
+
let mut count = |e: &mut Expr| {
|
|
2819
|
+
if e.id == node {
|
|
2820
|
+
seen += 1;
|
|
2821
|
+
}
|
|
2822
|
+
};
|
|
2823
|
+
let mut rename = |e: &mut Expr| {
|
|
2824
|
+
if e.id != node {
|
|
2825
|
+
return;
|
|
2826
|
+
}
|
|
2827
|
+
match &mut e.kind {
|
|
2828
|
+
ExprKind::FnCall(c) => c.name = name.to_string(),
|
|
2829
|
+
ExprKind::Attribute(a) => {
|
|
2830
|
+
if let AttrKind::Method(c) = &mut a.attr {
|
|
2831
|
+
c.name = name.to_string();
|
|
2832
|
+
}
|
|
2833
|
+
}
|
|
2834
|
+
_ => {}
|
|
2835
|
+
}
|
|
2836
|
+
};
|
|
2837
|
+
let run = |item: &mut Item, f: &mut dyn FnMut(&mut Expr)| match item {
|
|
2838
|
+
Item::Fn(func) => match &mut func.body {
|
|
2839
|
+
FnBody::Expr(e) => mutExpr(e, f),
|
|
2840
|
+
FnBody::Block(b) => mutBlock(b, f),
|
|
2841
|
+
FnBody::Extern => {}
|
|
2842
|
+
},
|
|
2843
|
+
Item::Test(t) => mutBlock(&mut t.body, f),
|
|
2844
|
+
Item::Const(c) => mutExpr(&mut c.value, f),
|
|
2845
|
+
_ => {}
|
|
2846
|
+
};
|
|
2847
|
+
run(&mut src.items[itemIdx], &mut count);
|
|
2848
|
+
if seen != 1 {
|
|
2849
|
+
return false;
|
|
2850
|
+
}
|
|
2851
|
+
run(&mut src.items[itemIdx], &mut rename);
|
|
2852
|
+
true
|
|
2853
|
+
}
|
|
2854
|
+
|
|
2855
|
+
/// Gives every call of `from` (a fn named `from` declared under `ty`) the name `to`.
|
|
2856
|
+
fn renameCalls(src: &mut Source, from: &HashSet<(Option<String>, String)>, to: &dyn std::ops::Fn(&str) -> String) {
|
|
2857
|
+
let mut rename = |e: &mut Expr| match &mut e.kind {
|
|
2858
|
+
ExprKind::FnCall(c) => {
|
|
2859
|
+
if from.contains(&(None, c.name.clone())) {
|
|
2860
|
+
c.name = to(&c.name);
|
|
2861
|
+
}
|
|
2862
|
+
}
|
|
2863
|
+
ExprKind::Attribute(a) => {
|
|
2864
|
+
if let AttrKind::Method(c) = &mut a.attr {
|
|
2865
|
+
if from.contains(&(c.recv.clone(), c.name.clone())) {
|
|
2866
|
+
c.name = to(&c.name);
|
|
2867
|
+
}
|
|
2868
|
+
}
|
|
2869
|
+
}
|
|
2870
|
+
_ => {}
|
|
2871
|
+
};
|
|
2872
|
+
for item in &mut src.items {
|
|
2873
|
+
match item {
|
|
2874
|
+
Item::Fn(func) => match &mut func.body {
|
|
2875
|
+
FnBody::Expr(e) => mutExpr(e, &mut rename),
|
|
2876
|
+
FnBody::Block(b) => mutBlock(b, &mut rename),
|
|
2877
|
+
FnBody::Extern => {}
|
|
2878
|
+
},
|
|
2879
|
+
Item::Test(t) => mutBlock(&mut t.body, &mut rename),
|
|
2880
|
+
Item::Const(c) => mutExpr(&mut c.value, &mut rename),
|
|
2881
|
+
_ => {}
|
|
2882
|
+
}
|
|
2883
|
+
}
|
|
2884
|
+
}
|
|
2885
|
+
|
|
2886
|
+
/// How many spreads of `ui` are proved in place.
|
|
2887
|
+
fn provedIn(an: &An, ui: usize) -> usize {
|
|
2888
|
+
an.spreads
|
|
2889
|
+
.iter()
|
|
2890
|
+
.filter(|s| s.unit == ui)
|
|
2891
|
+
.filter(|s| s.var.as_ref().is_some_and(|v| an.varOk(ui, v).is_ok()) && s.copies.is_none())
|
|
2892
|
+
.count()
|
|
2893
|
+
}
|
|
2894
|
+
|
|
2895
|
+
/// The calls to move to a unique version, per callee: those whose arguments are unique for every
|
|
2896
|
+
/// parameter that some other call leaves shared.
|
|
2897
|
+
fn versionPlan(an: &An) -> Vec<(usize, Vec<(usize, NodeId)>)> {
|
|
2898
|
+
// Only a fn that runs a spread, itself or further down, can gain from a copy.
|
|
2899
|
+
let mut gains: HashSet<usize> = an.spreads.iter().map(|s| s.unit).collect();
|
|
2900
|
+
loop {
|
|
2901
|
+
let before = gains.len();
|
|
2902
|
+
let more: Vec<usize> = an.sites.iter().filter(|s| gains.contains(&s.callee)).map(|s| s.caller).collect();
|
|
2903
|
+
gains.extend(more);
|
|
2904
|
+
if gains.len() == before {
|
|
2905
|
+
break;
|
|
2906
|
+
}
|
|
2907
|
+
}
|
|
2908
|
+
let mut plan = vec![];
|
|
2909
|
+
for (g, u) in an.units.iter().enumerate() {
|
|
2910
|
+
if u.kind != Kind::Fn || !(u.free || u.method) || an.escaped.contains(&g) || !gains.contains(&g) {
|
|
2911
|
+
continue;
|
|
2912
|
+
}
|
|
2913
|
+
if IMPLICIT.contains(&u.name.as_str()) || u.name == "main" || u.name.ends_with(VERSION_SUFFIX) {
|
|
2914
|
+
continue;
|
|
2915
|
+
}
|
|
2916
|
+
let sites: Vec<&Site> = an.sites.iter().filter(|s| s.callee == g).collect();
|
|
2917
|
+
if sites.len() < 2 {
|
|
2918
|
+
continue;
|
|
2919
|
+
}
|
|
2920
|
+
// Would this call hand over a unique value, were `g`'s parameter unique? (A local at its last
|
|
2921
|
+
// use depends on that: `v := mk(); g(v)`.) Only a plan: the final proof decides.
|
|
2922
|
+
let mut mixed = vec![];
|
|
2923
|
+
let mut okSites: Vec<Vec<usize>> = vec![];
|
|
2924
|
+
for (j, p) in u.params.iter().enumerate() {
|
|
2925
|
+
if !p.plain || an.paramUnique(g, j) {
|
|
2926
|
+
continue;
|
|
2927
|
+
}
|
|
2928
|
+
an.clearCache();
|
|
2929
|
+
an.up.borrow_mut().insert((g, j));
|
|
2930
|
+
let oks: Vec<usize> = (0..sites.len()).filter(|&k| an.siteArg(sites[k], g, j).is_ok()).collect();
|
|
2931
|
+
an.up.borrow_mut().remove(&(g, j));
|
|
2932
|
+
an.clearCache();
|
|
2933
|
+
if !oks.is_empty() && oks.len() < sites.len() {
|
|
2934
|
+
mixed.push(j);
|
|
2935
|
+
okSites.push(oks);
|
|
2936
|
+
}
|
|
2937
|
+
}
|
|
2938
|
+
if mixed.is_empty() {
|
|
2939
|
+
continue;
|
|
2940
|
+
}
|
|
2941
|
+
let uniq: Vec<(usize, NodeId)> = (0..sites.len())
|
|
2942
|
+
.filter(|k| okSites.iter().all(|oks| oks.contains(k)) && !sites[*k].inClosure)
|
|
2943
|
+
.map(|k| (sites[k].caller, sites[k].node))
|
|
2944
|
+
.collect();
|
|
2945
|
+
if !uniq.is_empty() {
|
|
2946
|
+
plan.push((g, uniq));
|
|
2947
|
+
}
|
|
2948
|
+
}
|
|
2949
|
+
plan
|
|
2950
|
+
}
|
|
2951
|
+
|
|
2952
|
+
/// Makes the unique versions that pay off, and returns the notes for `--explain-fusion`.
|
|
2953
|
+
fn versionCallers(src: &mut Source) -> Vec<String> {
|
|
2954
|
+
let nFns = src.items.iter().filter(|i| matches!(i, Item::Fn(_))).count();
|
|
2955
|
+
let budget = (nFns / 8).max(16);
|
|
2956
|
+
let mut made: HashMap<String, String> = HashMap::new();
|
|
2957
|
+
let mut notes = vec![];
|
|
2958
|
+
let mut cut = false;
|
|
2959
|
+
for round in 0..VERSION_ROUNDS {
|
|
2960
|
+
let an = build(src);
|
|
2961
|
+
solve(&an);
|
|
2962
|
+
let plan = versionPlan(&an);
|
|
2963
|
+
if plan.is_empty() {
|
|
2964
|
+
break;
|
|
2965
|
+
}
|
|
2966
|
+
if round + 1 == VERSION_ROUNDS {
|
|
2967
|
+
cut = true;
|
|
2968
|
+
break;
|
|
2969
|
+
}
|
|
2970
|
+
let mut changed = false;
|
|
2971
|
+
for (g, sites) in plan {
|
|
2972
|
+
let key = unitKey(&an.units[g]);
|
|
2973
|
+
let name = match made.get(&key) {
|
|
2974
|
+
Some(n) => n.clone(),
|
|
2975
|
+
None => {
|
|
2976
|
+
if made.len() >= budget {
|
|
2977
|
+
let note = format!("versions: no unique version of `{key}`: the program already has {budget} (a fn in every call chain is copied at most once)");
|
|
2978
|
+
if !notes.contains(¬e) {
|
|
2979
|
+
notes.push(note);
|
|
2980
|
+
}
|
|
2981
|
+
continue;
|
|
2982
|
+
}
|
|
2983
|
+
let Item::Fn(orig) = &src.items[an.units[g].itemIdx] else { continue };
|
|
2984
|
+
let mut copy = orig.clone();
|
|
2985
|
+
copy.name = format!("{}{VERSION_SUFFIX}", orig.name);
|
|
2986
|
+
copy.is_fip = false;
|
|
2987
|
+
refreshFnIds(&mut copy);
|
|
2988
|
+
let n = copy.name.clone();
|
|
2989
|
+
src.items.push(Item::Fn(copy));
|
|
2990
|
+
made.insert(key, n.clone());
|
|
2991
|
+
n
|
|
2992
|
+
}
|
|
2993
|
+
};
|
|
2994
|
+
for (caller, node) in sites {
|
|
2995
|
+
// A method call is moved only with its receiver's type known: the name alone
|
|
2996
|
+
// would reach the version of every type.
|
|
2997
|
+
if an.units[g].method {
|
|
2998
|
+
let known = an.sites.iter().any(|s| s.caller == caller && s.node == node && s.callee == g)
|
|
2999
|
+
&& methodRecvKnown(&an, caller, node, src);
|
|
3000
|
+
if !known {
|
|
3001
|
+
continue;
|
|
3002
|
+
}
|
|
3003
|
+
}
|
|
3004
|
+
changed |= retarget(src, an.units[caller].itemIdx, node, &name);
|
|
3005
|
+
}
|
|
3006
|
+
}
|
|
3007
|
+
if !changed {
|
|
3008
|
+
break;
|
|
3009
|
+
}
|
|
3010
|
+
}
|
|
3011
|
+
if cut {
|
|
3012
|
+
notes.push(format!("versions: stopped after {} rounds, calls further down a long call chain keep the shared version", VERSION_ROUNDS - 1));
|
|
3013
|
+
}
|
|
3014
|
+
if made.is_empty() {
|
|
3015
|
+
return notes;
|
|
3016
|
+
}
|
|
3017
|
+
// Keep a version only when its code proves more spreads than the original's, or it hands
|
|
3018
|
+
// values to a kept version.
|
|
3019
|
+
let an = build(src);
|
|
3020
|
+
solve(&an);
|
|
3021
|
+
let byKey: HashMap<String, usize> = an.units.iter().enumerate().filter(|(_, u)| u.kind == Kind::Fn).map(|(i, u)| (unitKey(u), i)).collect();
|
|
3022
|
+
let mut keep: HashSet<usize> = HashSet::new();
|
|
3023
|
+
let mut pairs = vec![];
|
|
3024
|
+
let mut madeSorted: Vec<(&String, &String)> = made.iter().collect();
|
|
3025
|
+
madeSorted.sort();
|
|
3026
|
+
for (orig, name) in madeSorted {
|
|
3027
|
+
let (Some(&o), cloneKey) = (byKey.get(orig), unitKey_(orig, name)) else { continue };
|
|
3028
|
+
let Some(&c) = byKey.get(&cloneKey) else { continue };
|
|
3029
|
+
pairs.push((o, c));
|
|
3030
|
+
// A version nothing calls proves everything for want of a caller: it is dropped.
|
|
3031
|
+
if an.sites.iter().any(|s| s.callee == c) && provedIn(&an, c) > provedIn(&an, o) {
|
|
3032
|
+
keep.insert(c);
|
|
3033
|
+
}
|
|
3034
|
+
}
|
|
3035
|
+
loop {
|
|
3036
|
+
let before = keep.len();
|
|
3037
|
+
for &(_, c) in &pairs {
|
|
3038
|
+
if !keep.contains(&c) && an.sites.iter().any(|s| s.caller == c && keep.contains(&s.callee)) {
|
|
3039
|
+
keep.insert(c);
|
|
3040
|
+
}
|
|
3041
|
+
}
|
|
3042
|
+
if keep.len() == before {
|
|
3043
|
+
break;
|
|
3044
|
+
}
|
|
3045
|
+
}
|
|
3046
|
+
let mut dropped: HashSet<(Option<String>, String)> = HashSet::new();
|
|
3047
|
+
for &(o, c) in &pairs {
|
|
3048
|
+
if keep.contains(&c) {
|
|
3049
|
+
let calls = an.sites.iter().filter(|s| s.callee == c).count();
|
|
3050
|
+
let n = provedIn(&an, c);
|
|
3051
|
+
let callers: Vec<&str> = an.sites.iter().filter(|s| s.callee == c).map(|s| an.units[s.caller].label.as_str()).take(3).collect();
|
|
3052
|
+
notes.push(format!(
|
|
3053
|
+
"versions: `{}` called with unique and shared values; `{}` takes the {} unique call(s) (from {}) and has {} spread(s) in place, `{}` keeps the shared ones",
|
|
3054
|
+
an.units[o].label, an.units[c].label, calls, callers.join(", "), n, an.units[o].label
|
|
3055
|
+
));
|
|
3056
|
+
} else {
|
|
3057
|
+
dropped.insert((an.units[c].ty.clone(), an.units[c].name.clone()));
|
|
3058
|
+
}
|
|
3059
|
+
}
|
|
3060
|
+
if !dropped.is_empty() {
|
|
3061
|
+
let free: HashSet<(Option<String>, String)> = dropped.iter().filter(|(t, _)| t.is_none()).cloned().collect();
|
|
3062
|
+
let strip = |n: &str| n.strip_suffix(VERSION_SUFFIX).unwrap_or(n).to_string();
|
|
3063
|
+
renameCalls(src, &free, &strip);
|
|
3064
|
+
// Method calls carry their receiver's type.
|
|
3065
|
+
let methods: HashSet<(Option<String>, String)> = dropped.iter().filter(|(t, _)| t.is_some()).cloned().collect();
|
|
3066
|
+
renameCalls(src, &methods, &strip);
|
|
3067
|
+
src.items.retain(|it| !matches!(it, Item::Fn(f) if dropped.contains(&(f.type_param.clone(), f.name.clone()))));
|
|
3068
|
+
}
|
|
3069
|
+
notes
|
|
3070
|
+
}
|
|
3071
|
+
|
|
3072
|
+
fn unitKey_(origKey: &str, cloneName: &str) -> String {
|
|
3073
|
+
match origKey.rsplit_once('.') {
|
|
3074
|
+
Some((t, _)) => format!("{t}.{cloneName}"),
|
|
3075
|
+
None => cloneName.to_string(),
|
|
3076
|
+
}
|
|
3077
|
+
}
|
|
3078
|
+
|
|
3079
|
+
/// Does the method call `node` of `caller` carry its receiver's type?
|
|
3080
|
+
fn methodRecvKnown(an: &An, caller: usize, node: NodeId, src: &Source) -> bool {
|
|
3081
|
+
let mut known = false;
|
|
3082
|
+
let mut find = |e: &mut Expr| {
|
|
3083
|
+
if e.id == node {
|
|
3084
|
+
if let ExprKind::Attribute(a) = &e.kind {
|
|
3085
|
+
if let AttrKind::Method(c) = &a.attr {
|
|
3086
|
+
known = c.recv.is_some();
|
|
3087
|
+
}
|
|
3088
|
+
}
|
|
3089
|
+
}
|
|
3090
|
+
};
|
|
3091
|
+
let mut item = src.items[an.units[caller].itemIdx].clone();
|
|
3092
|
+
match &mut item {
|
|
3093
|
+
Item::Fn(func) => match &mut func.body {
|
|
3094
|
+
FnBody::Expr(e) => mutExpr(e, &mut find),
|
|
3095
|
+
FnBody::Block(b) => mutBlock(b, &mut find),
|
|
3096
|
+
FnBody::Extern => {}
|
|
3097
|
+
},
|
|
3098
|
+
Item::Test(t) => mutBlock(&mut t.body, &mut find),
|
|
3099
|
+
Item::Const(c) => mutExpr(&mut c.value, &mut find),
|
|
3100
|
+
_ => {}
|
|
3101
|
+
}
|
|
3102
|
+
known
|
|
3103
|
+
}
|
compiler/core/tests/core/main.rs
CHANGED
|
@@ -28,5 +28,6 @@ mod trmc_test;
|
|
|
28
28
|
mod enum_checks_test;
|
|
29
29
|
mod uniqueness_moves_test;
|
|
30
30
|
mod uniqueness_test;
|
|
31
|
+
mod uniqueness_versions_test;
|
|
31
32
|
mod visit_test;
|
|
32
33
|
mod whistle_test;
|
compiler/core/tests/core/uniqueness_test.rs
CHANGED
|
@@ -308,7 +308,10 @@ fn mixed_unique_and_shared_calls_say_so() {
|
|
|
308
308
|
let (_, r) = run(&s);
|
|
309
309
|
assert!(!provedFn(&r, "bump"), "{r:?}");
|
|
310
310
|
let why = whyNot(&r, "bump");
|
|
311
|
+
assert!(why.contains("from other"), "{why}");
|
|
312
|
+
// The unique call has moved to its own version, which the report names.
|
|
313
|
+
assert!(provedFn(&r, "bump$unique"), "{r:?}");
|
|
311
|
-
assert!(
|
|
314
|
+
assert!(r.versions.iter().any(|v| v.contains("bump$unique") && v.contains("from go")), "{r:?}");
|
|
312
315
|
}
|
|
313
316
|
|
|
314
317
|
#[test]
|
compiler/core/tests/core/uniqueness_versions_test.rs
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
#![allow(non_snake_case)]
|
|
2
|
+
//! Shared and unique callers (T13): a fn called with both kinds of value gets a `$unique` copy for
|
|
3
|
+
//! the unique calls; the shared calls keep the copying original.
|
|
4
|
+
use plum_core::uniqueness::{markUnique, UniqueReport};
|
|
5
|
+
|
|
6
|
+
fn run(src: &str) -> (UniqueReport, plum_core::ast::Source) {
|
|
7
|
+
let mut s = plum_test_support::parseRawSource(src);
|
|
8
|
+
let r = markUnique(&mut s);
|
|
9
|
+
(r, s)
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
fn provedFn(r: &UniqueReport, name: &str) -> bool {
|
|
13
|
+
r.proved.iter().any(|p| p.starts_with(&format!("{name}:")))
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const CELL: &str = "struct Cell(label: Str, n: Int)\n\
|
|
17
|
+
fun bump(c: Cell) -> Cell = Cell(..c, n: c.n + 1)\n\
|
|
18
|
+
fun mk() -> Cell = Cell(label: \"a\", n: 0)\n";
|
|
19
|
+
|
|
20
|
+
#[test]
|
|
21
|
+
fn mixed_callers_give_a_unique_version() {
|
|
22
|
+
let (r, _) = run(&format!("{CELL}fun go() -> Int =\n s := mk()\n a := bump(s)\n b := bump(mk())\n a.n + b.n + s.n\n"));
|
|
23
|
+
assert!(provedFn(&r, "bump$unique"), "{r:?}");
|
|
24
|
+
assert!(!provedFn(&r, "bump"), "{r:?}");
|
|
25
|
+
assert!(r.versions.iter().any(|v| v.contains("bump$unique")), "{r:?}");
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
#[test]
|
|
29
|
+
fn only_shared_callers_make_no_version() {
|
|
30
|
+
let (r, s) = run(&format!("{CELL}fun go() -> Int =\n s := mk()\n a := bump(s)\n b := bump(s)\n a.n + b.n + s.n\n"));
|
|
31
|
+
assert!(r.versions.is_empty(), "{r:?}");
|
|
32
|
+
assert!(!provedFn(&r, "bump"), "{r:?}");
|
|
33
|
+
assert!(!s.items.iter().any(|i| matches!(i, plum_core::ast::Item::Fn(f) if f.name.contains("$unique"))));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
#[test]
|
|
37
|
+
fn only_unique_callers_make_no_version() {
|
|
38
|
+
let (r, _) = run(&format!("{CELL}fun go() -> Int =\n a := bump(mk())\n b := bump(mk())\n a.n + b.n\n"));
|
|
39
|
+
assert!(r.versions.is_empty(), "{r:?}");
|
|
40
|
+
assert!(provedFn(&r, "bump"), "{r:?}");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
#[test]
|
|
44
|
+
fn a_version_that_proves_nothing_more_is_dropped() {
|
|
45
|
+
// `size` has no spread: a copy of it would only grow the program.
|
|
46
|
+
let (r, s) = run(&format!("{CELL}fun size(c: Cell) -> Int = c.n\nfun go() -> Int =\n s := mk()\n size(s) + size(mk()) + s.n\n"));
|
|
47
|
+
assert!(r.versions.is_empty(), "{r:?}");
|
|
48
|
+
assert!(!s.items.iter().any(|i| matches!(i, plum_core::ast::Item::Fn(f) if f.name.contains("$unique"))));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
#[test]
|
|
52
|
+
fn a_shared_value_inside_the_unique_version_stays_a_copy() {
|
|
53
|
+
// `twice` gets a unique version; inside the shared `twice`, `bump` still sees a shared value.
|
|
54
|
+
let (r, _) = run(&format!(
|
|
55
|
+
"{CELL}fun twice(c: Cell) -> Cell = bump(bump(c))\nfun go() -> Int =\n s := mk()\n a := twice(s)\n b := twice(mk())\n a.n + b.n + s.n\n"
|
|
56
|
+
));
|
|
57
|
+
assert!(!provedFn(&r, "twice"), "{r:?}");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
#[test]
|
|
61
|
+
fn recursion_makes_one_version() {
|
|
62
|
+
let (r, s) = run(&format!(
|
|
63
|
+
"{CELL}fun run(c: Cell, k: Int) -> Cell = if k <= 0 then c else run(Cell(..c, n: c.n + 1), k - 1)\nfun go() -> Int =\n s := mk()\n a := run(s, 3)\n b := run(mk(), 3)\n a.n + b.n + s.n\n"
|
|
64
|
+
));
|
|
65
|
+
let copies = s.items.iter().filter(|i| matches!(i, plum_core::ast::Item::Fn(f) if f.name.starts_with("run"))).count();
|
|
66
|
+
assert!(copies <= 2, "{copies} {r:?}");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
#[test]
|
|
70
|
+
fn a_local_at_its_last_use_gets_the_version_too() {
|
|
71
|
+
// `v` is unique only if `bump` takes it uniquely, and the other call keeps `bump` from doing so.
|
|
72
|
+
let (r, _) = run(&format!(
|
|
73
|
+
"{CELL}fun go() -> Int =\n s := mk()\n a := bump(s)\n v := mk()\n b := bump(v)\n a.n + b.n + s.n\n"
|
|
74
|
+
));
|
|
75
|
+
assert!(provedFn(&r, "bump$unique"), "{r:?}");
|
|
76
|
+
assert!(!provedFn(&r, "bump"), "{r:?}");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
#[test]
|
|
80
|
+
fn a_fn_with_no_spread_below_it_takes_no_version_slot() {
|
|
81
|
+
let (r, s) = run(&format!(
|
|
82
|
+
"{CELL}fun size(c: Cell) -> Int = c.n\nfun go() -> Int =\n s := mk()\n v := mk()\n size(s) + size(v) + s.n\n"
|
|
83
|
+
));
|
|
84
|
+
assert!(r.versions.is_empty(), "{r:?}");
|
|
85
|
+
assert_eq!(s.items.iter().filter(|i| matches!(i, plum_core::ast::Item::Fn(f) if f.name.contains("$unique"))).count(), 0);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// ---- what cannot run must not make the rest copy ----
|
|
89
|
+
|
|
90
|
+
#[test]
|
|
91
|
+
fn a_call_from_a_fn_the_program_cannot_reach_does_not_count() {
|
|
92
|
+
// `helper` is what test blocks call; a build has none of them left.
|
|
93
|
+
let (r, _) = run(&format!(
|
|
94
|
+
"{CELL}fun helper(c: Cell) -> Int =\n d := bump(c)\n c.n + d.n\nfun main() -> Int = bump(mk()).n\n"
|
|
95
|
+
));
|
|
96
|
+
assert!(provedFn(&r, "bump"), "{r:?}");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
#[test]
|
|
100
|
+
fn a_call_from_a_reached_fn_counts() {
|
|
101
|
+
let (r, _) = run(&format!(
|
|
102
|
+
"{CELL}fun helper(c: Cell) -> Int =\n d := bump(c)\n c.n + d.n\nfun main() -> Int = helper(mk()) + bump(mk()).n\n"
|
|
103
|
+
));
|
|
104
|
+
assert!(!provedFn(&r, "bump"), "{r:?}");
|
|
105
|
+
assert!(provedFn(&r, "bump$unique"), "{r:?}");
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
#[test]
|
|
109
|
+
fn a_method_call_of_unknown_receiver_reaches_every_method_of_that_name() {
|
|
110
|
+
// Unstamped `x.go()`: the proof cannot tell, so `A.go`'s shared call counts.
|
|
111
|
+
let src = "struct A(n: Int, t: Str) =\n fun go(self) -> A = A(..self, n: 1)\n\
|
|
112
|
+
struct B(n: Int, t: Str) =\n fun go(self) -> B = B(..self, n: 2)\n\
|
|
113
|
+
fun helper(a: A) -> Int =\n b := a.go()\n a.n + b.n\n\
|
|
114
|
+
fun main() -> Int = helper(A(n: 0, t: \"\"))\n";
|
|
115
|
+
let (r, _) = run(src);
|
|
116
|
+
assert!(!provedFn(&r, "A.go"), "{r:?}");
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
#[test]
|
|
120
|
+
fn a_program_with_no_entry_point_keeps_every_call() {
|
|
121
|
+
let (r, _) = run(&format!("{CELL}fun helper(c: Cell) -> Int =\n d := bump(c)\n c.n + d.n\n"));
|
|
122
|
+
assert!(!provedFn(&r, "bump"), "{r:?}");
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// ---- what a copy and an in-place write do differently ----
|
|
126
|
+
|
|
127
|
+
#[test]
|
|
128
|
+
fn values_out_of_declaration_order_stay_a_copy() {
|
|
129
|
+
let src = "struct M(mut k: Int)\nstruct D(a: Int, b: Int, t: Str)\n\
|
|
130
|
+
fun nx(m: M) -> Int =\n m.k = m.k + 1\n m.k\n\
|
|
131
|
+
fun go(m: M) -> D =\n v := D(a: 0, b: 0, t: \"\")\n D(..v, b: nx(m), a: nx(m))\n\
|
|
132
|
+
fun ok(m: M) -> D =\n v := D(a: 0, b: 0, t: \"\")\n D(..v, a: nx(m), b: nx(m))\n";
|
|
133
|
+
let (r, _) = run(src);
|
|
134
|
+
assert!(!provedFn(&r, "go"), "{r:?}");
|
|
135
|
+
assert!(provedFn(&r, "ok"), "{r:?}");
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
#[test]
|
|
139
|
+
fn a_value_that_may_write_a_mut_field_of_the_source_stays_a_copy() {
|
|
140
|
+
// A copy reads `a` before `setA` runs; an in-place write would keep what `setA` wrote.
|
|
141
|
+
let src = "struct T(mut a: Int, b: Int, t: Str) =\n fun setA(self) -> Int =\n self.a = 9\n 1\n\
|
|
142
|
+
fun go() -> T =\n v := T(a: 1, b: 2, t: \"\")\n T(..v, b: v.setA())\n";
|
|
143
|
+
let (r, _) = run(src);
|
|
144
|
+
assert!(!provedFn(&r, "go"), "{r:?}");
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// ---- the game host ----
|
|
148
|
+
|
|
149
|
+
const GAME: &str = "struct Run(label: Str, t: Int) =\n fun update(self, dt: Int) -> Run = Run(..self, t: self.t + dt)\n fun draw(self) -> Int = self.t\n\
|
|
150
|
+
fun gameUpdate(g: Run, dt: Int) -> Run = g.update(dt)\nfun gameDraw(g: Run) -> Int = g.draw()\n";
|
|
151
|
+
|
|
152
|
+
#[test]
|
|
153
|
+
fn a_game_state_from_a_local_of_main_is_written_in_place() {
|
|
154
|
+
let (r, _) = run(&format!("{GAME}fun setup(g: Run) -> Int = g.t\nfun main() -> Run =\n g := Run(label: \"s\", t: 0)\n n := g.draw()\n g\n"));
|
|
155
|
+
assert!(provedFn(&r, "Run.update"), "{r:?}");
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
#[test]
|
|
159
|
+
fn a_game_state_main_also_keeps_is_not() {
|
|
160
|
+
let (r, _) = run(&format!(
|
|
161
|
+
"{GAME}Start = Run(label: \"s\", t: 0)\nfun main() -> Run =\n g := Start\n g\n"
|
|
162
|
+
));
|
|
163
|
+
assert!(!provedFn(&r, "Run.update"), "{r:?}");
|
|
164
|
+
let (r, _) = run(&format!(
|
|
165
|
+
"{GAME}struct Keep(r: Run)\nfun held(k: Keep) -> Int = k.r.t\nfun main() -> Run =\n g := Run(label: \"s\", t: 0)\n k := Keep(r: g)\n n := held(k)\n g\n"
|
|
166
|
+
));
|
|
167
|
+
assert!(!provedFn(&r, "Run.update"), "{r:?}");
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
#[test]
|
|
171
|
+
fn a_game_state_draw_keeps_is_not_written_in_place() {
|
|
172
|
+
let game = "struct Log(mut last: Int, mut kept: Option[Run])\n\
|
|
173
|
+
struct Run(log: Log, t: Int) =\n fun update(self, dt: Int) -> Run = Run(..self, t: self.t + dt)\n fun draw(self) -> Int =\n self.log.kept = Some(self)\n self.t\n\
|
|
174
|
+
fun gameUpdate(g: Run, dt: Int) -> Run = g.update(dt)\nfun gameDraw(g: Run) -> Int = g.draw()\n\
|
|
175
|
+
fun main() -> Run = Run(log: Log(last: 0, kept: None), t: 0)\n";
|
|
176
|
+
let (r, _) = run(game);
|
|
177
|
+
assert!(!provedFn(&r, "Run.update"), "{r:?}");
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
#[test]
|
|
181
|
+
fn a_draw_that_only_looks_leaves_the_state_unique() {
|
|
182
|
+
// Reads, a read-only helper, a copy with a spread and a free fn that only reads.
|
|
183
|
+
let game = "struct Run(label: Str, t: Int) =\n fun update(self, dt: Int) -> Run = Run(..self, t: self.t + dt)\n fun size(self) -> Int = self.t\n fun drawn(self) -> Run = Run(..self, t: 99)\n fun draw(self) -> Int = self.size() + self.drawn().t + look(self)\n\
|
|
184
|
+
fun look(r: Run) -> Int = r.t\n\
|
|
185
|
+
fun gameUpdate(g: Run, dt: Int) -> Run = g.update(dt)\nfun gameDraw(g: Run) -> Int = g.draw()\n\
|
|
186
|
+
fun main() -> Run = Run(label: \"s\", t: 0)\n";
|
|
187
|
+
let (r, _) = run(game);
|
|
188
|
+
assert!(provedFn(&r, "Run.update"), "{r:?}");
|
|
189
|
+
assert!(!provedFn(&r, "Run.drawn"), "{r:?}");
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
#[test]
|
|
193
|
+
fn a_constant_in_a_parameter_default_is_not_unique() {
|
|
194
|
+
let src = "struct C(label: Str, n: Int) =\n fun up(self) -> C = C(..self, n: self.n + 1)\n\
|
|
195
|
+
struct H(p: C, k: Int) =\n fun tick(self) -> H = H(..self, p: self.p.up())\n\
|
|
196
|
+
Base = C(label: \"b\", n: 1)\n\
|
|
197
|
+
fun bumped(c: C) -> C = C(..c, n: c.n + 1)\n\
|
|
198
|
+
fun held(n: Int, h: H = H(p: Base, k: 0)) -> H = if n <= 0 then h else held(n - 1, h.tick())\n\
|
|
199
|
+
fun called(n: Int, c: C = bumped(Base)) -> Int = if n <= 0 then c.n else called(n - 1, c)\n\
|
|
200
|
+
fun go() -> Int = held(2).p.n + called(1)\n";
|
|
201
|
+
let (r, _) = run(src);
|
|
202
|
+
// `tick`'s own spread is in place, but it may not hand `p` on, and `bumped` is handed a constant.
|
|
203
|
+
assert!(!provedFn(&r, "C.up"), "{r:?}");
|
|
204
|
+
assert!(!provedFn(&r, "bumped"), "{r:?}");
|
|
205
|
+
}
|
compiler/driver/src/lib.rs
CHANGED
|
@@ -78,12 +78,16 @@ pub fn fusionNotesWith(copy: &mut Source, fbip: bool) -> Vec<String> {
|
|
|
78
78
|
/// proof left as copies (see `plum_core::fip`). Needs `fbip`; without it nothing is enforced.
|
|
79
79
|
pub fn fusionRun(copy: &mut Source, fbip: bool) -> (Vec<String>, Vec<Diagnostic>) {
|
|
80
80
|
let origins = plum_core::fip::origins(copy);
|
|
81
|
+
// A build never runs `test` blocks (`plum test` lowers them to fns first, so none is left
|
|
82
|
+
// here): their calls must not make production code copy.
|
|
83
|
+
copy.items.retain(|i| !matches!(i, plum_core::ast::Item::Test(_)));
|
|
81
84
|
let mut errors = Vec::new();
|
|
82
85
|
let pure = plum_core::purity::pureFns(copy);
|
|
83
86
|
let mut notes = plum_core::simplify::simplify(copy, &pure);
|
|
84
87
|
notes.extend(plum_core::drive::drive(copy, &pure));
|
|
85
88
|
if fbip {
|
|
86
89
|
let rep = plum_core::uniqueness::markUnique(copy);
|
|
90
|
+
notes.extend(rep.versions.iter().cloned());
|
|
87
91
|
notes.extend(rep.proved.iter().map(|l| format!("unique spread at {l}")));
|
|
88
92
|
notes.extend(rep.unproved.iter().map(|(l, why)| format!("uniqueness: not in place {l}: {why}")));
|
|
89
93
|
errors = plum_core::fip::diagnostics(copy, &rep, &origins);
|
compiler/game/tests/fixtures/state_draw_keeps.plum
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
module state_draw_keeps
|
|
2
|
+
|
|
3
|
+
import std/Int
|
|
4
|
+
import std/Float
|
|
5
|
+
import std/Str
|
|
6
|
+
import std/game/Color
|
|
7
|
+
import std/game/gfx
|
|
8
|
+
import std/Io
|
|
9
|
+
|
|
10
|
+
# `draw` keeps the state it is given: the next `update` must not write that object in place.
|
|
11
|
+
struct Log(mut last: Option[Run])
|
|
12
|
+
|
|
13
|
+
struct Run(label: Str, log: Log, t: Int) =
|
|
14
|
+
fun update(self, io: Io, dt: Float) -> Run = Run(..self, t: self.t + 1)
|
|
15
|
+
|
|
16
|
+
fun draw(self, io: Io) =
|
|
17
|
+
before := match self.log.last
|
|
18
|
+
Some(r) => r.t
|
|
19
|
+
None => -1
|
|
20
|
+
self.log.last = Some(self)
|
|
21
|
+
gfx.drawText(io, "{before} {self.t}", 0.0, 0.0, 8.0, Color.White)
|
|
22
|
+
|
|
23
|
+
fun main(io: Io) -> Run = Run(label: "r", log: Log(last: None), t: 0)
|
compiler/game/tests/fixtures/state_main_alias.plum
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
module state_main_alias
|
|
2
|
+
|
|
3
|
+
import std/Int
|
|
4
|
+
import std/Float
|
|
5
|
+
import std/Str
|
|
6
|
+
import std/game/Color
|
|
7
|
+
import std/game/gfx
|
|
8
|
+
import std/Io
|
|
9
|
+
|
|
10
|
+
# `main` returns a local, but the local is a constant: `update` must not write it in place.
|
|
11
|
+
Start = Run(label: "start", t: 0)
|
|
12
|
+
|
|
13
|
+
struct Run(label: Str, t: Int) =
|
|
14
|
+
fun update(self, io: Io, dt: Float) -> Run = Run(..self, t: self.t + 1)
|
|
15
|
+
|
|
16
|
+
fun draw(self, io: Io) =
|
|
17
|
+
gfx.drawText(io, "{self.t} {Start.t}", 0.0, 0.0, 8.0, Color.White)
|
|
18
|
+
|
|
19
|
+
fun main(io: Io) -> Run =
|
|
20
|
+
s := Start
|
|
21
|
+
s
|
compiler/game/tests/host_test.rs
CHANGED
|
@@ -88,6 +88,18 @@ fn aStateFromAConstantIsNotWrittenInPlace() {
|
|
|
88
88
|
);
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
+
/// A local returned from `main` counts as unshared only when the proof says so.
|
|
92
|
+
#[test]
|
|
93
|
+
fn aLocalOfMainHoldingAConstantIsNotWrittenInPlace() {
|
|
94
|
+
assert_eq!(framesOf("state_main_alias.plum", 3), ["drawText(\"0 0\"", "drawText(\"1 0\"", "drawText(\"2 0\""]);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/// What `draw` keeps is an old state the host does not know about: `update` must copy.
|
|
98
|
+
#[test]
|
|
99
|
+
fn aStateDrawKeepsIsNotWrittenInPlace() {
|
|
100
|
+
assert_eq!(framesOf("state_draw_keeps.plum", 3), ["drawText(\"-1 0\"", "drawText(\"0 1\"", "drawText(\"1 2\""]);
|
|
101
|
+
}
|
|
102
|
+
|
|
91
103
|
/// `update` may write the state; `draw` may not: the host reads the state again after it.
|
|
92
104
|
#[test]
|
|
93
105
|
fn drawLeavesTheStateAlone() {
|
compiler/wasm-codegen/src/module.rs
CHANGED
|
@@ -316,7 +316,8 @@ impl WasmModule {
|
|
|
316
316
|
sorted.sort_by_key(|(i, _)| *i);
|
|
317
317
|
sorted.dedup_by_key(|(i, _)| *i);
|
|
318
318
|
for (i, n) in &sorted {
|
|
319
|
+
// A unique version (`f$unique`) shows in backtraces under the user's name.
|
|
319
|
-
map.append(*i, n);
|
|
320
|
+
map.append(*i, n.strip_suffix(plum_core::uniqueness::VERSION_SUFFIX).unwrap_or(n));
|
|
320
321
|
}
|
|
321
322
|
names.functions(&map);
|
|
322
323
|
module.section(&names);
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_mem/unique_inplace.rs
CHANGED
|
@@ -34,6 +34,7 @@ fun main() -> Int =
|
|
|
34
34
|
#[test]
|
|
35
35
|
fn unique_spread_reuses_object() {
|
|
36
36
|
let unique = prog(SPREAD);
|
|
37
|
+
// Fusion inlines `adv` into `main`, so the spread that runs is `main`'s.
|
|
37
|
-
assert!(spreadIsUnique("reuse_flag", "
|
|
38
|
+
assert!(spreadIsUnique("reuse_flag", "main", &unique));
|
|
38
39
|
assert_eq!(runInt("reuse_run", &unique), 207);
|
|
39
40
|
}
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_mem/unique_spread.rs
CHANGED
|
@@ -72,7 +72,8 @@ fn unique_flag_reuses_object() {
|
|
|
72
72
|
let p = format!("{PRE}{SPREAD}");
|
|
73
73
|
let a = structNewCount("u_plain", &p, false);
|
|
74
74
|
let b = structNewCount("u_flag", &p, true);
|
|
75
|
+
// `adv` is inlined and left unreached, so its own spread is not proved: the flag saves it too.
|
|
75
|
-
|
|
76
|
+
assert!(a > b, "plain {a} struct.new, unique {b}");
|
|
76
77
|
assert_eq!(runInt("u_run", &p, true), 214);
|
|
77
78
|
}
|
|
78
79
|
|
tests/fbip/fuzz/gen.pl
CHANGED
|
@@ -27,7 +27,7 @@ sub iexpr {
|
|
|
27
27
|
}
|
|
28
28
|
my @stmts;
|
|
29
29
|
for my $n (1..(6+r(12))) {
|
|
30
|
-
my $k = r(
|
|
30
|
+
my $k = r(51);
|
|
31
31
|
my $s;
|
|
32
32
|
my $V = recent(@vs); my $V2 = recent(@vs); my $W = recent(@ws);
|
|
33
33
|
my ($nvn, $nwn) = ("v$nv", "w$nw");
|
|
@@ -58,6 +58,11 @@ for my $n (1..(6+r(12))) {
|
|
|
58
58
|
elsif ($k==37) { $s = "0.until(".r(4).").fold($W.p, |acc, i| ".pick("acc.inc()", "pass(acc, acc)", "P(..acc, a: i)").")"; }
|
|
59
59
|
elsif ($k==43) { $s = "rtick($V)"; }
|
|
60
60
|
elsif ($k==44) { $s = "rleak(".pick("R(n: $V.a, p: $V)", "R(p: bump($V), n: $V.a)", "R(p: $V, n: 0).tick()").")"; }
|
|
61
|
+
elsif ($k==46) { $s = pick("vup($V)", "vup(vup($V))", "vup(mk(1, 2))", "pass(vup($V), $V2)"); }
|
|
62
|
+
elsif ($k==47) { $s = pick("$V.dbl()", "$V.dbl().dbl()", "mk(3, 4).dbl()", "pass($V.dbl(), $V)"); }
|
|
63
|
+
elsif ($k==48) { $s = pick("vping($V, ".r(4).")", "vping(mk(0, 0), ".r(4).")", "vpong($V, ".r(3).")"); }
|
|
64
|
+
elsif ($k==49) { $s = pick("vcnt($V, ".r(4).")", "vcnt(vcnt($V, 2), 1)", "vcnt(bump($V), 2)"); }
|
|
65
|
+
elsif ($k==50) { $s = "0.until(".r(3).").fold($V, |acc, i| ".pick("vup(acc)", "acc.dbl()", "vcnt(acc, i)").")"; }
|
|
61
66
|
elsif ($k==45) { $s = "0.until(".r(4).").fold($V, |acc, i| ".pick("step2(acc, i)", "step2(acc, $V2.a)").")"; }
|
|
62
67
|
else { $isv = 0; }
|
|
63
68
|
if ($isv) { push @stmts, "$nvn := $s"; push @vs, $nvn; $nv++; next; }
|
|
@@ -133,6 +138,22 @@ my %seen; my @show = grep { !$seen{$_}++ } (@ls, @qs, @kept);
|
|
|
133
138
|
my $linBody = join("
|
|
134
139
|
", @lin);
|
|
135
140
|
my $linDump = join(" + ", map { "$_.show()" } @show) || '""';
|
|
141
|
+
# A third test, on a type with a `mut` field: what a copy and an in-place write may do differently (the
|
|
142
|
+
# order values run in, a value writing the source), and a parameter default that holds a constant.
|
|
143
|
+
my @os = ('o0');
|
|
144
|
+
my $no = 1;
|
|
145
|
+
my @ord = ('o0 := Od(a: 1, b: 2, tag: "o")');
|
|
146
|
+
for my $n (1..(3+r(7))) {
|
|
147
|
+
my $x = $os[r(scalar @os)];
|
|
148
|
+
my $s = pick("Od(..$x, b: tk(c), a: tk(c))", "Od(..$x, a: tk(c), b: tk(c))", "Od(..$x, b: tk(c))", "Od(..$x, b: $x.latch())",
|
|
149
|
+
"Od(..$x, tag: \"t\", a: $x.a + 1)", "Od(..$x, b: tk(c), tag: \"u\")", "odUp($x)", "$x.up()", "odKeep($x, ".r(3).")");
|
|
150
|
+
@os = grep { $_ ne $x } @os if r(4);
|
|
151
|
+
push @ord, "o$no := $s";
|
|
152
|
+
push @os, "o$no";
|
|
153
|
+
$no++;
|
|
154
|
+
}
|
|
155
|
+
my $ordBody = join("\n ", @ord);
|
|
156
|
+
my $ordDump = join(" + ", map { "$_.show()" } @os);
|
|
136
157
|
open(my $fh, '>', $out) or die;
|
|
137
158
|
print $fh <<"EOP";
|
|
138
159
|
import std/Int
|
|
@@ -141,6 +162,7 @@ import std/Slice
|
|
|
141
162
|
|
|
142
163
|
struct P(a: Int, b: Int, tag: Str) =
|
|
143
164
|
fun inc(self) -> P = P(..self, a: self.a + 1)
|
|
165
|
+
fun dbl(self) -> P = P(..self, a: self.a * 2)
|
|
144
166
|
fun show(self) -> Str = "P(" + self.a.toStr() + "," + self.b.toStr() + "," + self.tag + ");"
|
|
145
167
|
|
|
146
168
|
struct Q(p: P, n: Int) =
|
|
@@ -189,6 +211,38 @@ fun mk(a: Int, b: Int) -> P = P(a: a, b: b, tag: "mk")
|
|
|
189
211
|
|
|
190
212
|
fun bump(p: P) -> P = P(..p, a: p.a + 1)
|
|
191
213
|
|
|
214
|
+
fun vup(p: P) -> P = P(..p, a: p.a + 2, b: p.b + 1)
|
|
215
|
+
|
|
216
|
+
fun vcnt(p: P, n: Int) -> P = if n <= 0 then p else vcnt(P(..p, b: p.b + 1), n - 1)
|
|
217
|
+
|
|
218
|
+
fun vping(p: P, n: Int) -> P = if n <= 0 then p else vpong(P(..p, a: p.a + 1), n - 1)
|
|
219
|
+
|
|
220
|
+
fun vpong(p: P, n: Int) -> P = if n <= 0 then p else vping(P(..p, b: p.b + 3), n - 1)
|
|
221
|
+
|
|
222
|
+
struct Ctr(mut k: Int)
|
|
223
|
+
|
|
224
|
+
fun tk(c: Ctr) -> Int =
|
|
225
|
+
c.k = c.k + 1
|
|
226
|
+
c.k
|
|
227
|
+
|
|
228
|
+
struct Od(mut a: Int, b: Int, tag: Str) =
|
|
229
|
+
fun latch(self) -> Int =
|
|
230
|
+
self.a = self.a + 50
|
|
231
|
+
1
|
|
232
|
+
fun up(self) -> Od = Od(..self, b: self.b + 1)
|
|
233
|
+
fun show(self) -> Str = "Od(" + self.a.toStr() + "," + self.b.toStr() + "," + self.tag + ");"
|
|
234
|
+
|
|
235
|
+
fun odUp(o: Od) -> Od = Od(..o, a: o.a + 3)
|
|
236
|
+
|
|
237
|
+
fun odKeep(o: Od, n: Int) -> Od = if n <= 0 then o else odKeep(Od(..o, b: o.b + n), n - 1)
|
|
238
|
+
|
|
239
|
+
OdStart = Od(a: 7, b: 8, tag: "start")
|
|
240
|
+
|
|
241
|
+
struct Oh(o: Od, n: Int) =
|
|
242
|
+
fun otick(self) -> Oh = Oh(..self, o: self.o.up())
|
|
243
|
+
|
|
244
|
+
fun odDflt(n: Int, h: Oh = Oh(o: OdStart, n: 0)) -> Oh = if n <= 0 then h else odDflt(n - 1, h.otick())
|
|
245
|
+
|
|
192
246
|
fun pass(x: P, y: P) -> P = if x.a > 2 then x else P(..y, b: 3)
|
|
193
247
|
|
|
194
248
|
fun repl(w: Q, p: P) -> P =
|
|
@@ -228,5 +282,11 @@ test "linear"
|
|
|
228
282
|
q0 := Lq(core: lmk(2), n: 0)
|
|
229
283
|
$linBody
|
|
230
284
|
assert $linDump == ""
|
|
285
|
+
|
|
286
|
+
test "order"
|
|
287
|
+
c := Ctr(k: 0)
|
|
288
|
+
$ordBody
|
|
289
|
+
h := odDflt(2)
|
|
290
|
+
assert h.o.show() + OdStart.show() + c.k.toStr() + $ordDump == ""
|
|
231
291
|
EOP
|
|
232
292
|
close $fh;
|
tests/fbip/versions.plum
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Str
|
|
3
|
+
|
|
4
|
+
# A fn called with both unique and shared values gets two versions: the unique calls reuse, the
|
|
5
|
+
# shared calls copy. The values are checked: a wrong proof writes through a value another holder
|
|
6
|
+
# still sees. Names are used by no other file.
|
|
7
|
+
struct Crate(label: Str, qty: Int) =
|
|
8
|
+
fun crateAdd(self, n: Int) -> Crate = Crate(..self, qty: self.qty + n)
|
|
9
|
+
|
|
10
|
+
fun crateBump(c: Crate, n: Int) -> Crate = Crate(..c, qty: c.qty + n)
|
|
11
|
+
|
|
12
|
+
# a recursive fn called both ways: the recursion inside the unique version stays unique
|
|
13
|
+
fun crateRun(c: Crate, k: Int) -> Crate = if k <= 0 then c else crateRun(Crate(..c, qty: c.qty + 1), k - 1)
|
|
14
|
+
|
|
15
|
+
# a shared value is handed on from a fn that also gets unique ones
|
|
16
|
+
fun crateTwice(c: Crate) -> Crate = crateBump(crateBump(c, 1), 2)
|
|
17
|
+
|
|
18
|
+
# mutual recursion across versions
|
|
19
|
+
fun pingCrate(c: Crate, k: Int) -> Crate = if k <= 0 then c else pongCrate(Crate(..c, qty: c.qty + 1), k - 1)
|
|
20
|
+
fun pongCrate(c: Crate, k: Int) -> Crate = if k <= 0 then c else pingCrate(Crate(..c, qty: c.qty + 10), k - 1)
|
|
21
|
+
|
|
22
|
+
# a local at its last use is unique only in the version
|
|
23
|
+
fun crateLocal() -> Int =
|
|
24
|
+
shared := Crate(label: "l", qty: 1)
|
|
25
|
+
a := crateBump(shared, 1)
|
|
26
|
+
own := Crate(label: "o", qty: 1)
|
|
27
|
+
b := crateBump(own, 2)
|
|
28
|
+
shared.qty * 100 + a.qty * 10 + b.qty
|
|
29
|
+
|
|
30
|
+
# one argument unique and the other shared, each way round
|
|
31
|
+
fun crateSum(x: Crate, y: Crate) -> Crate = Crate(..x, qty: x.qty + y.qty)
|
|
32
|
+
|
|
33
|
+
fun crateEach() -> Int =
|
|
34
|
+
s := Crate(label: "s", qty: 1)
|
|
35
|
+
a := crateSum(s, Crate(label: "t", qty: 2))
|
|
36
|
+
b := crateSum(Crate(label: "t", qty: 2), s)
|
|
37
|
+
own := Crate(label: "o", qty: 5)
|
|
38
|
+
c := crateSum(own, s)
|
|
39
|
+
s.qty * 1000 + a.qty * 100 + b.qty * 10 + c.qty
|
|
40
|
+
|
|
41
|
+
# values written out of declaration order, with side effects: as a copy would run them
|
|
42
|
+
struct Tally(mut k: Int)
|
|
43
|
+
|
|
44
|
+
struct Two(a: Int, b: Int, tag: Str)
|
|
45
|
+
|
|
46
|
+
fun tallyNext(t: Tally) -> Int =
|
|
47
|
+
t.k = t.k + 1
|
|
48
|
+
t.k
|
|
49
|
+
|
|
50
|
+
fun twoSpread() -> Int =
|
|
51
|
+
t := Tally(k: 0)
|
|
52
|
+
v := Two(a: 0, b: 0, tag: "x")
|
|
53
|
+
r := Two(..v, b: tallyNext(t), a: tallyNext(t))
|
|
54
|
+
r.a * 10 + r.b
|
|
55
|
+
|
|
56
|
+
# a value that writes a `mut` field of the spread source: a copy has read the field already
|
|
57
|
+
struct Latch(mut a: Int, b: Int, tag: Str) =
|
|
58
|
+
fun setA(self) -> Int =
|
|
59
|
+
self.a = 9
|
|
60
|
+
1
|
|
61
|
+
|
|
62
|
+
fun latchSpread() -> Int =
|
|
63
|
+
v := Latch(a: 1, b: 2, tag: "")
|
|
64
|
+
r := Latch(..v, b: v.setA())
|
|
65
|
+
r.a
|
|
66
|
+
|
|
67
|
+
# a constant reached through a parameter's default
|
|
68
|
+
struct CrateBox(crate: Crate, k: Int) =
|
|
69
|
+
fun boxTick(self) -> CrateBox = CrateBox(..self, crate: self.crate.crateAdd(1))
|
|
70
|
+
|
|
71
|
+
CrateBase = Crate(label: "base", qty: 1)
|
|
72
|
+
|
|
73
|
+
fun crateHeld(n: Int, b: CrateBox = CrateBox(crate: CrateBase, k: 0)) -> CrateBox =
|
|
74
|
+
if n <= 0 then b else crateHeld(n - 1, b.boxTick())
|
|
75
|
+
|
|
76
|
+
fun crateDefault(n: Int, c: Crate = crateBump(CrateBase, 1)) -> Int =
|
|
77
|
+
if n <= 0 then c.qty else crateDefault(n - 1, c)
|
|
78
|
+
|
|
79
|
+
test "unique call reuses and shared call copies"
|
|
80
|
+
shared := Crate(label: "a", qty: 1)
|
|
81
|
+
grown := crateBump(shared, 5)
|
|
82
|
+
assert shared.qty == 1
|
|
83
|
+
assert grown.qty == 6
|
|
84
|
+
fresh := crateBump(Crate(label: "b", qty: 1), 5)
|
|
85
|
+
assert fresh.qty == 6
|
|
86
|
+
again := crateBump(shared, 7)
|
|
87
|
+
assert shared.qty == 1
|
|
88
|
+
assert again.qty == 8
|
|
89
|
+
|
|
90
|
+
test "methods called both ways"
|
|
91
|
+
shared := Crate(label: "m", qty: 10)
|
|
92
|
+
a := shared.crateAdd(1)
|
|
93
|
+
b := Crate(label: "n", qty: 10).crateAdd(2)
|
|
94
|
+
c := shared.crateAdd(3)
|
|
95
|
+
assert shared.qty == 10
|
|
96
|
+
assert a.qty == 11
|
|
97
|
+
assert b.qty == 12
|
|
98
|
+
assert c.qty == 13
|
|
99
|
+
|
|
100
|
+
test "recursion and mutual recursion across versions"
|
|
101
|
+
shared := Crate(label: "r", qty: 0)
|
|
102
|
+
a := crateRun(shared, 4)
|
|
103
|
+
b := crateRun(Crate(label: "s", qty: 0), 4)
|
|
104
|
+
assert shared.qty == 0
|
|
105
|
+
assert a.qty == 4
|
|
106
|
+
assert b.qty == 4
|
|
107
|
+
p := pingCrate(shared, 3)
|
|
108
|
+
q := pingCrate(Crate(label: "t", qty: 0), 3)
|
|
109
|
+
assert shared.qty == 0
|
|
110
|
+
assert p.qty == 12
|
|
111
|
+
assert q.qty == 12
|
|
112
|
+
|
|
113
|
+
test "a shared value inside a unique caller stays shared"
|
|
114
|
+
shared := Crate(label: "w", qty: 100)
|
|
115
|
+
x := crateTwice(shared)
|
|
116
|
+
y := crateTwice(Crate(label: "z", qty: 100))
|
|
117
|
+
assert shared.qty == 100
|
|
118
|
+
assert x.qty == 103
|
|
119
|
+
assert y.qty == 103
|
|
120
|
+
|
|
121
|
+
test "a local handed over in a program that also shares"
|
|
122
|
+
assert crateLocal() == 123
|
|
123
|
+
|
|
124
|
+
test "one argument unique and the other shared"
|
|
125
|
+
assert crateEach() == 1336
|
|
126
|
+
|
|
127
|
+
test "field values run as a copy runs them"
|
|
128
|
+
assert twoSpread() == 12
|
|
129
|
+
assert latchSpread() == 1
|
|
130
|
+
|
|
131
|
+
test "a constant behind a parameter default stays as it was"
|
|
132
|
+
assert crateHeld(2).crate.qty == 3
|
|
133
|
+
assert crateDefault(1) == 2
|
|
134
|
+
assert CrateBase.qty == 1
|