plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
db5f7b1
— Peter John
2026-11-10T14:38:27+05:30
@sameRef(a, b) replaces std/ref's ref.same
- compiler/checker/src/identity.rs +5 -12
- compiler/checker/src/infer.rs +1 -1
- compiler/checker/src/program.rs +0 -10
- compiler/checker/src/state.rs +0 -3
- compiler/checker/tests/checker/features/identity.rs +27 -7
- compiler/checker/tests/checker/traits_tests.rs +1 -1
- compiler/core/src/compile_builtins.rs +113 -10
- compiler/core/src/lower.rs +1 -0
- compiler/core/src/parser.rs +8 -0
- compiler/core/src/purity.rs +2 -2
- compiler/core/src/uniqueness.rs +3 -20
- compiler/core/tests/core/traits_parse_test.rs +19 -0
- compiler/core/tests/core/uniqueness_test.rs +19 -11
- compiler/tooling/tree-sitter-plum/test/corpus/traits.txt +47 -0
- compiler/wasm-codegen/src/context.rs +0 -2
- compiler/wasm-codegen/src/driver.rs +0 -8
- compiler/wasm-codegen/src/expr.rs +2 -2
- compiler/wasm-codegen/src/intrinsics.rs +2 -9
- std/collections/RoseTree.plum +3 -4
- std/game/Game.plum +7 -8
- std/game/SceneTree.plum +15 -16
- std/ref.plum +0 -24
- tests/core/{ref_same.plum → same_ref.plum} +17 -18
compiler/checker/src/identity.rs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
//! Reference identity,
|
|
1
|
+
//! Reference identity, the built-in `@sameRef(a, b)`: whether two values are the
|
|
2
2
|
//! very same object. Codegen makes it one `ref.eq` (`plum_wasm_codegen::intrinsics`), so it
|
|
3
3
|
//! is only for values that are one heap reference. The rule, at every call: the argument
|
|
4
4
|
//! type must not be a scalar (`Int`, `Float`, `Bool`, `Byte`), `Unit`, `Io`, a flat struct
|
|
@@ -6,28 +6,21 @@
|
|
|
6
6
|
//! instantiation could make any of those).
|
|
7
7
|
//!
|
|
8
8
|
//! In-place updates never make two different contents look the same: a variable passed to
|
|
9
|
-
//! `
|
|
9
|
+
//! `@sameRef` is never updated in place (`plum_core::uniqueness`).
|
|
10
10
|
|
|
11
11
|
use crate::*;
|
|
12
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 `
|
|
13
|
+
/// For a call of `@sameRef`: an error when its argument type (after `binds`) is not one heap
|
|
21
14
|
/// reference. Any other call passes.
|
|
22
15
|
pub(crate) fn checkSameArgs(name: &str, params: &[PlumType], binds: &Binds, ctx: &CheckCtx) -> Result<(), String> {
|
|
23
|
-
if !
|
|
16
|
+
if name != plum_core::compile_builtins::SAME_REF_FN {
|
|
24
17
|
return Ok(());
|
|
25
18
|
}
|
|
26
19
|
let Some(p) = params.first() else { return Ok(()) };
|
|
27
20
|
let t = substVars(p, binds);
|
|
28
21
|
match whyNotHeap(&t, ctx) {
|
|
29
22
|
Some(why) => Err(format!(
|
|
30
|
-
"
|
|
23
|
+
"@sameRef compares heap objects by identity, and {t} {why}; compare values with =="
|
|
31
24
|
)),
|
|
32
25
|
None => Ok(()),
|
|
33
26
|
}
|
compiler/checker/src/infer.rs
CHANGED
|
@@ -469,7 +469,7 @@ pub(crate) fn inferExprInner(
|
|
|
469
469
|
ast::Expr { kind: ast::ExprKind::FnCall(call), .. } => {
|
|
470
470
|
// `@name(..)` left as a call by the parser: an unknown built-in, or a known one
|
|
471
471
|
// with the wrong arguments (`plum_core::compile_builtins`).
|
|
472
|
-
if let Some(e) = plum_core::compile_builtins::error(
|
|
472
|
+
if let Some(e) = plum_core::compile_builtins::error(call) {
|
|
473
473
|
return Err(e);
|
|
474
474
|
}
|
|
475
475
|
// `Int(x)`/`Float(x)`/`Byte(x)` are builtin numeric conversions, not
|
compiler/checker/src/program.rs
CHANGED
|
@@ -248,16 +248,6 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
248
248
|
})
|
|
249
249
|
.collect()
|
|
250
250
|
});
|
|
251
|
-
withCheck(|s| {
|
|
252
|
-
*s.same_fns.borrow_mut() = source
|
|
253
|
-
.items
|
|
254
|
-
.iter()
|
|
255
|
-
.filter_map(|i| match i {
|
|
256
|
-
ast::Item::Fn(f) if crate::identity::isSameFn(f) => Some(f.name.clone()),
|
|
257
|
-
_ => None,
|
|
258
|
-
})
|
|
259
|
-
.collect()
|
|
260
|
-
});
|
|
261
251
|
errors.extend(checkTraitDecls(source, &traits, &methods));
|
|
262
252
|
errors.extend(selfOutsideTrait(source));
|
|
263
253
|
// Shared fields of subtyped traits; codegen fills them in (see `addTraitParams`).
|
compiler/checker/src/state.rs
CHANGED
|
@@ -72,9 +72,6 @@ pub(crate) struct CheckState {
|
|
|
72
72
|
/// `CheckError` made from it is a `DiagKind::Resolution`. Saved, restored and cleared
|
|
73
73
|
/// together with `err_pos`.
|
|
74
74
|
pub(crate) err_resolution: Cell<bool>,
|
|
75
|
-
/// The global names of std's `ref.same` (std/ref.plum), whose argument type the checker
|
|
76
|
-
/// limits to heap types (`identity::checkSameArgs`).
|
|
77
|
-
pub(crate) same_fns: RefCell<std::collections::HashSet<String>>,
|
|
78
75
|
/// Generic types written with the wrong number of type arguments, as (name, the count
|
|
79
76
|
/// written): `declchecks::checkBareGenericTypes` reports each, and `plumTypeFromAstG`
|
|
80
77
|
/// turns such a type into a wildcard so the one mistake has no follow-up mismatches.
|
compiler/checker/tests/checker/features/identity.rs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
//! `
|
|
1
|
+
//! `@sameRef(a, b)`: reference identity, only for heap values.
|
|
2
2
|
use plum_checker::checkSource;
|
|
3
3
|
|
|
4
4
|
fn run(body: &str) -> Result<(), String> {
|
|
5
5
|
let src = format!(
|
|
6
|
-
"import std/Int\nimport std/Float\nimport std/Str\nimport std/collections/List\
|
|
6
|
+
"import std/Int\nimport std/Float\nimport std/Str\nimport std/collections/List\n\n\
|
|
7
7
|
struct Flat(x: Int, y: Int)\nstruct Boxed(x: Int, s: Str)\n\
|
|
8
8
|
trait Named =\n fun name(self) -> Str\n\
|
|
9
9
|
struct Dog(s: Str) is Named =\n fun name(self) -> Str = self.s\n\
|
|
@@ -16,13 +16,13 @@ fn run(body: &str) -> Result<(), String> {
|
|
|
16
16
|
#[test]
|
|
17
17
|
fn heap_values_may_be_compared() {
|
|
18
18
|
run("fun f(a: Boxed, d: Named, t: Tree, s: Str, xs: List[Int]) -> Bool =\n \
|
|
19
|
-
|
|
19
|
+
@sameRef(a, a) && @sameRef(d, d) && @sameRef(t, Leaf) && @sameRef(s, s) && @sameRef(xs, xs)\n")
|
|
20
20
|
.unwrap();
|
|
21
21
|
}
|
|
22
22
|
|
|
23
23
|
#[test]
|
|
24
24
|
fn a_generic_instantiated_with_a_heap_type_is_accepted() {
|
|
25
|
-
run("fun g[T](a: T) -> Bool =
|
|
25
|
+
run("fun g[T](a: T) -> Bool = @sameRef(a, a)\n\nfun f(b: Boxed) -> Bool = g(b)\n").unwrap();
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
#[test]
|
|
@@ -34,13 +34,33 @@ fn scalars_flat_structs_and_functions_are_rejected() {
|
|
|
34
34
|
("Flat(x: 1, y: 2), Flat(x: 1, y: 2)", "Flat is a flat struct"),
|
|
35
35
|
("|x: Int| x, |x: Int| x", "is a function"),
|
|
36
36
|
] {
|
|
37
|
-
let e = run(&format!("fun f() -> Bool =
|
|
37
|
+
let e = run(&format!("fun f() -> Bool = @sameRef({arg})\n")).unwrap_err();
|
|
38
|
-
assert!(e.contains("
|
|
38
|
+
assert!(e.contains("@sameRef compares heap objects by identity") && e.contains(why), "{arg}: {e}");
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
#[test]
|
|
43
43
|
fn a_generic_instantiated_with_a_scalar_is_rejected() {
|
|
44
|
-
let e = run("fun g[T](a: T) -> Bool =
|
|
44
|
+
let e = run("fun g[T](a: T) -> Bool = @sameRef(a, a)\n\nfun f() -> Bool = g(3)\n").unwrap_err();
|
|
45
45
|
assert!(e.contains("Int is a scalar"), "{e}");
|
|
46
46
|
}
|
|
47
|
+
|
|
48
|
+
#[test]
|
|
49
|
+
fn the_wrong_arguments_are_rejected() {
|
|
50
|
+
for body in ["@sameRef(a)", "@sameRef(a, a, a)", "@sameRef(a, List[Int])", "@sameRef()"] {
|
|
51
|
+
let e = run(&format!("fun f(a: Boxed) -> Bool = {body}\n")).unwrap_err();
|
|
52
|
+
assert!(e.contains("@sameRef takes two values, e.g. @sameRef(a, b)"), "{body}: {e}");
|
|
53
|
+
}
|
|
54
|
+
let e = run("fun f(a: Boxed, t: Tree) -> Bool = @sameRef(a, t)\n").unwrap_err();
|
|
55
|
+
assert!(e.contains("mismatch") || e.contains("expected"), "{e}");
|
|
56
|
+
let e = run("fun f(a: Boxed) -> Int = @sameRef(a, a)\n").unwrap_err();
|
|
57
|
+
assert!(e.contains("Bool"), "{e}");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/// The old spelling is gone with std/ref.plum: `ref` is an undefined name, and a function a
|
|
61
|
+
/// program calls `same` is an ordinary function.
|
|
62
|
+
#[test]
|
|
63
|
+
fn the_old_module_is_gone() {
|
|
64
|
+
assert!(run("fun f(a: Boxed) -> Bool = ref.same(a, a)\n").is_err());
|
|
65
|
+
run("fun same(a: Int, b: Int) -> Bool = a == b\n\nfun f() -> Bool = same(1, 2)\n").unwrap();
|
|
66
|
+
}
|
compiler/checker/tests/checker/traits_tests.rs
CHANGED
|
@@ -441,7 +441,7 @@ fn traitStatics() {
|
|
|
441
441
|
#[test]
|
|
442
442
|
fn compileTimeBuiltins() {
|
|
443
443
|
ok("fun main() =\n s: Str := @typeName(Int)\n show(s)\n");
|
|
444
|
-
fails("fun main() =\n show(@nope(Int))\n", "unknown built-in @nope; the built-ins are @typeName");
|
|
444
|
+
fails("fun main() =\n show(@nope(Int))\n", "unknown built-in @nope; the built-ins are @typeName, @sameRef");
|
|
445
445
|
fails("fun main() =\n x := 1\n show(@typeName(x))\n", "@typeName takes one type, e.g. @typeName(Self)");
|
|
446
446
|
fails("fun main() =\n show(@typeName(Int, Str))\n", "@typeName takes one type");
|
|
447
447
|
fails("fun main() =\n n: Int := @typeName(Int)\n show(\"{n}\")\n", "type mismatch");
|
compiler/core/src/compile_builtins.rs
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
//!
|
|
1
|
+
//! Built-ins: `@name(args)`, Zig-style. Each is in `BUILTINS`, with what it takes. The
|
|
2
|
-
//!
|
|
2
|
+
//! parser lowers one that takes a type (`lower`); one that takes values stays a call named
|
|
3
|
-
//!
|
|
3
|
+
//! `@name`, of a function the compiler declares itself (`declare`) and codegen fills in.
|
|
4
|
+
//! A call that names no built-in, or gives one the wrong arguments, is the checker's error
|
|
5
|
+
//! (`error`).
|
|
4
6
|
|
|
5
7
|
use crate::ast::*;
|
|
6
8
|
|
|
@@ -9,6 +11,8 @@ use crate::ast::*;
|
|
|
9
11
|
pub enum Takes {
|
|
10
12
|
/// Exactly one type.
|
|
11
13
|
OneType,
|
|
14
|
+
/// This many values.
|
|
15
|
+
Values(usize),
|
|
12
16
|
}
|
|
13
17
|
|
|
14
18
|
/// The built-ins, with what each takes and an example.
|
|
@@ -18,8 +22,93 @@ pub const BUILTINS: &[(&str, Takes, &str)] = &[
|
|
|
18
22
|
// `@typeName(Self)` is each implementer's own name. It is std's
|
|
19
23
|
// `str.typeName[T]()`, resolved per instantiation.
|
|
20
24
|
("typeName", Takes::OneType, "@typeName(Self)"),
|
|
25
|
+
// `@sameRef(a, b)`: whether `a` and `b` are the very same heap object (one `ref.eq`).
|
|
26
|
+
// Only for heap types (`plum_checker::identity`); a variable passed to it is never
|
|
27
|
+
// updated in place (`uniqueness`).
|
|
28
|
+
(SAME_REF, Takes::Values(2), "@sameRef(a, b)"),
|
|
21
29
|
];
|
|
22
30
|
|
|
31
|
+
/// `@sameRef` without its `@`.
|
|
32
|
+
pub const SAME_REF: &str = "sameRef";
|
|
33
|
+
/// The name of `@sameRef`'s calls and of its declaration.
|
|
34
|
+
pub const SAME_REF_FN: &str = "@sameRef";
|
|
35
|
+
|
|
36
|
+
/// What a value built-in is declared as: `(name, type parameters, parameter types, result)`.
|
|
37
|
+
const DECLS: &[(&str, &[&str], &[&str], &str)] = &[(SAME_REF_FN, &["T"], &["T", "T"], "Bool")];
|
|
38
|
+
|
|
39
|
+
/// How a built-in takes its arguments; `None` for a name that is not one.
|
|
40
|
+
pub fn takes(name: &str) -> Option<Takes> {
|
|
41
|
+
BUILTINS.iter().find(|(n, _, _)| *n == name).map(|e| e.1)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/// Whether `f` is the declaration of a value built-in (`@sameRef`), made by `declare`.
|
|
45
|
+
pub fn isDeclared(f: &Fn) -> bool {
|
|
46
|
+
f.type_param.is_none() && f.name.starts_with('@')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/// Whether `f` is the declaration of `@sameRef`.
|
|
50
|
+
pub fn isSameRef(f: &Fn) -> bool {
|
|
51
|
+
f.type_param.is_none() && f.name == SAME_REF_FN
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/// Declares each value built-in `source` calls and does not declare yet: a function named
|
|
55
|
+
/// `@name` with the built-in's signature and no body of its own. Every pass then sees its
|
|
56
|
+
/// calls as calls of that function; codegen supplies the instructions.
|
|
57
|
+
pub fn declare(source: &mut Source) {
|
|
58
|
+
let mut used: Vec<&'static str> = Vec::new();
|
|
59
|
+
{
|
|
60
|
+
let mut note = |e: &Expr| {
|
|
61
|
+
if let ExprKind::FnCall(c) = &e.kind {
|
|
62
|
+
if let Some(d) = DECLS.iter().find(|d| d.0 == c.name) {
|
|
63
|
+
if !used.contains(&d.0) {
|
|
64
|
+
used.push(d.0);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
for item in &source.items {
|
|
70
|
+
match item {
|
|
71
|
+
Item::Fn(f) => match &f.body {
|
|
72
|
+
FnBody::Block(b) => crate::visit::walkBlockRef(b, &mut note),
|
|
73
|
+
FnBody::Expr(e) => crate::visit::walkRef(e, &mut note),
|
|
74
|
+
FnBody::Extern => {}
|
|
75
|
+
},
|
|
76
|
+
Item::Const(c) => crate::visit::walkRef(&c.value, &mut note),
|
|
77
|
+
Item::Test(t) => crate::visit::walkBlockRef(&t.body, &mut note),
|
|
78
|
+
Item::Enum(_) | Item::Trait(_) => {}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
let ty = |n: &str| Type { name: n.to_string(), generics: Vec::new() };
|
|
83
|
+
for (name, generics, params, ret) in DECLS {
|
|
84
|
+
let declared = source.items.iter().any(|i| matches!(i, Item::Fn(f) if f.type_param.is_none() && f.name == *name));
|
|
85
|
+
if declared || !used.contains(name) {
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
source.items.push(Item::Fn(Fn {
|
|
89
|
+
name: name.to_string(),
|
|
90
|
+
file: String::new(),
|
|
91
|
+
line: 0,
|
|
92
|
+
column: 0,
|
|
93
|
+
type_param: None,
|
|
94
|
+
generics: generics.iter().map(|g| g.to_string()).collect(),
|
|
95
|
+
bounds: Vec::new(),
|
|
96
|
+
is_extern: false,
|
|
97
|
+
is_export: false,
|
|
98
|
+
is_test: false,
|
|
99
|
+
is_fip: false,
|
|
100
|
+
has_self: false,
|
|
101
|
+
params: params
|
|
102
|
+
.iter()
|
|
103
|
+
.enumerate()
|
|
104
|
+
.map(|(i, t)| Param { name: ["a", "b"][i].to_string(), ty: ParamType::Type(ty(t)), default: None })
|
|
105
|
+
.collect(),
|
|
106
|
+
returns: (*ret != "Unit").then(|| ty(ret)),
|
|
107
|
+
body: FnBody::Block(Block { stmts: vec![Stmt::Todo] }),
|
|
108
|
+
}));
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
23
112
|
/// One argument as written: a type or a value.
|
|
24
113
|
#[derive(Debug, Clone)]
|
|
25
114
|
pub enum BuiltinArg {
|
|
@@ -57,12 +146,26 @@ pub fn lower(name: &str, args: Vec<BuiltinArg>, line: usize, column: usize) -> E
|
|
|
57
146
|
}
|
|
58
147
|
|
|
59
148
|
/// The error for a call named `@name` that reached the checker: an unknown built-in, or
|
|
60
|
-
/// one given the wrong arguments.
|
|
149
|
+
/// one given the wrong arguments. `None` for any other call, and for a value built-in given
|
|
150
|
+
/// the right number of values (the checker then types it like any call).
|
|
61
|
-
pub fn error(
|
|
151
|
+
pub fn error(call: &FnCall) -> Option<String> {
|
|
62
|
-
let bare = name.strip_prefix('@')?;
|
|
152
|
+
let bare = call.name.strip_prefix('@')?;
|
|
63
153
|
let known: Vec<String> = BUILTINS.iter().map(|(n, _, _)| format!("@{n}")).collect();
|
|
64
|
-
|
|
154
|
+
match BUILTINS.iter().find(|(n, _, _)| *n == bare) {
|
|
65
|
-
Some((_, Takes::OneType, eg)) => format!("@{bare} takes one type, e.g. {eg}"),
|
|
155
|
+
Some((_, Takes::OneType, eg)) => Some(format!("@{bare} takes one type, e.g. {eg}")),
|
|
156
|
+
Some((_, Takes::Values(n), eg)) => {
|
|
157
|
+
let positional = call.args.iter().all(|a| matches!(a, Arg::Positional(_)));
|
|
158
|
+
if call.args.len() == *n && call.type_args.is_empty() && positional {
|
|
159
|
+
return None;
|
|
160
|
+
}
|
|
161
|
+
let count = match n {
|
|
162
|
+
0 => "no arguments".to_string(),
|
|
163
|
+
1 => "one value".to_string(),
|
|
164
|
+
2 => "two values".to_string(),
|
|
165
|
+
n => format!("{n} values"),
|
|
166
|
+
};
|
|
167
|
+
Some(format!("@{bare} takes {count}, e.g. {eg}"))
|
|
168
|
+
}
|
|
66
|
-
None => format!("unknown built-in @{bare}; the built-ins are {}", known.join(", ")),
|
|
169
|
+
None => Some(format!("unknown built-in @{bare}; the built-ins are {}", known.join(", "))),
|
|
67
|
-
}
|
|
170
|
+
}
|
|
68
171
|
}
|
compiler/core/src/lower.rs
CHANGED
|
@@ -25,6 +25,7 @@ pub fn perFileDiag(source: &mut Source) -> Result<(), Vec<Diagnostic>> {
|
|
|
25
25
|
/// errors.
|
|
26
26
|
pub fn frontEndDiag(source: &mut Source) -> Result<(), Vec<Diagnostic>> {
|
|
27
27
|
crate::session::begin();
|
|
28
|
+
crate::compile_builtins::declare(source);
|
|
28
29
|
let pathErrors = crate::spread_paths::lowerSpreadPaths(source);
|
|
29
30
|
if !pathErrors.is_empty() {
|
|
30
31
|
return Err(pathErrors);
|
compiler/core/src/parser.rs
CHANGED
|
@@ -1596,10 +1596,18 @@ impl<'a> AstParser<'a> {
|
|
|
1596
1596
|
/// `@name(args)`: a compile-time built-in (`compile_builtins`).
|
|
1597
1597
|
fn parseBuiltinCall(&self, node: Node) -> Expr {
|
|
1598
1598
|
let name = node.child_by_field_name("name").map(|n| self.text(n)).unwrap_or_default();
|
|
1599
|
+
// A built-in that takes values reads a bare capitalised name (`End`) as the value
|
|
1600
|
+
// it is, not as a type.
|
|
1601
|
+
let values = matches!(crate::compile_builtins::takes(&name), Some(crate::compile_builtins::Takes::Values(_)));
|
|
1599
1602
|
let mut cursor = node.walk();
|
|
1600
1603
|
let args = node
|
|
1601
1604
|
.children_by_field_name("argument", &mut cursor)
|
|
1602
1605
|
.map(|a| match a.kind() {
|
|
1606
|
+
"type" if values && a.named_child_count() == 1 && a.named_child(0).is_some_and(|c| c.kind() == "type_identifier" && c.byte_range() == a.byte_range()) => {
|
|
1607
|
+
let mut e = Expr::TypeName(self.text(a));
|
|
1608
|
+
e.span = self.spanOf(a);
|
|
1609
|
+
crate::compile_builtins::BuiltinArg::Value(e)
|
|
1610
|
+
}
|
|
1603
1611
|
"type" => crate::compile_builtins::BuiltinArg::Type(self.parseType(a)),
|
|
1604
1612
|
_ => crate::compile_builtins::BuiltinArg::Value(self.parseExpression(self.unwrapExprNode(a))),
|
|
1605
1613
|
})
|
compiler/core/src/purity.rs
CHANGED
|
@@ -51,8 +51,8 @@ pub fn pureFns(src: &Source) -> HashSet<String> {
|
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
53
|
let mut info = analyse(f, &ctors, &receivers);
|
|
54
|
-
if crate::
|
|
54
|
+
if crate::compile_builtins::isSameRef(f) || crate::native::nativeOp(f).is_some() {
|
|
55
|
-
//
|
|
55
|
+
// `@sameRef` and std's native math ops: a `todo` body the compiler fills
|
|
56
56
|
// with one instruction (`ref.eq`, `f64.sqrt`, ...)
|
|
57
57
|
info.impure = false;
|
|
58
58
|
}
|
compiler/core/src/uniqueness.rs
CHANGED
|
@@ -519,9 +519,6 @@ struct An {
|
|
|
519
519
|
copyTypes: HashMap<String, String>,
|
|
520
520
|
/// Types and variants with a `mut` field.
|
|
521
521
|
mutTypes: HashSet<String>,
|
|
522
|
-
/// The global names of std's `ref.same` (std/ref.plum): a variable passed to it is never
|
|
523
|
-
/// unique, so what it is compared with by identity cannot have been written into its cell.
|
|
524
|
-
sameFns: HashSet<String>,
|
|
525
522
|
/// Variable checks in progress, and whether one of them has been answered by assuming it holds.
|
|
526
523
|
active: RefCell<HashSet<(usize, String, bool, bool)>>,
|
|
527
524
|
assumed: std::cell::Cell<bool>,
|
|
@@ -1312,10 +1309,10 @@ impl<'a> Scan<'a> {
|
|
|
1312
1309
|
let v = self.v.to_string();
|
|
1313
1310
|
let g = self.an.isFree(&c.name);
|
|
1314
1311
|
let bareCount = c.args.iter().filter(|a| self.bare(argExpr(a))).count();
|
|
1315
|
-
// `
|
|
1312
|
+
// `@sameRef(v, w)` compares `v` by identity: had `v`'s cell been written in place,
|
|
1316
1313
|
// `w` (its new version) would be the same object with other contents.
|
|
1317
|
-
if bareCount > 0 &&
|
|
1314
|
+
if bareCount > 0 && c.name == crate::compile_builtins::SAME_REF_FN {
|
|
1318
|
-
self.fail(format!("`{v}` is compared by identity (`
|
|
1315
|
+
self.fail(format!("`{v}` is compared by identity (`@sameRef`), so it is never updated in place"));
|
|
1319
1316
|
return;
|
|
1320
1317
|
}
|
|
1321
1318
|
for (k, a) in c.args.iter().enumerate() {
|
|
@@ -1667,12 +1664,6 @@ fn varTypes(u: &Unit) -> HashMap<String, Option<String>> {
|
|
|
1667
1664
|
/// (see `build`): the renamed name is defined nowhere.
|
|
1668
1665
|
const SHADOW_MARK: &str = "\u{0}shadow";
|
|
1669
1666
|
|
|
1670
|
-
/// Whether `f` is std's `ref.same` (std/ref.plum), under any module rename (`same@ref`).
|
|
1671
|
-
pub(crate) fn isSameFn(f: &Fn) -> bool {
|
|
1672
|
-
f.type_param.is_none()
|
|
1673
|
-
&& crate::modules::sourceFnName(&f.name) == "same"
|
|
1674
|
-
&& f.file.replace('\\', "/").ends_with("std/ref.plum")
|
|
1675
|
-
}
|
|
1676
1667
|
|
|
1677
1668
|
fn build(src: &Source) -> An {
|
|
1678
1669
|
let mut units: Vec<Unit> = Vec::new();
|
|
@@ -1905,14 +1896,6 @@ fn build(src: &Source) -> An {
|
|
|
1905
1896
|
varTy,
|
|
1906
1897
|
copyTypes,
|
|
1907
1898
|
mutTypes,
|
|
1908
|
-
sameFns: src
|
|
1909
|
-
.items
|
|
1910
|
-
.iter()
|
|
1911
|
-
.filter_map(|i| match i {
|
|
1912
|
-
Item::Fn(f) if isSameFn(f) => Some(f.name.clone()),
|
|
1913
|
-
_ => None,
|
|
1914
|
-
})
|
|
1915
|
-
.collect(),
|
|
1916
1899
|
active: RefCell::new(HashSet::new()),
|
|
1917
1900
|
assumed: std::cell::Cell::new(false),
|
|
1918
1901
|
};
|
compiler/core/tests/core/traits_parse_test.rs
CHANGED
|
@@ -201,3 +201,22 @@ fn compileTimeBuiltinCalls() {
|
|
|
201
201
|
assert_eq!(c.args.len(), 1);
|
|
202
202
|
assert_eq!(c.type_args, vec![named("Orb")]);
|
|
203
203
|
}
|
|
204
|
+
|
|
205
|
+
/// `@sameRef(a, b)` stays a call named `@sameRef`; a bare capitalised argument is the value
|
|
206
|
+
/// (a variant or a constant), not a type.
|
|
207
|
+
#[test]
|
|
208
|
+
fn valueBuiltinCalls() {
|
|
209
|
+
let s = plum_test_support::parseRawSource("fun f(t: Tree) -> Bool = @sameRef(t, Leaf)\n");
|
|
210
|
+
let FnBody::Expr(e) = &fnOf(&s, None, "f").body else { panic!("expr body") };
|
|
211
|
+
let ExprKind::FnCall(c) = &e.kind else { panic!("{e:?}") };
|
|
212
|
+
assert_eq!(c.name, "@sameRef");
|
|
213
|
+
assert!(c.type_args.is_empty());
|
|
214
|
+
let [Arg::Positional(a), Arg::Positional(b)] = &c.args[..] else { panic!("{c:?}") };
|
|
215
|
+
assert!(matches!(&a.kind, ExprKind::Var(n) if n == "t"));
|
|
216
|
+
assert!(matches!(&b.kind, ExprKind::TypeName(n) if n == "Leaf"));
|
|
217
|
+
// A type with arguments is no value: it stays a type argument, for the checker to report.
|
|
218
|
+
let s = plum_test_support::parseRawSource("fun f(t: Tree) -> Bool = @sameRef(t, List[Int])\n");
|
|
219
|
+
let FnBody::Expr(e) = &fnOf(&s, None, "f").body else { panic!("expr body") };
|
|
220
|
+
let ExprKind::FnCall(c) = &e.kind else { panic!("{e:?}") };
|
|
221
|
+
assert_eq!((c.args.len(), c.type_args.len()), (1, 1));
|
|
222
|
+
}
|
compiler/core/tests/core/uniqueness_test.rs
CHANGED
|
@@ -423,26 +423,34 @@ fn a_closure_field_named_like_a_fresh_method_is_not_that_method() {
|
|
|
423
423
|
}
|
|
424
424
|
|
|
425
425
|
#[test]
|
|
426
|
-
fn
|
|
426
|
+
fn a_variable_compared_by_same_ref_is_never_updated_in_place() {
|
|
427
|
-
// Written in place, `c`'s cell would hold the new version, and `
|
|
427
|
+
// Written in place, `c`'s cell would hold the new version, and `@sameRef(c, new)` would
|
|
428
|
-
// say nothing changed.
|
|
428
|
+
// say nothing changed. The built-in makes its arguments shared.
|
|
429
429
|
let s = format!(
|
|
430
|
-
"{CELL}fun same[T](a: T, b: T) -> Bool = todo\n\
|
|
431
|
-
|
|
430
|
+
"{CELL}fun probe(c: Cell) -> Cell =\n ok := @sameRef(c, Cell(label: \"x\", n: 0))\n Cell(..c, n: 1)\n\
|
|
432
431
|
fun go() -> Cell = probe(Cell(label: \"m\", n: 0))\n"
|
|
433
432
|
);
|
|
434
433
|
let mut src = plum_test_support::parseRawSource(&s);
|
|
434
|
+
plum_core::compile_builtins::declare(&mut src);
|
|
435
|
+
let r = markUnique(&mut src);
|
|
436
|
+
assert!(!provedFn(&r, "probe"), "{r:?}");
|
|
437
|
+
assert!(whyNot(&r, "probe").contains("@sameRef"), "{r:?}");
|
|
438
|
+
// A function that merely has the old name blocks nothing: the built-in is matched by
|
|
439
|
+
// its own name, not by a file or a function called `same`.
|
|
440
|
+
let named = format!(
|
|
441
|
+
"{CELL}fun same(a: Cell, b: Cell) -> Bool = a.n == b.n\n\
|
|
442
|
+
fun probe(c: Cell) -> Cell =\n ok := same(c, Cell(label: \"x\", n: 0))\n Cell(..c, n: 1)\n\
|
|
443
|
+
fun go() -> Cell = probe(Cell(label: \"m\", n: 0))\n"
|
|
444
|
+
);
|
|
445
|
+
let mut src = plum_test_support::parseRawSource(&named);
|
|
435
446
|
for i in &mut src.items {
|
|
436
447
|
if let Item::Fn(f) = i {
|
|
437
|
-
if f.name == "same" {
|
|
438
|
-
|
|
448
|
+
f.file = "lib/std/ref.plum".to_string();
|
|
439
|
-
}
|
|
440
449
|
}
|
|
441
450
|
}
|
|
442
451
|
let r = markUnique(&mut src);
|
|
443
|
-
assert!(!provedFn(&r, "probe"), "{r:?}");
|
|
444
|
-
assert!(whyNot(&r, "probe").contains("
|
|
452
|
+
assert!(!whyNot(&r, "probe").contains("@sameRef"), "{r:?}");
|
|
445
|
-
// The same fn without `
|
|
453
|
+
// The same fn without `@sameRef` is proved: the call above is what blocks it.
|
|
446
454
|
let plain = format!(
|
|
447
455
|
"{CELL}fun probe(c: Cell) -> Cell =\n ok := c.n == 0\n Cell(..c, n: 1)\n\
|
|
448
456
|
fun go() -> Cell = probe(Cell(label: \"m\", n: 0))\n"
|
compiler/tooling/tree-sitter-plum/test/corpus/traits.txt
CHANGED
|
@@ -342,3 +342,50 @@ fun g() = @foo(x + 1, Self)
|
|
|
342
342
|
(integer)))))
|
|
343
343
|
(type
|
|
344
344
|
(type_identifier)))))))
|
|
345
|
+
|
|
346
|
+
==================
|
|
347
|
+
built-in calls that take values
|
|
348
|
+
==================
|
|
349
|
+
|
|
350
|
+
fun f(a: Cell, e: Chain) -> Bool = @sameRef(a, b.kept()) && @sameRef(e, End)
|
|
351
|
+
|
|
352
|
+
---
|
|
353
|
+
|
|
354
|
+
(source
|
|
355
|
+
(fn
|
|
356
|
+
(fn_identifier)
|
|
357
|
+
(param
|
|
358
|
+
(var_identifier)
|
|
359
|
+
(type
|
|
360
|
+
(type_identifier)))
|
|
361
|
+
(param
|
|
362
|
+
(var_identifier)
|
|
363
|
+
(type
|
|
364
|
+
(type_identifier)))
|
|
365
|
+
(type
|
|
366
|
+
(type_identifier))
|
|
367
|
+
(expression
|
|
368
|
+
(boolean_operator
|
|
369
|
+
(expression
|
|
370
|
+
(primary_expression
|
|
371
|
+
(builtin_call
|
|
372
|
+
(var_identifier)
|
|
373
|
+
(expression
|
|
374
|
+
(primary_expression
|
|
375
|
+
(var_identifier)))
|
|
376
|
+
(expression
|
|
377
|
+
(primary_expression
|
|
378
|
+
(attribute
|
|
379
|
+
(primary_expression
|
|
380
|
+
(var_identifier))
|
|
381
|
+
(fn_identifier)
|
|
382
|
+
(fn_argument_list)))))))
|
|
383
|
+
(expression
|
|
384
|
+
(primary_expression
|
|
385
|
+
(builtin_call
|
|
386
|
+
(var_identifier)
|
|
387
|
+
(expression
|
|
388
|
+
(primary_expression
|
|
389
|
+
(var_identifier)))
|
|
390
|
+
(type
|
|
391
|
+
(type_identifier)))))))))
|
compiler/wasm-codegen/src/context.rs
CHANGED
|
@@ -284,8 +284,6 @@ pub(crate) struct GenState {
|
|
|
284
284
|
pub(crate) value_helpers: HashMap<String, u32>,
|
|
285
285
|
/// Per-compile facts (the source file `x!` crash messages name).
|
|
286
286
|
pub(crate) err_info: ErrInfo,
|
|
287
|
-
/// The global names of std's `ref.same` (std/ref.plum): its calls compile to one `ref.eq`.
|
|
288
|
-
pub(crate) same_fns: std::collections::HashSet<String>,
|
|
289
287
|
/// The wasm functions of std's native ops (`plum_core::native`): a direct call of one
|
|
290
288
|
/// compiles to its instruction in line (see `calls::emitCall`).
|
|
291
289
|
pub(crate) native_fns: HashMap<u32, plum_core::native::NativeOp>,
|
compiler/wasm-codegen/src/driver.rs
CHANGED
|
@@ -270,14 +270,6 @@ impl<'a> Setup<'a> {
|
|
|
270
270
|
let Setup { source, base_types, inst_types, enum_variants, enum_params, eg, units, instantiations, type_apps, type_funs, .. } = self;
|
|
271
271
|
// ---- collect the concrete generic types the program uses ----
|
|
272
272
|
withGen(|s| {
|
|
273
|
-
s.same_fns = source
|
|
274
|
-
.items
|
|
275
|
-
.iter()
|
|
276
|
-
.filter_map(|i| match i {
|
|
277
|
-
ast::Item::Fn(f) if crate::intrinsics::isSameFn(f) => Some(f.name.clone()),
|
|
278
|
-
_ => None,
|
|
279
|
-
})
|
|
280
|
-
.collect();
|
|
281
273
|
let v = &mut s.value_enums;
|
|
282
274
|
for item in &source.items {
|
|
283
275
|
if let ast::Item::Enum(e) = item {
|
compiler/wasm-codegen/src/expr.rs
CHANGED
|
@@ -411,8 +411,8 @@ fn compileExprNode(
|
|
|
411
411
|
} else {
|
|
412
412
|
let (func_idx, sig) = resolveCallee(ctx, expr, false, &call.name)
|
|
413
413
|
.ok_or_else(|| format!("unknown function '{}'", call.name))?;
|
|
414
|
-
if
|
|
414
|
+
if call.name == plum_core::compile_builtins::SAME_REF_FN && call.args.len() == 2 && sig.params.len() == 2 {
|
|
415
|
-
// `
|
|
415
|
+
// `@sameRef(a, b)` in line: one `ref.eq` (see `intrinsics::compileSameFnBody`).
|
|
416
416
|
for (arg, vt) in call.args.iter().zip(&sig.params) {
|
|
417
417
|
compileExpr(argExprOf(arg), body, ctx, state)?;
|
|
418
418
|
crate::intrinsics::castToEq(vt, body);
|
compiler/wasm-codegen/src/intrinsics.rs
CHANGED
|
@@ -14,7 +14,7 @@ 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
|
|
17
|
+
if plum_core::compile_builtins::isSameRef(f) {
|
|
18
18
|
return compileSameFnBody(subst);
|
|
19
19
|
}
|
|
20
20
|
if let Some(op) = plum_core::native::nativeOp(f) {
|
|
@@ -49,14 +49,7 @@ pub(crate) fn typeNameBody(f: &ast::Fn, subst: &Subst) -> ast::Fn {
|
|
|
49
49
|
g
|
|
50
50
|
}
|
|
51
51
|
|
|
52
|
-
/// `ref.same[T](a, b)` (std/ref.plum): reference identity.
|
|
53
|
-
pub(crate) fn isSameFn(f: &ast::Fn) -> bool {
|
|
54
|
-
f.type_param.is_none()
|
|
55
|
-
&& plum_core::modules::sourceFnName(&f.name) == "same"
|
|
56
|
-
&& f.file.replace('\\', "/").ends_with("std/ref.plum")
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/// The body of `
|
|
52
|
+
/// The body of `@sameRef[T](a, b)` (`plum_core::compile_builtins`) for one `T`: `ref.eq` of its two parameters (locals 0 and 1). The
|
|
60
53
|
/// checker lets only heap types through (see `plum_checker::identity`), so each parameter is
|
|
61
54
|
/// one reference: a concrete heap type is already an `eqref`, an `anyref` (a trait object,
|
|
62
55
|
/// a closure) is cast to one first.
|
std/collections/RoseTree.plum
CHANGED
|
@@ -5,7 +5,6 @@ import std/Bool
|
|
|
5
5
|
import std/Str
|
|
6
6
|
import std/Option
|
|
7
7
|
import std/collections/List
|
|
8
|
-
import std/ref
|
|
9
8
|
|
|
10
9
|
# A rose tree written functionally (see std/collections/AvlTree for the
|
|
11
10
|
# rules these persistent collections follow): a persistent tree in which a node has any number of children,
|
|
@@ -349,11 +348,11 @@ test "200000 children: of, chainOf, filter, replace, update, addChild and map ru
|
|
|
349
348
|
assert RoseTree.chainOf(kids).count() == 200000
|
|
350
349
|
assert t.filter(|v| v != 199999).count() == 200000
|
|
351
350
|
assert t.filter(|v| v < 0 || v % 2 == 0).count() == 100001
|
|
352
|
-
assert
|
|
351
|
+
assert @sameRef(t.filter(|v| v != 0).kids(), t.kids().rest())
|
|
353
|
-
assert
|
|
352
|
+
assert @sameRef(t.filter(|v| v != -5), t)
|
|
354
353
|
u := t.update(|v| v == 199999, |v| 7)
|
|
355
354
|
assert u.count() == 200001 && u.kids().fold(0, |a, v| a + v) == t.kids().fold(0, |a, v| a + v) - 199999 + 7
|
|
356
|
-
assert
|
|
355
|
+
assert @sameRef(t.update(|v| v == -5, |v| 7), t)
|
|
357
356
|
assert t.replace(|v| v == 100000, |n| RoseEmpty).count() == 200000
|
|
358
357
|
assert t.addChild(RoseTree.leaf(7)).count() == 200002
|
|
359
358
|
assert t.map(|v| v + 1).fold(0, |a, v| a + v) == t.fold(0, |a, v| a + v) + 200001
|
std/game/Game.plum
CHANGED
|
@@ -8,7 +8,6 @@ import std/Option
|
|
|
8
8
|
import std/collections/List
|
|
9
9
|
import std/Slice
|
|
10
10
|
import std/Io
|
|
11
|
-
import std/ref
|
|
12
11
|
import std/math/Vec2
|
|
13
12
|
import std/math/Affine
|
|
14
13
|
import std/game/Color
|
|
@@ -216,7 +215,7 @@ struct Game[S: Reducer[M], M](
|
|
|
216
215
|
out := framed(screenNode(k, keyOf[S, M](self.tree, s.from)), s.frame(false, self.view))
|
|
217
216
|
out.concat(framed(now, s.frame(true, self.view)))
|
|
218
217
|
None => now
|
|
219
|
-
if
|
|
218
|
+
if @sameRef(kids, k) && n.isEmpty()
|
|
220
219
|
self.tree
|
|
221
220
|
else
|
|
222
221
|
node: RoseTree[Actor[M]] := RoseNode(value: r, firstChild: kids, nextSibling: RoseEmpty)
|
|
@@ -235,7 +234,7 @@ struct Game[S: Reducer[M], M](
|
|
|
235
234
|
kids := match self.shift
|
|
236
235
|
Some(s) => framed(now, s.frame(true, self.view))
|
|
237
236
|
None => now
|
|
238
|
-
if
|
|
237
|
+
if @sameRef(kids, k) && n.isEmpty()
|
|
239
238
|
self.tree
|
|
240
239
|
else
|
|
241
240
|
node: RoseTree[Actor[M]] := RoseNode(value: r, firstChild: kids, nextSibling: RoseEmpty)
|
|
@@ -272,7 +271,7 @@ struct Game[S: Reducer[M], M](
|
|
|
272
271
|
else
|
|
273
272
|
ran := Game(..self, tree: turn.tree, store: flushed, shift: advanced(self.shift, dt), exited: turn.exit, ticks: self.ticks + 1, pointer: pointer, view: view)
|
|
274
273
|
# Only a message changes the state, so a tick that sent none names the same screen.
|
|
275
|
-
if
|
|
274
|
+
if @sameRef(turn.store, self.store) then ran else ran.switched(io)
|
|
276
275
|
|
|
277
276
|
# The game with the screen `state.screen()` names current, if it is another one: it
|
|
278
277
|
# `enter`s, and comes in by its `transition`. A name no screen has keeps the current
|
|
@@ -410,7 +409,7 @@ fun spliced[M](whole: RoseTree[Actor[M]], live: RoseTree[Actor[M]], key: Int) ->
|
|
|
410
409
|
put := replaceKid(k, key, liveScreen(lk, key))
|
|
411
410
|
extras := liveExtras(lk, key)
|
|
412
411
|
kids := if extras.isEmpty() then put else put.concat(extras)
|
|
413
|
-
if
|
|
412
|
+
if @sameRef(r, r0) && @sameRef(kids, k) && n0.isEmpty()
|
|
414
413
|
whole
|
|
415
414
|
else
|
|
416
415
|
empty: RoseTree[Actor[M]] := RoseEmpty
|
|
@@ -444,10 +443,10 @@ fun replaceKid[M](kids: RoseTree[Actor[M]], key: Int, by: RoseTree[Actor[M]]) ->
|
|
|
444
443
|
if a.key() == key
|
|
445
444
|
match by
|
|
446
445
|
RoseEmpty => n
|
|
447
|
-
RoseNode(b, bk, _) => if
|
|
446
|
+
RoseNode(b, bk, _) => if @sameRef(b, a) && @sameRef(bk, k) then kids else RoseNode(value: b, firstChild: bk, nextSibling: n)
|
|
448
447
|
else
|
|
449
448
|
n2 := replaceKid(n, key, by)
|
|
450
|
-
if
|
|
449
|
+
if @sameRef(n2, n) then kids else RoseNode(value: a, firstChild: k, nextSibling: n2)
|
|
451
450
|
|
|
452
451
|
# The tree with the screen `key` (a child of the root) through `f` with its own subtree,
|
|
453
452
|
# if it is a `Screen[S, M]`; unchanged otherwise.
|
|
@@ -464,7 +463,7 @@ fun onScreen[S, M](tree: SceneTree[M], key: Int, f: fn(Screen[S, M], SceneTree[M
|
|
|
464
463
|
Some(x) => x.key() == ShiftFrameId
|
|
465
464
|
None => false
|
|
466
465
|
kids := if framedNow then framedAgain(k, sub.root) else replaceKid(k, key, sub.root)
|
|
467
|
-
if
|
|
466
|
+
if @sameRef(kids, k) then tree else tree.withRoot(RoseNode(value: r, firstChild: kids, nextSibling: n))
|
|
468
467
|
_ => tree
|
|
469
468
|
None => tree
|
|
470
469
|
|
std/game/SceneTree.plum
CHANGED
|
@@ -13,7 +13,6 @@ import std/collections/Set
|
|
|
13
13
|
import std/Pair
|
|
14
14
|
import std/math/math
|
|
15
15
|
import std/Io
|
|
16
|
-
import std/ref
|
|
17
16
|
import std/math/Vec2
|
|
18
17
|
import std/math/Affine
|
|
19
18
|
import std/game/Color
|
|
@@ -53,13 +52,13 @@ import std/game/Ctx
|
|
|
53
52
|
#
|
|
54
53
|
# The walks `step` and `apply` rebuild every link node they pass: each is one loop along a
|
|
55
54
|
# sibling chain (the compiler builds the chain front to back, tail modulo cons), with
|
|
56
|
-
# recursion only into children. Keeping an unchanged node instead (`
|
|
55
|
+
# recursion only into children. Keeping an unchanged node instead (`@sameRef` on its actor,
|
|
57
56
|
# children and later siblings) needs the siblings' result before the node is built, so the
|
|
58
57
|
# walk recurses along the chain; that costs more than the nodes it saves, even when 99% of
|
|
59
58
|
# the actors stand still (benchmarks/scene_trees, workloads 10 and 11). `input`, which
|
|
60
59
|
# recurses anyway, keeps every node off the hit actor's path, and the hit node itself when
|
|
61
60
|
# the actor's `input` returns it as it was (`Actor`'s default); a value compared by
|
|
62
|
-
# `
|
|
61
|
+
# `@sameRef` is never updated in place, so a changed actor is always another
|
|
63
62
|
# object. `withRoot`, `apply` with nothing to do and `input` that hits nothing return the
|
|
64
63
|
# tree itself.
|
|
65
64
|
struct SceneTree[M](root: RoseTree[Actor[M]], camX: Float, camY: Float, camScale: Float) =
|
|
@@ -69,7 +68,7 @@ struct SceneTree[M](root: RoseTree[Actor[M]], camX: Float, camY: Float, camScale
|
|
|
69
68
|
SceneTree(root: RoseTree.leaf(top), camX: 0.0, camY: 0.0, camScale: 1.0)
|
|
70
69
|
|
|
71
70
|
# The same camera over another tree; this very tree when `r` is its own root.
|
|
72
|
-
fun withRoot(self, r: RoseTree[Actor[M]]) -> SceneTree[M] = if
|
|
71
|
+
fun withRoot(self, r: RoseTree[Actor[M]]) -> SceneTree[M] = if @sameRef(r, self.root) then self else SceneTree(..self, root: r)
|
|
73
72
|
|
|
74
73
|
# A game's tree (std/game/Game): a root group (id `ScreensRootId`) whose children are the
|
|
75
74
|
# screens, in order.
|
|
@@ -479,7 +478,7 @@ fun routeChain[M](t: RoseTree[Actor[M]], ctx: Ctx[M], p: Vec2, e: InputEvent, i:
|
|
|
479
478
|
RoseNode(a, k, n) =>
|
|
480
479
|
if i > 0
|
|
481
480
|
n2 := routeChain(n, ctx, p, e, i - 1, path)
|
|
482
|
-
if
|
|
481
|
+
if @sameRef(n2, n) then t else RoseNode(value: a, firstChild: k, nextSibling: n2)
|
|
483
482
|
else
|
|
484
483
|
pl := a.place()
|
|
485
484
|
q := toLocal(pl, p)
|
|
@@ -487,10 +486,10 @@ fun routeChain[M](t: RoseTree[Actor[M]], ctx: Ctx[M], p: Vec2, e: InputEvent, i:
|
|
|
487
486
|
Cons(j, rest) =>
|
|
488
487
|
k2 := routeChain(k, ctx.under(pl.local(), a.opacity()), q, e, j, rest)
|
|
489
488
|
na := a.input(ctx, InputEvent.pointerAt(e, q))
|
|
490
|
-
if
|
|
489
|
+
if @sameRef(na, a) && @sameRef(k2, k) then t else RoseNode(value: na, firstChild: k2, nextSibling: n)
|
|
491
490
|
Nil =>
|
|
492
491
|
na := a.input(ctx, InputEvent.pointerAt(e, q))
|
|
493
|
-
if
|
|
492
|
+
if @sameRef(na, a) then t else RoseNode(value: na, firstChild: k, nextSibling: n)
|
|
494
493
|
|
|
495
494
|
# The topmost shown `Clickable` actor under `p` (a point in the chain's parent's
|
|
496
495
|
# coordinates) that says it is hit: later siblings first, and in each, its children before
|
|
@@ -650,23 +649,23 @@ test "a step that changes nothing keeps every actor"
|
|
|
650
649
|
|
|
651
650
|
test "input or apply that changes nothing returns the very same tree"
|
|
652
651
|
s0 := ttree().add(0, trect(1, 0.0, 0.0, 5.0)).add(0, tgroup(2, 0.0, 0.0, 1.0, 0.0, [trect(3, 0.0, 0.0, 5.0)]))
|
|
653
|
-
assert
|
|
652
|
+
assert @sameRef(s0.apply(Slice[Cmd[Int]]()), s0)
|
|
654
|
-
assert
|
|
653
|
+
assert @sameRef(s0.input(Ctx[Int](), PointerDown(x: 1000.0, y: 1000.0)), s0)
|
|
655
654
|
# A hit on a rect whose `input` is the default: the same tree.
|
|
656
|
-
assert
|
|
655
|
+
assert @sameRef(s0.input(Ctx[Int](), PointerDown(x: 1.0, y: 1.0)), s0)
|
|
657
656
|
|
|
658
657
|
test "input keeps the nodes off the hit actor's path"
|
|
659
658
|
s0 := ttree().add(0, tgroup(1, 0.0, 0.0, 1.0, 0.0, [trect(2, 0.0, 0.0, 5.0)])).add(0, tclicker(3, 100.0)).add(0, trect(4, 500.0, 0.0, 5.0))
|
|
660
659
|
s1 := s0.input(Ctx[Int](), PointerDown(x: 101.0, y: 1.0))
|
|
661
660
|
assert s1.findAs[TClicker](3).unwrap().clicks == 1
|
|
662
661
|
assert s0.findAs[TClicker](3).unwrap().clicks == 0
|
|
663
|
-
assert
|
|
662
|
+
assert @sameRef(nodeOf(s1.root, 4), nodeOf(s0.root, 4))
|
|
664
|
-
assert
|
|
663
|
+
assert @sameRef(s1.find(1).unwrap(), s0.find(1).unwrap())
|
|
665
|
-
assert
|
|
664
|
+
assert @sameRef(s1.find(2).unwrap(), s0.find(2).unwrap())
|
|
666
665
|
|
|
667
666
|
test "an actor whose step changes it is seen as changed, also where nothing else holds the tree"
|
|
668
667
|
# Under the default, `--no-fbip` and `--no-fusion` alike (the sweep runs all three): were
|
|
669
|
-
# the drifter written in place, `
|
|
668
|
+
# the drifter written in place, `@sameRef` would keep the old node and the old place.
|
|
670
669
|
assert tx(tstepFresh(10.0), 2) == 5.0
|
|
671
670
|
assert tx(tstepFresh(-4.0), 2) == -2.0
|
|
672
671
|
assert tx(tstepFresh(10.0).step(Ctx[Int](), 0.5), 2) == 10.0
|
|
@@ -905,8 +904,8 @@ test "only a Clickable actor is hit: a plain one with a hit method never is, its
|
|
|
905
904
|
assert TPlain(id: 9, at: place.at(0.0, 0.0), inputs: 0).hit(Vec2(x: 0.0, y: 0.0))
|
|
906
905
|
# A press on the plain parent alone goes nowhere; one on the child goes to it, then to
|
|
907
906
|
# the parent on its way up.
|
|
908
|
-
assert
|
|
907
|
+
assert @sameRef(s.input(Ctx[Int](), PointerDown(x: 5.0, y: 5.0)), s)
|
|
909
|
-
assert
|
|
908
|
+
assert @sameRef(s.input(Ctx[Int](), PointerDown(x: 205.0, y: 5.0)), s)
|
|
910
909
|
s1 := s.input(Ctx[Int](), PointerDown(x: 25.0, y: 5.0))
|
|
911
910
|
assert s1.findAs[TClicker](2).unwrap().clicks == 1
|
|
912
911
|
assert s1.findAs[TPlain](1).unwrap().inputs == 1
|
std/ref.plum
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
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/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 → same_ref.plum}
RENAMED
|
@@ -3,9 +3,8 @@ import std/Str
|
|
|
3
3
|
import std/Bool
|
|
4
4
|
import std/Option
|
|
5
5
|
import std/collections/List
|
|
6
|
-
import std/ref
|
|
7
6
|
|
|
8
|
-
# `
|
|
7
|
+
# `@sameRef(a, b)`: the very same object, not an equal one. The sweep runs this file with
|
|
9
8
|
# the default, `--no-fbip` and `--no-fusion`; every answer must be the same in all three
|
|
10
9
|
# (an in-place update must never make an updated value look the same as the old one).
|
|
11
10
|
|
|
@@ -35,7 +34,7 @@ fun fresh() -> Cell = Cell(label: "a", n: 1)
|
|
|
35
34
|
# A cell updated where nothing else holds it, then compared with what came in.
|
|
36
35
|
fun changedAfter(c: Cell) -> Bool =
|
|
37
36
|
d := c.bumped()
|
|
38
|
-
!
|
|
37
|
+
!@sameRef(c, d)
|
|
39
38
|
|
|
40
39
|
# The chain with every cell at `k`, sharing every link whose cell did not change.
|
|
41
40
|
fun toward(xs: Chain, k: Int) -> Chain = match xs
|
|
@@ -43,7 +42,7 @@ fun toward(xs: Chain, k: Int) -> Chain = match xs
|
|
|
43
42
|
Link(v, next) =>
|
|
44
43
|
v2 := v.toward(k)
|
|
45
44
|
n2 := toward(next, k)
|
|
46
|
-
if
|
|
45
|
+
if @sameRef(v2, v) && @sameRef(n2, next) then xs else Link(v: v2, next: n2)
|
|
47
46
|
|
|
48
47
|
fun sumOf(xs: Chain) -> Int = match xs
|
|
49
48
|
End => 0
|
|
@@ -52,11 +51,11 @@ fun sumOf(xs: Chain) -> Int = match xs
|
|
|
52
51
|
test "a value is the same as itself, and a copy or an equal value is not"
|
|
53
52
|
a := fresh()
|
|
54
53
|
b := a
|
|
55
|
-
assert
|
|
54
|
+
assert @sameRef(a, b)
|
|
56
|
-
assert
|
|
55
|
+
assert @sameRef(a, a.kept())
|
|
57
|
-
assert !
|
|
56
|
+
assert !@sameRef(a, Cell(..a))
|
|
58
|
-
assert !
|
|
57
|
+
assert !@sameRef(a, fresh())
|
|
59
|
-
assert !
|
|
58
|
+
assert !@sameRef(a, a.bumped())
|
|
60
59
|
|
|
61
60
|
test "an update where nothing else holds the value is still another object"
|
|
62
61
|
assert changedAfter(fresh())
|
|
@@ -64,31 +63,31 @@ test "an update where nothing else holds the value is still another object"
|
|
|
64
63
|
|
|
65
64
|
test "strings, lists and enum values"
|
|
66
65
|
s := "plum"
|
|
67
|
-
assert
|
|
66
|
+
assert @sameRef(s, s)
|
|
68
67
|
xs: List[Int] := [1, 2, 3]
|
|
69
|
-
assert
|
|
68
|
+
assert @sameRef(xs, xs)
|
|
70
|
-
assert !
|
|
69
|
+
assert !@sameRef(xs, [1, 2, 3])
|
|
71
70
|
e: Chain := End
|
|
72
|
-
assert
|
|
71
|
+
assert @sameRef(e, End)
|
|
73
72
|
|
|
74
73
|
test "trait objects: a default method that returns self keeps the object"
|
|
75
74
|
r: Thing := Rock(id: 1)
|
|
76
|
-
assert
|
|
75
|
+
assert @sameRef(r, r.moved())
|
|
77
76
|
b: Thing := Ball(id: 2, y: 0)
|
|
78
77
|
m := b.moved()
|
|
79
|
-
assert !
|
|
78
|
+
assert !@sameRef(b, m)
|
|
80
79
|
assert m.key() == 2
|
|
81
80
|
|
|
82
81
|
test "a walk that shares what did not change"
|
|
83
82
|
xs: Chain := Link(v: Cell(label: "a", n: 3), next: Link(v: Cell(label: "b", n: 3), next: End))
|
|
84
|
-
assert
|
|
83
|
+
assert @sameRef(toward(xs, 3), xs)
|
|
85
84
|
ys := toward(xs, 4)
|
|
86
|
-
assert !
|
|
85
|
+
assert !@sameRef(ys, xs)
|
|
87
86
|
assert sumOf(ys) == 8
|
|
88
87
|
assert sumOf(xs) == 6
|
|
89
88
|
# Only the second changes: the first link is rebuilt over it, the end is shared.
|
|
90
89
|
zs: Chain := Link(v: Cell(label: "a", n: 4), next: Link(v: Cell(label: "b", n: 3), next: End))
|
|
91
90
|
ws := toward(zs, 4)
|
|
92
|
-
assert !
|
|
91
|
+
assert !@sameRef(ws, zs)
|
|
93
92
|
assert sumOf(ws) == 8
|
|
94
93
|
assert sumOf(zs) == 7
|