plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
28d65a2
— Peter John
2026-11-10T12:24:11+05:30
Traits: generic implementers of a trait that doesn't fix their parameters
- compiler/checker/src/callsites.rs +97 -11
- compiler/checker/src/patterns.rs +6 -2
- compiler/checker/src/program.rs +12 -1
- compiler/checker/src/state.rs +4 -0
- compiler/checker/tests/checker/traits_tests.rs +13 -0
- compiler/wasm-codegen/src/traits.rs +15 -1
- docs/language.md +3 -1
- tests/traits/open_generic_impl.plum +40 -0
compiler/checker/src/callsites.rs
CHANGED
|
@@ -94,18 +94,27 @@ pub(crate) fn recordDispatch(obj_ty: &PlumType, name: &str) {
|
|
|
94
94
|
if !e.args.iter().zip(targs).all(|(a, t)| bindParams(a, t, &mut b)) {
|
|
95
95
|
continue;
|
|
96
96
|
}
|
|
97
|
-
|
|
97
|
+
let open = !gens.iter().all(|g| b.contains_key(g));
|
|
98
|
-
|
|
98
|
+
let site = CallSite {
|
|
99
|
-
|
|
99
|
+
recv: Some(ty.clone()),
|
|
100
|
-
|
|
100
|
+
name: name.to_string(),
|
|
101
|
-
|
|
101
|
+
args: b,
|
|
102
|
-
|
|
102
|
+
line,
|
|
103
|
-
|
|
103
|
+
column,
|
|
104
|
-
|
|
104
|
+
file: shownFile(),
|
|
105
|
-
|
|
105
|
+
expr,
|
|
106
|
-
|
|
106
|
+
implicit: false,
|
|
107
|
-
|
|
107
|
+
dispatch: true,
|
|
108
|
+
};
|
|
109
|
+
if open {
|
|
110
|
+
withCheck(|s| {
|
|
111
|
+
let mut v = s.open_dispatch.borrow_mut();
|
|
112
|
+
if !v.iter().any(|o| o.recv == site.recv && o.name == site.name && o.args == site.args) {
|
|
113
|
+
v.push(site);
|
|
114
|
+
}
|
|
108
115
|
});
|
|
116
|
+
} else {
|
|
117
|
+
sites.push(site);
|
|
109
118
|
}
|
|
110
119
|
}
|
|
111
120
|
}
|
|
@@ -116,6 +125,83 @@ pub(crate) fn recordDispatch(obj_ty: &PlumType, name: &str) {
|
|
|
116
125
|
});
|
|
117
126
|
}
|
|
118
127
|
|
|
128
|
+
/// For each call on a trait object that may reach a generic implementer whose `is` entry
|
|
129
|
+
/// leaves some of its generics open (`Box[M] is Clickable`, see `recordDispatch`): records
|
|
130
|
+
/// the method's instantiation for every instance of the type the program's types name so
|
|
131
|
+
/// far and that agrees with what the entry fixed. Returns whether it recorded any.
|
|
132
|
+
pub(crate) fn recordOpenDispatches(info: &TypedInfo) -> bool {
|
|
133
|
+
let open: Vec<CallSite> = withCheck(|s| s.open_dispatch.borrow().clone());
|
|
134
|
+
if open.is_empty() {
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
// The instances: every generic type named in a type recorded so far (as codegen finds
|
|
138
|
+
// the types it lays out), open arguments resolved by the bindings recorded so far.
|
|
139
|
+
let wanted: std::collections::HashSet<&str> = open.iter().filter_map(|o| o.recv.as_deref()).collect();
|
|
140
|
+
let mut instances: std::collections::HashSet<PlumType> = std::collections::HashSet::new();
|
|
141
|
+
withCheck(|s| {
|
|
142
|
+
let binds = s.record_binds.borrow();
|
|
143
|
+
let empty = Binds::new();
|
|
144
|
+
let b = binds.as_ref().unwrap_or(&empty);
|
|
145
|
+
let mut add = |t: &PlumType| appsNamed(&substVars(t, b), &wanted, &mut instances);
|
|
146
|
+
if let Some(r) = s.record.borrow().as_ref() {
|
|
147
|
+
r.values().for_each(&mut add);
|
|
148
|
+
}
|
|
149
|
+
info.inst_expr_types.values().chain(info.inst_annotated.values()).for_each(&mut add);
|
|
150
|
+
info.instantiations.iter().flat_map(|i| i.type_args.iter()).for_each(&mut add);
|
|
151
|
+
});
|
|
152
|
+
let traits = currentTraits();
|
|
153
|
+
let mut sites: Vec<CallSite> = Vec::new();
|
|
154
|
+
for o in &open {
|
|
155
|
+
let Some(ty) = &o.recv else { continue };
|
|
156
|
+
let Some((gens, _)) = traits.impls.get(ty) else { continue };
|
|
157
|
+
for inst in &instances {
|
|
158
|
+
let PlumType::TApp(n, targs) = inst else { continue };
|
|
159
|
+
if n != ty || targs.len() != gens.len() {
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
let mut args = o.args.clone();
|
|
163
|
+
let mut ok = true;
|
|
164
|
+
for (g, t) in gens.iter().zip(targs) {
|
|
165
|
+
match args.get(g) {
|
|
166
|
+
Some(prev) if prev != t => ok = false,
|
|
167
|
+
_ => {
|
|
168
|
+
args.insert(g.clone(), t.clone());
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
let key = (format!("{ty}.{}", o.name), targs.clone());
|
|
173
|
+
if ok && !info.inst_index.contains_key(&key) && !sites.iter().any(|s| s.args == args && s.recv == o.recv && s.name == o.name) {
|
|
174
|
+
sites.push(CallSite { args, ..o.clone() });
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
let any = !sites.is_empty();
|
|
179
|
+
withCheck(|s| {
|
|
180
|
+
if let Some(v) = s.calls.borrow_mut().as_mut() {
|
|
181
|
+
v.extend(sites);
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
any
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/// The concrete `TApp`s in `t` (itself or inside it) whose name is one of `names`.
|
|
188
|
+
fn appsNamed(t: &PlumType, names: &std::collections::HashSet<&str>, out: &mut std::collections::HashSet<PlumType>) {
|
|
189
|
+
use PlumType::*;
|
|
190
|
+
match t {
|
|
191
|
+
TApp(n, args) => {
|
|
192
|
+
args.iter().for_each(|a| appsNamed(a, names, out));
|
|
193
|
+
if names.contains(n.as_str()) && !hasFreeVars(t) && !out.contains(t) {
|
|
194
|
+
out.insert(t.clone());
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
TFun(ps, r) => {
|
|
198
|
+
ps.iter().for_each(|p| appsNamed(p, names, out));
|
|
199
|
+
appsNamed(r, names, out);
|
|
200
|
+
}
|
|
201
|
+
_ => {}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
119
205
|
/// Matches the pattern `pat` (with `TParam`s) against the concrete `t`, binding the params.
|
|
120
206
|
pub(crate) fn bindParams(pat: &PlumType, t: &PlumType, b: &mut BTreeMap<String, PlumType>) -> bool {
|
|
121
207
|
use PlumType::*;
|
compiler/checker/src/patterns.rs
CHANGED
|
@@ -96,8 +96,12 @@ pub(crate) fn checkPattern(
|
|
|
96
96
|
let ty = &if args.is_empty() { ty.clone() } else { target.to_string() };
|
|
97
97
|
if isTraitObject(&subject) {
|
|
98
98
|
if isTraitObject(&target) {
|
|
99
|
-
// A downcast to a trait: a value of any type that is both.
|
|
99
|
+
// A downcast to a trait: a value of any type that is both. In one copy of
|
|
100
|
+
// a generic body, a trait written as such (`Clickable as c` on an
|
|
101
|
+
// `Actor[M]`, in `hitPath[Msg]`) is no error when this program has no
|
|
102
|
+
// such type: the case never matches. A generic one (`T as t`) still is.
|
|
103
|
+
let written = withCheck(|s| s.inst_mode.get() && !s.tsubst.borrow().as_ref().is_some_and(|m| m.contains_key(ty)));
|
|
100
|
-
if !currentTraits().mayBeBoth(&subject, &target) {
|
|
104
|
+
if !currentTraits().mayBeBoth(&subject, &target) && !written {
|
|
101
105
|
let what = if target.to_string() == *ty { String::new() } else { format!(" ({ty} is {target} here)") };
|
|
102
106
|
return Err(format!(
|
|
103
107
|
"`{ty} as {name}`{what}: no type is both a {subject} and a {target}, so a {subject} is never a {target}"
|
compiler/checker/src/program.rs
CHANGED
|
@@ -418,7 +418,7 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
418
418
|
|
|
419
419
|
// Check each reached instantiation (BFS); its own calls enqueue more.
|
|
420
420
|
let mut seen_msgs: std::collections::HashSet<String> = std::collections::HashSet::new();
|
|
421
|
-
while let Some(id) =
|
|
421
|
+
while let Some(id) = nextInstantiation(&mut inst, &fn_by_key, &ctx) {
|
|
422
422
|
let i = inst.info.instantiations[id].clone();
|
|
423
423
|
let Some(f) = fn_by_key
|
|
424
424
|
.get(&(i.receiver.clone(), i.name.clone()))
|
|
@@ -500,6 +500,17 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
500
500
|
(result, inst.info)
|
|
501
501
|
}
|
|
502
502
|
|
|
503
|
+
/// The next instantiation to check. When the queue runs dry, the worklist knows every
|
|
504
|
+
/// instance it reached: the calls on trait objects that may reach a generic implementer
|
|
505
|
+
/// whose entry leaves a generic open (`Box[M] is Clickable`) get their copies then, and
|
|
506
|
+
/// those (and whatever they reach) are checked next.
|
|
507
|
+
fn nextInstantiation(inst: &mut InstState, fns: &HashMap<(Option<String>, String), &ast::Fn>, ctx: &CheckCtx) -> Option<usize> {
|
|
508
|
+
if inst.queue.is_empty() && recordOpenDispatches(&inst.info) {
|
|
509
|
+
registerCalls(inst, fns, ctx, None);
|
|
510
|
+
}
|
|
511
|
+
inst.queue.pop_front()
|
|
512
|
+
}
|
|
513
|
+
|
|
503
514
|
/// The errors of a method's `$dyn` copy (`plum_core::trait_defaults`), said as the method's:
|
|
504
515
|
/// it was checked again with `Self` inside a parameter or the result as the trait object.
|
|
505
516
|
fn dynErrors(f: &ast::Fn, errors: &mut [CheckError]) {
|
compiler/checker/src/state.rs
CHANGED
|
@@ -30,6 +30,10 @@ pub(crate) struct CheckState {
|
|
|
30
30
|
pub(crate) record: RefCell<Option<HashMap<crate::RecordKey, PlumType>>>,
|
|
31
31
|
/// Generic-call sites seen while checking one body (see `CallSite`); `None` outside `checkSourceInner`.
|
|
32
32
|
pub(crate) calls: RefCell<Option<Vec<CallSite>>>,
|
|
33
|
+
/// Calls on a trait object that may reach a generic implementer whose `is` entry leaves
|
|
34
|
+
/// some of its generics open (`Box[M] is Clickable`): instantiated for each `Box[..]`
|
|
35
|
+
/// the program has, once the worklist knows them (`registerOpenDispatches`).
|
|
36
|
+
pub(crate) open_dispatch: RefCell<Vec<CallSite>>,
|
|
33
37
|
/// While checking a generic body for one instantiation: its generic parameter -> concrete type.
|
|
34
38
|
pub(crate) tsubst: RefCell<Option<BTreeMap<String, PlumType>>>,
|
|
35
39
|
/// True while checking an instantiated generic body (method lookups on declared types are strict).
|
compiler/checker/tests/checker/traits_tests.rs
CHANGED
|
@@ -673,6 +673,19 @@ fn downcastToAGenericImplementer() {
|
|
|
673
673
|
);
|
|
674
674
|
}
|
|
675
675
|
|
|
676
|
+
/// A trait written in a generic body's downcast (`Named as n` on a `Thing[M]`, as std's
|
|
677
|
+
/// scene tree has `Clickable as c` on an `Actor[M]`) is no error in a copy for which the
|
|
678
|
+
/// program has no type that is both: the case never matches. Written in a plain fn it is.
|
|
679
|
+
#[test]
|
|
680
|
+
fn downcastToATraitInAGenericBodyMayNeverMatch() {
|
|
681
|
+
let named = "trait Named =\n fun name(self) -> Str\n\nstruct Tag(n: Str) is Named =\n fun name(self) -> Str = self.n\n\n";
|
|
682
|
+
ok(&format!("{GEN}{named}fun nameOf[M](t: Thing[M]) -> Str = match t\n Named as n => n.name()\n _ => \"none\"\n\nfun main() =\n b: Thing[Msg] := Box(id: 1)\n show(nameOf(b))\n"));
|
|
683
|
+
fails(
|
|
684
|
+
&format!("{GEN}{named}fun nameOf(t: Thing[Msg]) -> Str = match t\n Named as n => n.name()\n _ => \"none\"\n\nfun main() = Unit\n"),
|
|
685
|
+
"no type is both a Thing[Msg] and a Named",
|
|
686
|
+
);
|
|
687
|
+
}
|
|
688
|
+
|
|
676
689
|
/// `Box[Msg] as b` names the arguments of a generic implementer.
|
|
677
690
|
#[test]
|
|
678
691
|
fn downcastWithTypeArguments() {
|
compiler/wasm-codegen/src/traits.rs
CHANGED
|
@@ -384,13 +384,27 @@ pub(crate) enum AsTarget {
|
|
|
384
384
|
|
|
385
385
|
impl AsTarget {
|
|
386
386
|
/// Leaves 1 on the stack if the trait object `load` pushes has one of `tags`, else 0:
|
|
387
|
-
///
|
|
387
|
+
/// one range compare for tags without a gap, else for more than two tags under 64 a bit
|
|
388
|
+
/// of a mask, else a compare per tag.
|
|
388
389
|
pub(crate) fn emitTest(tags: &[i32], reg: &GcTypeRegistry, body: &mut Vec<u8>, load: &mut dyn FnMut(&mut Vec<u8>)) {
|
|
389
390
|
let obj = reg.obj_idx.expect("a downcast's subject is a trait object");
|
|
390
391
|
let tag = |body: &mut Vec<u8>, load: &mut dyn FnMut(&mut Vec<u8>)| {
|
|
391
392
|
load(body);
|
|
392
393
|
Instruction::StructGet { struct_type_index: obj, field_index: 0 }.encode(body);
|
|
393
394
|
};
|
|
395
|
+
// Tags that run without a gap (a trait's implementers get nearby tags, see
|
|
396
|
+
// `buildGcTypeRegistry`): one unsigned compare of the tag's offset from the first.
|
|
397
|
+
let (lo, hi) = (tags.iter().copied().min().unwrap_or(0), tags.iter().copied().max().unwrap_or(0));
|
|
398
|
+
if tags.len() > 1 && (hi - lo) as usize + 1 == tags.len() {
|
|
399
|
+
tag(body, load);
|
|
400
|
+
if lo != 0 {
|
|
401
|
+
Instruction::I32Const(lo).encode(body);
|
|
402
|
+
Instruction::I32Sub.encode(body);
|
|
403
|
+
}
|
|
404
|
+
Instruction::I32Const(hi - lo + 1).encode(body);
|
|
405
|
+
Instruction::I32LtU.encode(body);
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
394
408
|
if tags.len() > 2 && tags.iter().all(|t| (0..64).contains(t)) {
|
|
395
409
|
let mask = tags.iter().fold(0u64, |m, t| m | (1u64 << t));
|
|
396
410
|
Instruction::I64Const(mask as i64).encode(body);
|
docs/language.md
CHANGED
|
@@ -582,7 +582,9 @@ fun widthOf(s: Shape) -> Float = match s
|
|
|
582
582
|
|
|
583
583
|
The type may be a generic parameter (`T as t`, with `T` set by the caller: `firstOf[Rect](xs)`), or a generic type whose arguments the trait object fixes (`Keep as k` on a `Reducer[Int]` binds a `Keep[Int]`) or that you write (`Keep[Int] as k`).
|
|
584
584
|
|
|
585
|
-
It may also be another trait: `Screen[S, M] as s` on an `Actor[M]` matches a value of any type that implements both, and binds it as a `Screen[S, M]` trait object. A trait with type parameters needs them written, and a downcast to a trait that no type implements together with the subject's is an error.
|
|
585
|
+
It may also be another trait: `Screen[S, M] as s` on an `Actor[M]` matches a value of any type that implements both, and binds it as a `Screen[S, M]` trait object. A trait with type parameters needs them written, and a downcast to a trait that no type implements together with the subject's is an error, except in a generic fn where the subject's type depends on the fn's parameters (`Clickable as c` on an `Actor[M]`): there a program with no such type just never matches the case. The test is one compare of the value's type tag (a range check when the types' tags are next to each other, as a trait's implementers' usually are).
|
|
586
|
+
|
|
587
|
+
A generic type may implement a trait that doesn't fix its parameters (`struct Box[M](..) is Actor[M], Clickable`): a call on a `Clickable` reaches each `Box[..]` the program has.
|
|
586
588
|
|
|
587
589
|
**Type parameters.** A trait takes them like a struct, and an implementer names them:
|
|
588
590
|
|
tests/traits/open_generic_impl.plum
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Str
|
|
3
|
+
import std/List
|
|
4
|
+
import std/Option
|
|
5
|
+
|
|
6
|
+
# A generic implementer of a trait that doesn't fix its parameter (`Box[M] is Sized`, as
|
|
7
|
+
# std/game's `Box[M] is Actor[M], Clickable`): a call on a `Sized` dispatches to each
|
|
8
|
+
# `Box[..]` the program has, so the method is compiled for each of them.
|
|
9
|
+
|
|
10
|
+
trait Thing[M] =
|
|
11
|
+
fun key(self) -> Int
|
|
12
|
+
|
|
13
|
+
trait Sized =
|
|
14
|
+
fun size(self) -> Int
|
|
15
|
+
|
|
16
|
+
struct Box[M](id: Int, w: Int) is Thing[M], Sized =
|
|
17
|
+
fun key(self) -> Int = self.id
|
|
18
|
+
fun size(self) -> Int = self.w * 10
|
|
19
|
+
|
|
20
|
+
struct Cell(n: Int) is Sized =
|
|
21
|
+
fun size(self) -> Int = self.n
|
|
22
|
+
|
|
23
|
+
fun sizeOf[M](t: Thing[M]) -> Int = match t
|
|
24
|
+
Sized as s => s.size()
|
|
25
|
+
_ => -1
|
|
26
|
+
|
|
27
|
+
struct Plain[M](id: Int) is Thing[M] =
|
|
28
|
+
fun key(self) -> Int = self.id
|
|
29
|
+
|
|
30
|
+
test "a downcast from a Thing[M] to Sized dispatches to each Box[..]"
|
|
31
|
+
a: Thing[Int] := Box(id: 1, w: 2)
|
|
32
|
+
b: Thing[Str] := Box(id: 2, w: 5)
|
|
33
|
+
c: Thing[Int] := Plain(id: 3)
|
|
34
|
+
assert sizeOf(a) == 20 && sizeOf(b) == 50 && sizeOf(c) == -1
|
|
35
|
+
|
|
36
|
+
test "a list of Sized mixing a Box[..] and a plain implementer"
|
|
37
|
+
a: Thing[Int] := Box(id: 1, w: 3)
|
|
38
|
+
xs: List[Sized] := [Cell(n: 4)]
|
|
39
|
+
total := xs.fold(0, |n, s| n + s.size())
|
|
40
|
+
assert total + sizeOf(a) == 34
|