plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
dd03d29
— Peter John
2026-11-09T22:25:05+05:30
std ref.same: reference identity as one ref.eq, heap types only, never updated in place
- compiler/checker/src/identity.rs +49 -0
- compiler/checker/src/infer.rs +1 -0
- compiler/checker/src/lib.rs +1 -0
- compiler/checker/src/program.rs +10 -0
- compiler/checker/src/state.rs +3 -0
- compiler/checker/tests/checker/features/identity.rs +46 -0
- compiler/checker/tests/checker/features/mod.rs +1 -0
- compiler/core/src/purity.rs +4 -0
- compiler/core/src/uniqueness.rs +24 -0
- compiler/core/tests/core/uniqueness_test.rs +29 -0
- compiler/wasm-codegen/src/context.rs +2 -0
- compiler/wasm-codegen/src/driver.rs +8 -0
- compiler/wasm-codegen/src/expr.rs +11 -2
- compiler/wasm-codegen/src/intrinsics.rs +47 -0
- docs/std.md +2 -1
- std/ref.plum +24 -0
- tests/core/ref_same.plum +94 -0
compiler/checker/src/identity.rs
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
//! Reference identity, std's `ref.same(a, b)` (std/ref.plum): whether two values are the
|
|
2
|
+
//! very same object. Codegen makes it one `ref.eq` (`plum_wasm_codegen::intrinsics`), so it
|
|
3
|
+
//! is only for values that are one heap reference. The rule, at every call: the argument
|
|
4
|
+
//! type must not be a scalar (`Int`, `Float`, `Bool`, `Byte`), `Unit`, `Io`, a flat struct
|
|
5
|
+
//! (copied by value: it has no identity), a function, or a bare type parameter (which an
|
|
6
|
+
//! instantiation could make any of those).
|
|
7
|
+
//!
|
|
8
|
+
//! In-place updates never make two different contents look the same: a variable passed to
|
|
9
|
+
//! `same` is never updated in place (`plum_core::uniqueness`).
|
|
10
|
+
|
|
11
|
+
use crate::*;
|
|
12
|
+
|
|
13
|
+
/// Whether `f` is std's `same` (std/ref.plum), under any module rename (`same@ref`).
|
|
14
|
+
pub(crate) fn isSameFn(f: &ast::Fn) -> bool {
|
|
15
|
+
f.type_param.is_none()
|
|
16
|
+
&& plum_core::modules::sourceFnName(&f.name) == "same"
|
|
17
|
+
&& f.file.replace('\\', "/").ends_with("std/ref.plum")
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/// For a call of `ref.same`: an error when its argument type (after `binds`) is not one heap
|
|
21
|
+
/// reference. Any other call passes.
|
|
22
|
+
pub(crate) fn checkSameArgs(name: &str, params: &[PlumType], binds: &Binds, ctx: &CheckCtx) -> Result<(), String> {
|
|
23
|
+
if !withCheck(|s| s.same_fns.borrow().contains(name)) {
|
|
24
|
+
return Ok(());
|
|
25
|
+
}
|
|
26
|
+
let Some(p) = params.first() else { return Ok(()) };
|
|
27
|
+
let t = substVars(p, binds);
|
|
28
|
+
match whyNotHeap(&t, ctx) {
|
|
29
|
+
Some(why) => Err(format!(
|
|
30
|
+
"ref.same compares heap objects by identity, and {t} {why}; compare values with =="
|
|
31
|
+
)),
|
|
32
|
+
None => Ok(()),
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
fn whyNotHeap(t: &PlumType, ctx: &CheckCtx) -> Option<&'static str> {
|
|
37
|
+
match t {
|
|
38
|
+
PlumType::TInt | PlumType::TFloat | PlumType::TBool | PlumType::TByte | PlumType::TUnit => {
|
|
39
|
+
Some("is a scalar")
|
|
40
|
+
}
|
|
41
|
+
PlumType::TFun(..) => Some("is a function"),
|
|
42
|
+
PlumType::TParam(_) | PlumType::TVar(_) => Some("is a type parameter, which may be a scalar"),
|
|
43
|
+
PlumType::TNamed(n) if n == ast::IO_TYPE => Some("is a capability, not an object"),
|
|
44
|
+
PlumType::TNamed(n) if ctx.enum_variants.values().any(|i| i.enum_name == *n && i.is_value) => {
|
|
45
|
+
Some("is a flat struct, copied by value")
|
|
46
|
+
}
|
|
47
|
+
_ => None,
|
|
48
|
+
}
|
|
49
|
+
}
|
compiler/checker/src/infer.rs
CHANGED
|
@@ -559,6 +559,7 @@ pub(crate) fn inferExprInner(
|
|
|
559
559
|
.unwrap_or(param_types.len());
|
|
560
560
|
checkCallArgs(&label, ¶m_types, &call.args, required, env, ctx, &mut binds)?;
|
|
561
561
|
checkUnpinned(call, &call_map, ¶m_types, &ret, &binds, ctx)?;
|
|
562
|
+
crate::identity::checkSameArgs(&call.name, ¶m_types, &binds, ctx)?;
|
|
562
563
|
recordCall(None, &call.name, call_map);
|
|
563
564
|
Ok(substVars(&ret, &binds))
|
|
564
565
|
}
|
compiler/checker/src/lib.rs
CHANGED
|
@@ -11,6 +11,7 @@ mod declchecks;
|
|
|
11
11
|
mod fields;
|
|
12
12
|
mod fncheck;
|
|
13
13
|
mod generics;
|
|
14
|
+
mod identity;
|
|
14
15
|
mod infer;
|
|
15
16
|
mod loops;
|
|
16
17
|
mod matchcheck;
|
compiler/checker/src/program.rs
CHANGED
|
@@ -224,6 +224,16 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
224
224
|
})
|
|
225
225
|
.collect()
|
|
226
226
|
});
|
|
227
|
+
withCheck(|s| {
|
|
228
|
+
*s.same_fns.borrow_mut() = source
|
|
229
|
+
.items
|
|
230
|
+
.iter()
|
|
231
|
+
.filter_map(|i| match i {
|
|
232
|
+
ast::Item::Fn(f) if crate::identity::isSameFn(f) => Some(f.name.clone()),
|
|
233
|
+
_ => None,
|
|
234
|
+
})
|
|
235
|
+
.collect()
|
|
236
|
+
});
|
|
227
237
|
errors.extend(checkTraitDecls(source, &traits, &methods));
|
|
228
238
|
errors.extend(selfOutsideTrait(source));
|
|
229
239
|
// Shared fields of subtyped traits; codegen fills them in (see `addTraitParams`).
|
compiler/checker/src/state.rs
CHANGED
|
@@ -68,6 +68,9 @@ pub(crate) struct CheckState {
|
|
|
68
68
|
/// `CheckError` made from it is a `DiagKind::Resolution`. Saved, restored and cleared
|
|
69
69
|
/// together with `err_pos`.
|
|
70
70
|
pub(crate) err_resolution: Cell<bool>,
|
|
71
|
+
/// The global names of std's `ref.same` (std/ref.plum), whose argument type the checker
|
|
72
|
+
/// limits to heap types (`identity::checkSameArgs`).
|
|
73
|
+
pub(crate) same_fns: RefCell<std::collections::HashSet<String>>,
|
|
71
74
|
/// The names of the top-level functions and constants (the keys of the global env).
|
|
72
75
|
pub(crate) globals: RefCell<std::collections::HashSet<String>>,
|
|
73
76
|
pub(crate) scope_site: RefCell<Option<(String, usize, String)>>,
|
compiler/checker/tests/checker/features/identity.rs
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
//! `ref.same(a, b)` (std/ref.plum): reference identity, only for heap values.
|
|
2
|
+
use plum_checker::checkSource;
|
|
3
|
+
|
|
4
|
+
fn run(body: &str) -> Result<(), String> {
|
|
5
|
+
let src = format!(
|
|
6
|
+
"import std/Int\nimport std/Float\nimport std/Str\nimport std/List\nimport std/ref\n\n\
|
|
7
|
+
struct Flat(x: Int, y: Int)\nstruct Boxed(x: Int, s: Str)\n\
|
|
8
|
+
trait Named =\n fun name(self) -> Str\n\
|
|
9
|
+
struct Dog(s: Str) is Named =\n fun name(self) -> Str = self.s\n\
|
|
10
|
+
enum Tree =\n | Leaf\n | Node(l: Tree, r: Tree)\n\n{body}"
|
|
11
|
+
);
|
|
12
|
+
let source = plum_test_support::load("identity", &src)?;
|
|
13
|
+
checkSource(&source).map_err(|e| e.into_iter().map(|x| x.message).collect::<Vec<_>>().join(" | "))
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
#[test]
|
|
17
|
+
fn heap_values_may_be_compared() {
|
|
18
|
+
run("fun f(a: Boxed, d: Named, t: Tree, s: Str, xs: List[Int]) -> Bool =\n \
|
|
19
|
+
ref.same(a, a) && ref.same(d, d) && ref.same(t, Leaf) && ref.same(s, s) && ref.same(xs, xs)\n")
|
|
20
|
+
.unwrap();
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
#[test]
|
|
24
|
+
fn a_generic_instantiated_with_a_heap_type_is_accepted() {
|
|
25
|
+
run("fun g[T](a: T) -> Bool = ref.same(a, a)\n\nfun f(b: Boxed) -> Bool = g(b)\n").unwrap();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
#[test]
|
|
29
|
+
fn scalars_flat_structs_and_functions_are_rejected() {
|
|
30
|
+
for (arg, why) in [
|
|
31
|
+
("1, 2", "Int is a scalar"),
|
|
32
|
+
("1.0, 2.0", "Float is a scalar"),
|
|
33
|
+
("true, false", "Bool is a scalar"),
|
|
34
|
+
("Flat(x: 1, y: 2), Flat(x: 1, y: 2)", "Flat is a flat struct"),
|
|
35
|
+
("|x: Int| x, |x: Int| x", "is a function"),
|
|
36
|
+
] {
|
|
37
|
+
let e = run(&format!("fun f() -> Bool = ref.same({arg})\n")).unwrap_err();
|
|
38
|
+
assert!(e.contains("ref.same compares heap objects by identity") && e.contains(why), "{arg}: {e}");
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
#[test]
|
|
43
|
+
fn a_generic_instantiated_with_a_scalar_is_rejected() {
|
|
44
|
+
let e = run("fun g[T](a: T) -> Bool = ref.same(a, a)\n\nfun f() -> Bool = g(3)\n").unwrap_err();
|
|
45
|
+
assert!(e.contains("Int is a scalar"), "{e}");
|
|
46
|
+
}
|
compiler/checker/tests/checker/features/mod.rs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
#![allow(non_snake_case)]
|
|
2
2
|
//! Small checker feature tests, one module per feature.
|
|
3
3
|
mod closure_types;
|
|
4
|
+
mod identity;
|
|
4
5
|
mod io_capability;
|
|
5
6
|
mod mutability;
|
|
6
7
|
mod optional_unpinned;
|
compiler/core/src/purity.rs
CHANGED
|
@@ -51,6 +51,10 @@ pub fn pureFns(src: &Source) -> HashSet<String> {
|
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
53
|
let mut info = analyse(f, &ctors, &receivers);
|
|
54
|
+
if crate::uniqueness::isSameFn(f) {
|
|
55
|
+
// std's `ref.same`: a `todo` body the compiler fills with one `ref.eq`
|
|
56
|
+
info.impure = false;
|
|
57
|
+
}
|
|
54
58
|
if reachesIo(f, &ioTypes) {
|
|
55
59
|
info.impure = true;
|
|
56
60
|
}
|
compiler/core/src/uniqueness.rs
CHANGED
|
@@ -518,6 +518,9 @@ struct An {
|
|
|
518
518
|
copyTypes: HashMap<String, String>,
|
|
519
519
|
/// Types and variants with a `mut` field.
|
|
520
520
|
mutTypes: HashSet<String>,
|
|
521
|
+
/// The global names of std's `ref.same` (std/ref.plum): a variable passed to it is never
|
|
522
|
+
/// unique, so what it is compared with by identity cannot have been written into its cell.
|
|
523
|
+
sameFns: HashSet<String>,
|
|
521
524
|
/// Variable checks in progress, and whether one of them has been answered by assuming it holds.
|
|
522
525
|
active: RefCell<HashSet<(usize, String, bool, bool)>>,
|
|
523
526
|
assumed: std::cell::Cell<bool>,
|
|
@@ -1282,6 +1285,12 @@ impl<'a> Scan<'a> {
|
|
|
1282
1285
|
let v = self.v.to_string();
|
|
1283
1286
|
let g = self.an.isFree(&c.name);
|
|
1284
1287
|
let bareCount = c.args.iter().filter(|a| self.bare(argExpr(a))).count();
|
|
1288
|
+
// `ref.same(v, w)` compares `v` by identity: had `v`'s cell been written in place,
|
|
1289
|
+
// `w` (its new version) would be the same object with other contents.
|
|
1290
|
+
if bareCount > 0 && self.an.sameFns.contains(&c.name) {
|
|
1291
|
+
self.fail(format!("`{v}` is compared by identity (`ref.same`), so it is never updated in place"));
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
1285
1294
|
for (k, a) in c.args.iter().enumerate() {
|
|
1286
1295
|
let e = argExpr(a);
|
|
1287
1296
|
let lv = live || c.args[k + 1..].iter().any(|x| self.mentions(argExpr(x)));
|
|
@@ -1610,6 +1619,13 @@ fn varTypes(u: &Unit) -> HashMap<String, Option<String>> {
|
|
|
1610
1619
|
/// (see `build`): the renamed name is defined nowhere.
|
|
1611
1620
|
const SHADOW_MARK: &str = "\u{0}shadow";
|
|
1612
1621
|
|
|
1622
|
+
/// Whether `f` is std's `ref.same` (std/ref.plum), under any module rename (`same@ref`).
|
|
1623
|
+
pub(crate) fn isSameFn(f: &Fn) -> bool {
|
|
1624
|
+
f.type_param.is_none()
|
|
1625
|
+
&& crate::modules::sourceFnName(&f.name) == "same"
|
|
1626
|
+
&& f.file.replace('\\', "/").ends_with("std/ref.plum")
|
|
1627
|
+
}
|
|
1628
|
+
|
|
1613
1629
|
fn build(src: &Source) -> An {
|
|
1614
1630
|
let mut units: Vec<Unit> = Vec::new();
|
|
1615
1631
|
let mut enums: HashMap<String, Vec<String>> = HashMap::new();
|
|
@@ -1842,6 +1858,14 @@ fn build(src: &Source) -> An {
|
|
|
1842
1858
|
varTy,
|
|
1843
1859
|
copyTypes,
|
|
1844
1860
|
mutTypes,
|
|
1861
|
+
sameFns: src
|
|
1862
|
+
.items
|
|
1863
|
+
.iter()
|
|
1864
|
+
.filter_map(|i| match i {
|
|
1865
|
+
Item::Fn(f) if isSameFn(f) => Some(f.name.clone()),
|
|
1866
|
+
_ => None,
|
|
1867
|
+
})
|
|
1868
|
+
.collect(),
|
|
1845
1869
|
active: RefCell::new(HashSet::new()),
|
|
1846
1870
|
assumed: std::cell::Cell::new(false),
|
|
1847
1871
|
};
|
compiler/core/tests/core/uniqueness_test.rs
CHANGED
|
@@ -421,3 +421,32 @@ fn a_closure_field_named_like_a_fresh_method_is_not_that_method() {
|
|
|
421
421
|
let (_, r) = run(&s);
|
|
422
422
|
assert!(!provedFn(&r, "bump"), "{r:?}");
|
|
423
423
|
}
|
|
424
|
+
|
|
425
|
+
#[test]
|
|
426
|
+
fn a_variable_compared_by_ref_same_is_never_updated_in_place() {
|
|
427
|
+
// Written in place, `c`'s cell would hold the new version, and `ref.same(c, new)` would
|
|
428
|
+
// say nothing changed. std's `same` (std/ref.plum) makes its arguments shared.
|
|
429
|
+
let s = format!(
|
|
430
|
+
"{CELL}fun same[T](a: T, b: T) -> Bool = todo\n\
|
|
431
|
+
fun probe(c: Cell) -> Cell =\n ok := same(c, Cell(label: \"x\", n: 0))\n Cell(..c, n: 1)\n\
|
|
432
|
+
fun go() -> Cell = probe(Cell(label: \"m\", n: 0))\n"
|
|
433
|
+
);
|
|
434
|
+
let mut src = plum_test_support::parseRawSource(&s);
|
|
435
|
+
for i in &mut src.items {
|
|
436
|
+
if let Item::Fn(f) = i {
|
|
437
|
+
if f.name == "same" {
|
|
438
|
+
f.file = "lib/std/ref.plum".to_string();
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
let r = markUnique(&mut src);
|
|
443
|
+
assert!(!provedFn(&r, "probe"), "{r:?}");
|
|
444
|
+
assert!(whyNot(&r, "probe").contains("ref.same"), "{r:?}");
|
|
445
|
+
// The same fn without `same` is proved: the call above is what blocks it.
|
|
446
|
+
let plain = format!(
|
|
447
|
+
"{CELL}fun probe(c: Cell) -> Cell =\n ok := c.n == 0\n Cell(..c, n: 1)\n\
|
|
448
|
+
fun go() -> Cell = probe(Cell(label: \"m\", n: 0))\n"
|
|
449
|
+
);
|
|
450
|
+
let (_, r) = run(&plain);
|
|
451
|
+
assert!(provedFn(&r, "probe"), "{r:?}");
|
|
452
|
+
}
|
compiler/wasm-codegen/src/context.rs
CHANGED
|
@@ -281,6 +281,8 @@ pub(crate) struct GenState {
|
|
|
281
281
|
pub(crate) value_helpers: HashMap<String, u32>,
|
|
282
282
|
/// Per-compile facts (the source file `x!` crash messages name).
|
|
283
283
|
pub(crate) err_info: ErrInfo,
|
|
284
|
+
/// The global names of std's `ref.same` (std/ref.plum): its calls compile to one `ref.eq`.
|
|
285
|
+
pub(crate) same_fns: std::collections::HashSet<String>,
|
|
284
286
|
/// The program's traits.
|
|
285
287
|
pub(crate) traits: Option<std::rc::Rc<plum_checker::traits::Traits>>,
|
|
286
288
|
/// (trait object type, method) -> its dispatcher (see `traits.rs`).
|
compiler/wasm-codegen/src/driver.rs
CHANGED
|
@@ -269,6 +269,14 @@ impl<'a> Setup<'a> {
|
|
|
269
269
|
let Setup { source, base_types, inst_types, enum_variants, enum_params, eg, units, instantiations, type_apps, type_funs, .. } = self;
|
|
270
270
|
// ---- collect the concrete generic types the program uses ----
|
|
271
271
|
withGen(|s| {
|
|
272
|
+
s.same_fns = source
|
|
273
|
+
.items
|
|
274
|
+
.iter()
|
|
275
|
+
.filter_map(|i| match i {
|
|
276
|
+
ast::Item::Fn(f) if crate::intrinsics::isSameFn(f) => Some(f.name.clone()),
|
|
277
|
+
_ => None,
|
|
278
|
+
})
|
|
279
|
+
.collect();
|
|
272
280
|
let v = &mut s.value_enums;
|
|
273
281
|
for item in &source.items {
|
|
274
282
|
if let ast::Item::Enum(e) = item {
|
compiler/wasm-codegen/src/expr.rs
CHANGED
|
@@ -378,8 +378,17 @@ pub(crate) fn compileExpr(
|
|
|
378
378
|
} else {
|
|
379
379
|
let (func_idx, sig) = resolveCallee(ctx, expr, false, &call.name)
|
|
380
380
|
.ok_or_else(|| format!("unknown function '{}'", call.name))?;
|
|
381
|
+
if withGen(|s| s.same_fns.contains(&call.name)) && call.args.len() == 2 && sig.params.len() == 2 {
|
|
382
|
+
// `ref.same(a, b)` in line: one `ref.eq` (see `intrinsics::compileSameFnBody`).
|
|
383
|
+
for (arg, vt) in call.args.iter().zip(&sig.params) {
|
|
384
|
+
compileExpr(argExprOf(arg), body, ctx, state)?;
|
|
385
|
+
crate::intrinsics::castToEq(vt, body);
|
|
386
|
+
}
|
|
387
|
+
Instruction::RefEq.encode(body);
|
|
388
|
+
} else {
|
|
381
|
-
|
|
389
|
+
compileCallArgs(&call.name, &call.args, sig, body, ctx, state)?;
|
|
382
|
-
|
|
390
|
+
emitCall(func_idx, sig, call.tail, expr, body, ctx);
|
|
391
|
+
}
|
|
383
392
|
}
|
|
384
393
|
}
|
|
385
394
|
ast::Expr { kind: ast::ExprKind::Self_, .. } => {
|
compiler/wasm-codegen/src/intrinsics.rs
CHANGED
|
@@ -14,6 +14,9 @@ pub(crate) fn compileIntrinsicFnBody(f: &ast::Fn, subst: &Subst) -> Option<Vec<u
|
|
|
14
14
|
if isMemFn(f) {
|
|
15
15
|
return compileMemIntrinsicFnBody(f);
|
|
16
16
|
}
|
|
17
|
+
if isSameFn(f) {
|
|
18
|
+
return compileSameFnBody(subst);
|
|
19
|
+
}
|
|
17
20
|
if let Some(recv) = f.type_param.as_deref() {
|
|
18
21
|
if isArraySpecialization(recv) {
|
|
19
22
|
return compileArrayIntrinsicFnBody(f, subst);
|
|
@@ -43,6 +46,50 @@ pub(crate) fn typeNameBody(f: &ast::Fn, subst: &Subst) -> ast::Fn {
|
|
|
43
46
|
g
|
|
44
47
|
}
|
|
45
48
|
|
|
49
|
+
/// `ref.same[T](a, b)` (std/ref.plum): reference identity.
|
|
50
|
+
pub(crate) fn isSameFn(f: &ast::Fn) -> bool {
|
|
51
|
+
f.type_param.is_none()
|
|
52
|
+
&& plum_core::modules::sourceFnName(&f.name) == "same"
|
|
53
|
+
&& f.file.replace('\\', "/").ends_with("std/ref.plum")
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/// The body of `same[T]` for one `T`: `ref.eq` of its two parameters (locals 0 and 1). The
|
|
57
|
+
/// checker lets only heap types through (see `plum_checker::identity`), so each parameter is
|
|
58
|
+
/// one reference: a concrete heap type is already an `eqref`, an `anyref` (a trait object,
|
|
59
|
+
/// a closure) is cast to one first.
|
|
60
|
+
pub(crate) fn compileSameFnBody(subst: &Subst) -> Option<Vec<u8>> {
|
|
61
|
+
let t = subst.get("T")?;
|
|
62
|
+
let vt = {
|
|
63
|
+
let g = gcTypes();
|
|
64
|
+
if leafCount(t) != 1 {
|
|
65
|
+
return None;
|
|
66
|
+
}
|
|
67
|
+
plumTypeToGcValtype(t, &g)
|
|
68
|
+
};
|
|
69
|
+
if !matches!(vt, ValType::Ref(_)) {
|
|
70
|
+
return None;
|
|
71
|
+
}
|
|
72
|
+
let mut body = vec![0u8];
|
|
73
|
+
for local in 0..2 {
|
|
74
|
+
Instruction::LocalGet(local).encode(&mut body);
|
|
75
|
+
castToEq(&vt, &mut body);
|
|
76
|
+
}
|
|
77
|
+
Instruction::RefEq.encode(&mut body);
|
|
78
|
+
Instruction::End.encode(&mut body);
|
|
79
|
+
Some(body)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/// After a value of wasm type `vt` is pushed: makes it an `eqref` for `ref.eq`. A concrete
|
|
83
|
+
/// heap type already is one; an `anyref` (a trait object, a closure) is cast.
|
|
84
|
+
pub(crate) fn castToEq(vt: &ValType, body: &mut Vec<u8>) {
|
|
85
|
+
if let ValType::Ref(r) = vt {
|
|
86
|
+
if !matches!(r.heap_type, HeapType::Concrete(_)) {
|
|
87
|
+
Instruction::RefCastNullable(HeapType::Abstract { shared: false, ty: wasm_encoder::AbstractHeapType::Eq })
|
|
88
|
+
.encode(body);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
46
93
|
/// A function of the std module `mem` (`std/mem.plum`): its bodies are intrinsics.
|
|
47
94
|
pub(crate) fn isMemFn(f: &ast::Fn) -> bool {
|
|
48
95
|
f.type_param.is_none() && f.file.replace('\\', "/").ends_with("std/mem.plum")
|
docs/std.md
CHANGED
|
@@ -15,7 +15,7 @@ The [game engine](game.md) has its own page.
|
|
|
15
15
|
| [`Option`, `Result`](#option-and-result) | missing values and failures |
|
|
16
16
|
| [`Json`](#json) | reading and writing JSON |
|
|
17
17
|
| [`os`, `http`](#files-and-network) | files and the network |
|
|
18
|
-
| [`Time`, `Random`, `Uuid`, `base64`, `Aabb`](#utilities) | utilities |
|
|
18
|
+
| [`Time`, `Random`, `Uuid`, `base64`, `Aabb`, `ref`](#utilities) | utilities |
|
|
19
19
|
| [`testing`](#testing) | helpers for tests |
|
|
20
20
|
| [`game/Store`](#game-state-store) | a game's state as a `Reducer`, and its messages |
|
|
21
21
|
|
|
@@ -183,6 +183,7 @@ fun main(io: Io) =
|
|
|
183
183
|
- **`Uuid`:** `Uuid.v4(rng)`, `Uuid.fromStr`, `Uuid.isValid`
|
|
184
184
|
- **`base64`:** `base64.encode`, `base64.decode`, `base64.encodeURL`
|
|
185
185
|
- **`Aabb`:** an axis-aligned box, corners included: `Aabb.of(x, y, w, h)`, `width`, `height`, `center`, `overlaps`, `contains`, `containsPoint`, `union`, `distSq`, `rayEntry`
|
|
186
|
+
- **`ref`:** `ref.same(a, b)` is true when `a` and `b` are the very same object, not just equal ones: `ref.same(a, Box(..a))` is false. Only for values on the heap (a struct that isn't flat, an enum, a trait object, `Str`, `List`, ...); the checker rejects a scalar, a flat struct or a function. A persistent structure uses it to keep what didn't change: the scene tree's `input` and `Game`'s tick return a node as it was when its actor came back as the same object (see [the game engine](game.md)). The compiler never updates a value compared by `ref.same` in place, so an update always shows up as another object
|
|
186
187
|
- **`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)
|
|
187
188
|
- **`io.nowMicros()`:** a wall clock in microseconds since the Unix epoch, as a `Float`, on every host
|
|
188
189
|
|
std/ref.plum
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
module std
|
|
2
|
+
|
|
3
|
+
import std/Bool
|
|
4
|
+
|
|
5
|
+
# Reference identity: whether two values are the very same object, not just equal ones.
|
|
6
|
+
#
|
|
7
|
+
# ref.same(a, a) # true
|
|
8
|
+
# ref.same(a, Box(..a)) # false: a copy is another object, however equal
|
|
9
|
+
#
|
|
10
|
+
# It is what a persistent structure uses to keep what did not change: a walk that rebuilds
|
|
11
|
+
# a node only when a part of it is another object returns the old node otherwise, so an
|
|
12
|
+
# unchanged tree comes back as the very same tree (std/game/scene/SceneTree's `input`,
|
|
13
|
+
# std/game/Game's tick).
|
|
14
|
+
#
|
|
15
|
+
# Only for values that live on the heap: a struct that is not flat, an enum, a trait object,
|
|
16
|
+
# `Str`, `Slice`, `List`, `Array` and the like. The checker rejects a scalar (`Int`,
|
|
17
|
+
# `Float`, `Bool`, `Byte`), `Unit`, a flat struct (copied by value, so it has no identity),
|
|
18
|
+
# a function, and a generic that one of its instantiations makes any of those.
|
|
19
|
+
#
|
|
20
|
+
# In-place updates (FBIP) never fool it: a variable passed to `same` is never updated in
|
|
21
|
+
# place, so a method that changes a field of it always returns another object (see
|
|
22
|
+
# `plum_core::uniqueness`).
|
|
23
|
+
fun same[T](a: T, b: T) -> Bool =
|
|
24
|
+
todo
|
tests/core/ref_same.plum
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Str
|
|
3
|
+
import std/Bool
|
|
4
|
+
import std/Option
|
|
5
|
+
import std/List
|
|
6
|
+
import std/ref
|
|
7
|
+
|
|
8
|
+
# `ref.same(a, b)`: the very same object, not an equal one. The sweep runs this file with
|
|
9
|
+
# the default, `--no-fbip` and `--no-fusion`; every answer must be the same in all three
|
|
10
|
+
# (an in-place update must never make an updated value look the same as the old one).
|
|
11
|
+
|
|
12
|
+
struct Cell(label: Str, n: Int) =
|
|
13
|
+
fun kept(self) -> Cell = self
|
|
14
|
+
fun bumped(self) -> Cell = Cell(..self, n: self.n + 1)
|
|
15
|
+
# `self` when nothing changes, else a new cell.
|
|
16
|
+
fun toward(self, k: Int) -> Cell = if self.n == k then self else Cell(..self, n: k)
|
|
17
|
+
|
|
18
|
+
trait Thing =
|
|
19
|
+
fun key(self) -> Int
|
|
20
|
+
fun moved(self) -> Self = self
|
|
21
|
+
|
|
22
|
+
struct Rock(id: Int) is Thing =
|
|
23
|
+
fun key(self) -> Int = self.id
|
|
24
|
+
|
|
25
|
+
struct Ball(id: Int, y: Int) is Thing =
|
|
26
|
+
fun key(self) -> Int = self.id
|
|
27
|
+
fun moved(self) -> Ball = Ball(..self, y: self.y + 1)
|
|
28
|
+
|
|
29
|
+
enum Chain =
|
|
30
|
+
| End
|
|
31
|
+
| Link(v: Cell, next: Chain)
|
|
32
|
+
|
|
33
|
+
fun fresh() -> Cell = Cell(label: "a", n: 1)
|
|
34
|
+
|
|
35
|
+
# A cell updated where nothing else holds it, then compared with what came in.
|
|
36
|
+
fun changedAfter(c: Cell) -> Bool =
|
|
37
|
+
d := c.bumped()
|
|
38
|
+
!ref.same(c, d)
|
|
39
|
+
|
|
40
|
+
# The chain with every cell at `k`, sharing every link whose cell did not change.
|
|
41
|
+
fun toward(xs: Chain, k: Int) -> Chain = match xs
|
|
42
|
+
End => xs
|
|
43
|
+
Link(v, next) =>
|
|
44
|
+
v2 := v.toward(k)
|
|
45
|
+
n2 := toward(next, k)
|
|
46
|
+
if ref.same(v2, v) && ref.same(n2, next) then xs else Link(v: v2, next: n2)
|
|
47
|
+
|
|
48
|
+
fun sumOf(xs: Chain) -> Int = match xs
|
|
49
|
+
End => 0
|
|
50
|
+
Link(v, next) => v.n + sumOf(next)
|
|
51
|
+
|
|
52
|
+
test "a value is the same as itself, and a copy or an equal value is not"
|
|
53
|
+
a := fresh()
|
|
54
|
+
b := a
|
|
55
|
+
assert ref.same(a, b)
|
|
56
|
+
assert ref.same(a, a.kept())
|
|
57
|
+
assert !ref.same(a, Cell(..a))
|
|
58
|
+
assert !ref.same(a, fresh())
|
|
59
|
+
assert !ref.same(a, a.bumped())
|
|
60
|
+
|
|
61
|
+
test "an update where nothing else holds the value is still another object"
|
|
62
|
+
assert changedAfter(fresh())
|
|
63
|
+
assert changedAfter(Cell(label: "b", n: 7))
|
|
64
|
+
|
|
65
|
+
test "strings, lists and enum values"
|
|
66
|
+
s := "plum"
|
|
67
|
+
assert ref.same(s, s)
|
|
68
|
+
xs: List[Int] := [1, 2, 3]
|
|
69
|
+
assert ref.same(xs, xs)
|
|
70
|
+
assert !ref.same(xs, [1, 2, 3])
|
|
71
|
+
e: Chain := End
|
|
72
|
+
assert ref.same(e, End)
|
|
73
|
+
|
|
74
|
+
test "trait objects: a default method that returns self keeps the object"
|
|
75
|
+
r: Thing := Rock(id: 1)
|
|
76
|
+
assert ref.same(r, r.moved())
|
|
77
|
+
b: Thing := Ball(id: 2, y: 0)
|
|
78
|
+
m := b.moved()
|
|
79
|
+
assert !ref.same(b, m)
|
|
80
|
+
assert m.key() == 2
|
|
81
|
+
|
|
82
|
+
test "a walk that shares what did not change"
|
|
83
|
+
xs: Chain := Link(v: Cell(label: "a", n: 3), next: Link(v: Cell(label: "b", n: 3), next: End))
|
|
84
|
+
assert ref.same(toward(xs, 3), xs)
|
|
85
|
+
ys := toward(xs, 4)
|
|
86
|
+
assert !ref.same(ys, xs)
|
|
87
|
+
assert sumOf(ys) == 8
|
|
88
|
+
assert sumOf(xs) == 6
|
|
89
|
+
# Only the second changes: the first link is rebuilt over it, the end is shared.
|
|
90
|
+
zs: Chain := Link(v: Cell(label: "a", n: 4), next: Link(v: Cell(label: "b", n: 3), next: End))
|
|
91
|
+
ws := toward(zs, 4)
|
|
92
|
+
assert !ref.same(ws, zs)
|
|
93
|
+
assert sumOf(ws) == 8
|
|
94
|
+
assert sumOf(zs) == 7
|