plum

#treesitter#compiler#wasm

git clone https://git.pyrossh.dev/plum

A statically typed, imperative programming language inspired by rust, python


9d679b4 — Peter John 2026-11-09T13:37:24+05:30
Traits: codegen, and FBIP through dispatch and downcasts (actor-trait tasks 3 and 4)
compiler/checker/src/callcheck.rs CHANGED
@@ -396,6 +396,7 @@ pub(crate) fn inferMethodCall(
396
396
  let label = format!("method '{}.{}'", class_name, name);
397
397
  checkCallArgs(&label, &params, args, required, env, ctx, &mut binds)?;
398
398
  recordCall(Some(&class_name), name, call_map);
399
+ recordDispatch(&resolveRecorded(obj_ty), name);
399
400
  Ok(substVars(&ret, &binds))
400
401
  }
401
402
 
compiler/checker/src/callsites.rs CHANGED
@@ -15,6 +15,9 @@ pub(crate) struct CallSite {
15
15
  expr: ast::NodeId,
16
16
  /// A call codegen makes on its own (string interpolation's `toStr`), not written in source.
17
17
  implicit: bool,
18
+ /// A method of a generic implementer that a call on a trait object may reach: it is
19
+ /// instantiated, but the call expression is not its call site (codegen dispatches).
20
+ dispatch: bool,
18
21
  }
19
22
 
20
23
  pub(crate) fn recordCall(recv: Option<&str>, name: &str, args: BTreeMap<String, PlumType>) {
@@ -43,11 +46,76 @@ pub(crate) fn recordCallAt(
43
46
  column,
44
47
  expr,
45
48
  implicit,
49
+ dispatch: false,
46
50
  });
47
51
  }
48
52
  } });
49
53
  }
50
54
 
55
+ /// A call `obj.name(..)` on the trait object `obj_ty` may run the method of any type that
56
+ /// implements it: each generic implementer whose `is` entry fixes all of its parameters
57
+ /// (`Box[M] is Actor[M]` for an `Actor[Msg]`: `Box[Msg]`) has its method instantiated.
58
+ pub(crate) fn recordDispatch(obj_ty: &PlumType, name: &str) {
59
+ let traits = currentTraits();
60
+ let Some((tname, targs)) = traits.traitObject(obj_ty) else { return };
61
+ if targs.iter().any(hasFreeVars) {
62
+ return;
63
+ }
64
+ let expr = withCheck(|s| s.cur_expr.get());
65
+ if expr == ast::NodeId(0) {
66
+ return;
67
+ }
68
+ let (line, column) = withCheck(|s| s.cur_pos.get());
69
+ let mut sites = Vec::new();
70
+ for (ty, (gens, entries)) in &traits.impls {
71
+ if gens.is_empty() {
72
+ continue;
73
+ }
74
+ for e in entries.iter().filter(|e| e.trait_name == tname && e.args.len() == targs.len()) {
75
+ let mut b: BTreeMap<String, PlumType> = BTreeMap::new();
76
+ if !e.args.iter().zip(targs).all(|(a, t)| bindParams(a, t, &mut b)) {
77
+ continue;
78
+ }
79
+ if gens.iter().all(|g| b.contains_key(g)) {
80
+ sites.push(CallSite {
81
+ recv: Some(ty.clone()),
82
+ name: name.to_string(),
83
+ args: b,
84
+ line,
85
+ column,
86
+ expr,
87
+ implicit: false,
88
+ dispatch: true,
89
+ });
90
+ }
91
+ }
92
+ }
93
+ withCheck(|s| {
94
+ if let Some(v) = s.calls.borrow_mut().as_mut() {
95
+ v.extend(sites);
96
+ }
97
+ });
98
+ }
99
+
100
+ /// Matches the pattern `pat` (with `TParam`s) against the concrete `t`, binding the params.
101
+ fn bindParams(pat: &PlumType, t: &PlumType, b: &mut BTreeMap<String, PlumType>) -> bool {
102
+ use PlumType::*;
103
+ match (pat, t) {
104
+ (TParam(p), _) => match b.get(p) {
105
+ Some(prev) => prev == t,
106
+ None => {
107
+ b.insert(p.clone(), t.clone());
108
+ true
109
+ }
110
+ },
111
+ (TApp(x, xs), TApp(y, ys)) => x == y && xs.len() == ys.len() && xs.iter().zip(ys).all(|(p, q)| bindParams(p, q, b)),
112
+ (TFun(ps, r), TFun(qs, s)) => {
113
+ ps.len() == qs.len() && ps.iter().zip(qs).all(|(p, q)| bindParams(p, q, b)) && bindParams(r, s, b)
114
+ }
115
+ _ => pat == t,
116
+ }
117
+ }
118
+
51
119
  pub(crate) struct InstState {
52
120
  pub(crate) info: TypedInfo,
53
121
  /// Per instantiation id: the "in X[T] (called at f:l:c): " chain prefix.
@@ -195,6 +263,9 @@ pub(crate) fn registerCalls(
195
263
  }
196
264
  }
197
265
  if let Some(&existing) = st.info.inst_index.get(&key) {
266
+ if cs.dispatch {
267
+ continue;
268
+ }
198
269
  st.info
199
270
  .call_inst
200
271
  .insert((parent, cs.expr, cs.implicit), existing);
@@ -223,7 +294,9 @@ pub(crate) fn registerCalls(
223
294
  called_at_column: cs.column,
224
295
  });
225
296
  st.info.inst_index.insert(key, id);
297
+ if !cs.dispatch {
226
- st.info.call_inst.insert((parent, cs.expr, cs.implicit), id);
298
+ st.info.call_inst.insert((parent, cs.expr, cs.implicit), id);
299
+ }
227
300
  st.queue.push_back(id);
228
301
  }
229
302
  }
compiler/checker/src/program.rs CHANGED
@@ -54,6 +54,16 @@ pub(crate) fn checkSourceFull(source: &ast::Source) -> (CheckResult<()>, TypedIn
54
54
  }
55
55
  return (result, info);
56
56
  }
57
+ if let Some(mut expanded) = plum_core::trait_defaults::expandDefaults(source) {
58
+ // Each implementer gets its own copy of the trait defaults it inherits.
59
+ ast::numberIds(&mut expanded);
60
+ let expanded = std::rc::Rc::new(expanded);
61
+ let (result, mut info) = checkSourceFull(&expanded);
62
+ if info.lowered.is_none() {
63
+ info.lowered = Some(expanded);
64
+ }
65
+ return (result, info);
66
+ }
57
67
  if let Some(mut applied) = applyOwnGenerics(source) {
58
68
  // Check (and let codegen compile) the copy with bare own-generic names applied.
59
69
  ast::numberIds(&mut applied);
@@ -288,6 +298,7 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
288
298
  }
289
299
  }
290
300
 
301
+ let defaultsAt = plum_core::trait_defaults::defaultPositions(source);
291
302
  // Roots: every non-generic fn and every test. A generic fn is only
292
303
  // name-resolved here (its body is type-checked per instantiation below).
293
304
  for item in &source.items {
@@ -298,6 +309,11 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
298
309
  continue;
299
310
  }
300
311
  let mut local_errors = checkFn(f, &global_env, &ctx);
312
+ // A trait default's copy in an implementer: its errors are the default's own,
313
+ // reported once where the trait's default is checked.
314
+ if plum_core::trait_defaults::isDefaultCopy(f, &defaultsAt.0, &defaultsAt.1) {
315
+ local_errors.clear();
316
+ }
301
317
  if !fnGenericNames(f, &ctx).is_empty() {
302
318
  local_errors.retain(|e| e.kind == types::DiagKind::Resolution);
303
319
  drainCalls();
@@ -360,7 +376,10 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
360
376
  withCheck(|s| { let m = &s.inst_mode; m.set(true) });
361
377
  withCheck(|s| { let l = &s.cur_pos; l.set((f.line, f.column)) });
362
378
  let saved = withCheck(|s| { let r = &s.record; r.borrow_mut().replace(HashMap::new()) });
363
- let errs = checkFn(f, &global_env, &ctx);
379
+ let mut errs = checkFn(f, &global_env, &ctx);
380
+ if plum_core::trait_defaults::isDefaultCopy(f, &defaultsAt.0, &defaultsAt.1) {
381
+ errs.clear();
382
+ }
364
383
  let own = withCheck(|s| { let r = &s.record; std::mem::replace(&mut *r.borrow_mut(), saved) });
365
384
  withCheck(|s| { let s = &s.tsubst; *s.borrow_mut() = None });
366
385
  withCheck(|s| { let m = &s.inst_mode; m.set(false) });
compiler/checker/src/unification.rs CHANGED
@@ -125,6 +125,18 @@ pub(crate) fn bindMatch(pattern: &PlumType, actual: &PlumType, b: &mut Binds) {
125
125
  bindMatch(p, a, b);
126
126
  }
127
127
  }
128
+ // An implementer built where its trait object is expected: the trait's arguments
129
+ // pin the implementer's own (`Box(..)` as an `Actor[Msg]` is a `Box[Msg]`).
130
+ (TApp(..), TApp(..)) if hasInferVars(pattern) && isTraitObject(actual) => {
131
+ let traits = currentTraits();
132
+ if let Some((name, args)) = traits.traitObject(actual) {
133
+ if let Some(e) = traits.entriesOf(pattern).into_iter().find(|e| e.trait_name == name) {
134
+ for (p, a) in e.args.iter().zip(args) {
135
+ bindMatch(p, a, b);
136
+ }
137
+ }
138
+ }
139
+ }
128
140
  (TFun(ps, r), TFun(qs, s)) if ps.len() == qs.len() => {
129
141
  for (p, a) in ps.iter().zip(qs) {
130
142
  bindMatch(p, a, b);
compiler/checker/tests/checker/traits_tests.rs CHANGED
@@ -1,6 +1,5 @@
1
1
  #![allow(non_snake_case)]
2
- //! Traits: conformance, trait objects, `Self`, downcasts and bounds (checker only: codegen
2
+ //! Traits: conformance, trait objects, `Self`, downcasts and bounds.
3
- //! doesn't compile traits yet).
4
3
  use plum_checker::types::PlumType;
5
4
 
6
5
  const PRE: &str = "import std/Str\nimport std/Int\nimport std/Float\nimport std/List\n\nfun show(s: Str) = Unit\n\n";
@@ -553,8 +552,7 @@ fun main() =
553
552
  }
554
553
 
555
554
  #[test]
556
- fn traitsDontCompileYet() {
555
+ fn traitsCompile() {
557
556
  let source = plum_test_support::load("traits", &format!("{PRE}{ACTOR}fun main() = show(\"x\")\n")).unwrap();
558
- let err = plum_test_support::compileSource(&source).unwrap_err();
557
+ plum_test_support::compileSource(&source).unwrap_or_else(|e| panic!("{e}"));
559
- assert!(err.contains("traits not yet supported in codegen"), "{err}");
560
558
  }
compiler/core/src/forms.rs CHANGED
@@ -719,6 +719,15 @@ fn walkDeep(stmts: &mut [Stmt], fs: &mut dyn FnMut(&mut Stmt), fe: &mut dyn FnMu
719
719
  }
720
720
  }
721
721
 
722
+ /// Visits every statement and every expression of `body`, closure bodies included.
723
+ pub fn walkBody(body: &mut FnBody, fs: &mut dyn FnMut(&mut Stmt), fe: &mut dyn FnMut(&mut Expr)) {
724
+ match body {
725
+ FnBody::Expr(e) => walkDeepExpr(e, fs, fe),
726
+ FnBody::Block(b) => walkDeep(&mut b.stmts, fs, fe),
727
+ FnBody::Extern => {}
728
+ }
729
+ }
730
+
722
731
  fn walkDeepExpr(e: &mut Expr, fs: &mut dyn FnMut(&mut Stmt), fe: &mut dyn FnMut(&mut Expr)) {
723
732
  fe(e);
724
733
  match &mut e.kind {
compiler/core/src/layout.rs CHANGED
@@ -6,7 +6,8 @@
6
6
  //! Everything else is `Boxed` (a heap struct). A
7
7
  //! struct with a `fun init(self)` method (which may declare internal fields)
8
8
  //! is always `Boxed`; the parser records it in `StructInfo::forceBoxed`.
9
- //! A struct generated from an inline variant is always `Boxed` too.
9
+ //! A struct generated from an inline variant is always `Boxed` too, and so is a struct
10
+ //! that implements a trait (`is Actor`).
10
11
 
11
12
  use crate::ast::{Enum, Item};
12
13
  use std::collections::{HashMap, HashSet};
@@ -86,7 +87,9 @@ where
86
87
  if info.forceBoxed || e.variants.len() != 1 {
87
88
  return false;
88
89
  }
90
+ // A trait object holds a reference to its value, and the value's heap type is its
91
+ // tag: a type that implements a trait is a heap struct.
89
- if !e.generics.is_empty() {
92
+ if !e.generics.is_empty() || !e.implements.is_empty() {
90
93
  return false;
91
94
  }
92
95
  let v = &e.variants[0];
compiler/core/src/lib.rs CHANGED
@@ -31,6 +31,7 @@ pub mod session;
31
31
  pub mod simplify;
32
32
  pub mod spread_paths;
33
33
  pub mod tail;
34
+ pub mod trait_defaults;
34
35
  pub mod tests_lower;
35
36
  pub mod trmc;
36
37
  pub mod uniqueness;
compiler/core/src/trait_defaults.rs ADDED
@@ -0,0 +1,186 @@
1
+ //! Trait defaults, compiled per implementer.
2
+ //!
3
+ //! The parser keeps each default body of a trait as a method of the trait itself (`self`
4
+ //! the trait object). Here every type that implements the trait and doesn't override a
5
+ //! default gets its own copy of it, as an ordinary method of the type: the signature from
6
+ //! the trait with `Self` as the type and the trait's parameters as the `is` entry's
7
+ //! arguments, the body with fresh node ids. Inside a copy `self.key()` is a direct call,
8
+ //! and every pass sees an ordinary method. The copy keeps the default's position, so
9
+ //! `isDefaultCopy` can tell it from a method the type wrote.
10
+
11
+ use crate::ast::*;
12
+ use std::collections::{HashMap, HashSet};
13
+
14
+ /// The program with a copy of each inherited default added to each implementer, or
15
+ /// `None` when nothing is missing (the program already has every copy, or has no traits).
16
+ pub fn expandDefaults(src: &Source) -> Option<Source> {
17
+ let traits: HashMap<&str, &Trait> = src
18
+ .items
19
+ .iter()
20
+ .filter_map(|i| match i {
21
+ Item::Trait(t) => Some((t.name.as_str(), t)),
22
+ _ => None,
23
+ })
24
+ .collect();
25
+ if traits.is_empty() {
26
+ return None;
27
+ }
28
+ let defaults: HashMap<(&str, &str), &Fn> = src
29
+ .items
30
+ .iter()
31
+ .filter_map(|i| match i {
32
+ Item::Fn(f) if !matches!(f.body, FnBody::Extern) => {
33
+ let owner = f.type_param.as_deref()?;
34
+ traits.contains_key(owner).then_some(((owner, f.name.as_str()), f))
35
+ }
36
+ _ => None,
37
+ })
38
+ .collect();
39
+ let mut owned: HashSet<(String, String)> = src
40
+ .items
41
+ .iter()
42
+ .filter_map(|i| match i {
43
+ Item::Fn(f) => f.type_param.clone().map(|t| (t, f.name.clone())),
44
+ _ => None,
45
+ })
46
+ .collect();
47
+ let mut added: Vec<Item> = Vec::new();
48
+ for item in &src.items {
49
+ let Item::Enum(e) = item else { continue };
50
+ let selfTy = Type {
51
+ name: e.name.clone(),
52
+ generics: e.generics.iter().map(|g| Type { name: g.name.clone(), generics: vec![] }).collect(),
53
+ };
54
+ for entry in &e.implements {
55
+ let Some(t) = traits.get(entry.name.as_str()) else { continue };
56
+ if t.generics.len() != entry.generics.len() {
57
+ continue;
58
+ }
59
+ let mut subst: HashMap<String, Type> =
60
+ t.generics.iter().map(|g| g.name.clone()).zip(entry.generics.iter().cloned()).collect();
61
+ subst.insert(SELF_TYPE.to_string(), selfTy.clone());
62
+ for m in t.methods.iter().filter(|m| m.hasDefault) {
63
+ let key = (e.name.clone(), m.sig.name.clone());
64
+ if owned.contains(&key) {
65
+ continue;
66
+ }
67
+ let Some(d) = defaults.get(&(t.name.as_str(), m.sig.name.as_str())) else { continue };
68
+ let mut f = (*d).clone();
69
+ f.type_param = Some(e.name.clone());
70
+ for (p, sp) in f.params.iter_mut().zip(&m.sig.params) {
71
+ p.ty = substParam(&sp.ty, &subst);
72
+ }
73
+ f.returns = m.sig.returns.as_ref().map(|r| substType(r, &subst));
74
+ substBody(&mut f.body, &subst);
75
+ refreshFnIds(&mut f);
76
+ owned.insert(key);
77
+ added.push(Item::Fn(f));
78
+ }
79
+ }
80
+ }
81
+ if added.is_empty() {
82
+ return None;
83
+ }
84
+ let mut out = src.clone();
85
+ out.items.extend(added);
86
+ Some(out)
87
+ }
88
+
89
+ /// Whether `f` is a copy `expandDefaults` made: a method of a type at the position of a
90
+ /// default body of a trait. `defaultsAt` is `defaultPositions` of the program.
91
+ pub fn isDefaultCopy(f: &Fn, defaultsAt: &HashSet<(String, usize, usize, String)>, traitNames: &HashSet<String>) -> bool {
92
+ match &f.type_param {
93
+ Some(owner) if !traitNames.contains(owner) => {
94
+ defaultsAt.contains(&(f.file.clone(), f.line, f.column, f.name.clone()))
95
+ }
96
+ _ => false,
97
+ }
98
+ }
99
+
100
+ /// `(file, line, column, name)` of each default body of a trait in `src`.
101
+ pub fn defaultPositions(src: &Source) -> (HashSet<(String, usize, usize, String)>, HashSet<String>) {
102
+ let names: HashSet<String> = src
103
+ .items
104
+ .iter()
105
+ .filter_map(|i| match i {
106
+ Item::Trait(t) => Some(t.name.clone()),
107
+ _ => None,
108
+ })
109
+ .collect();
110
+ let at = src
111
+ .items
112
+ .iter()
113
+ .filter_map(|i| match i {
114
+ Item::Fn(f) if f.type_param.as_ref().is_some_and(|t| names.contains(t)) => {
115
+ Some((f.file.clone(), f.line, f.column, f.name.clone()))
116
+ }
117
+ _ => None,
118
+ })
119
+ .collect();
120
+ (at, names)
121
+ }
122
+
123
+ fn substType(t: &Type, s: &HashMap<String, Type>) -> Type {
124
+ if t.generics.is_empty() {
125
+ if let Some(r) = s.get(&t.name) {
126
+ return r.clone();
127
+ }
128
+ }
129
+ Type { name: t.name.clone(), generics: t.generics.iter().map(|g| substType(g, s)).collect() }
130
+ }
131
+
132
+ fn substParam(t: &ParamType, s: &HashMap<String, Type>) -> ParamType {
133
+ match t {
134
+ ParamType::Type(t) => ParamType::Type(substType(t, s)),
135
+ ParamType::Fn(ps, r) => {
136
+ ParamType::Fn(ps.iter().map(|p| substType(p, s)).collect(), r.as_ref().map(|r| Box::new(substType(r, s))))
137
+ }
138
+ }
139
+ }
140
+
141
+ /// The types written inside a body: annotations, closure parameter types, explicit type
142
+ /// arguments of a construction.
143
+ fn substBody(body: &mut FnBody, s: &HashMap<String, Type>) {
144
+ crate::forms::walkBody(
145
+ body,
146
+ &mut |st| {
147
+ if let StmtKind::Assign(a) = &mut st.kind {
148
+ if let Some(t) = &mut a.ty {
149
+ *t = substType(t, s);
150
+ }
151
+ }
152
+ },
153
+ &mut |e| match &mut e.kind {
154
+ ExprKind::Closure(c) => {
155
+ for t in c.param_types.iter_mut().flatten() {
156
+ *t = substType(t, s);
157
+ }
158
+ }
159
+ ExprKind::ClassCall(c) => {
160
+ for t in &mut c.generics {
161
+ *t = substType(t, s);
162
+ }
163
+ }
164
+ _ => {}
165
+ },
166
+ );
167
+ }
168
+
169
+ /// Removes the trait's own default bodies (methods of a trait, `self` the trait object),
170
+ /// once every implementer has its copy (`expandDefaults`). A rewrite pass resolves
171
+ /// `a.step()` on an `Actor` by the receiver's name: with `Actor.step` gone it sees an
172
+ /// unknown callee, any type's `step`, instead of the default body.
173
+ pub fn dropTraitBodies(src: &mut Source) {
174
+ let names: HashSet<String> = src
175
+ .items
176
+ .iter()
177
+ .filter_map(|i| match i {
178
+ Item::Trait(t) => Some(t.name.clone()),
179
+ _ => None,
180
+ })
181
+ .collect();
182
+ if names.is_empty() {
183
+ return;
184
+ }
185
+ src.items.retain(|item| !matches!(item, Item::Fn(f) if f.type_param.as_ref().is_some_and(|t| names.contains(t))));
186
+ }
compiler/core/src/uniqueness.rs CHANGED
@@ -1062,6 +1062,47 @@ impl<'a> Scan<'a> {
1062
1062
  }
1063
1063
  }
1064
1064
 
1065
+ /// `match x / T as v => ..`: `v` takes the value over from `x` (a downcast moves it), so `v`
1066
+ /// is unique in the arm when `x` is unique and the match is the unit's result (nothing runs
1067
+ /// after it) with `x` not mentioned in the arm. `None`: no downcast binds `v` in `c`.
1068
+ fn downcastMove(&mut self, m: &Match, c: &Case, tail: bool, depth: usize) -> Option<Result<(), String>> {
1069
+ let k = c.patterns.iter().position(|p| matches!(p, CasePattern::As { name, .. } if name == self.v))?;
1070
+ let v = self.v.to_string();
1071
+ let others = c.patterns.iter().enumerate().any(|(i, p)| {
1072
+ let mut names = vec![];
1073
+ crate::visit::patternBinders(p, &mut names);
1074
+ i != k && names.contains(&v)
1075
+ });
1076
+ let Some(x) = m.subjects.get(k).and_then(varName).filter(|x| *x != v && !others) else {
1077
+ return Some(Err(format!("`{v}` is bound by a downcast of a value that is not a variable")));
1078
+ };
1079
+ if !tail {
1080
+ return Some(Err(format!("`{v}` is bound by a downcast in a match that is not the result")));
1081
+ }
1082
+ let mut usedInArm = false;
1083
+ let mut seen = |n: Node| {
1084
+ if let Node::E(e) = n {
1085
+ usedInArm |= isVar(e, x);
1086
+ }
1087
+ !usedInArm
1088
+ };
1089
+ walkBlock(&c.body, &mut seen);
1090
+ if let Some(g) = &c.guard {
1091
+ walkExpr(g, &mut seen);
1092
+ }
1093
+ if usedInArm {
1094
+ return Some(Err(format!("`{x}` is still used in the arm that downcasts it to `{v}`")));
1095
+ }
1096
+ if let Err(why) = self.an.varOk(self.unit, x) {
1097
+ return Some(Err(format!("`{v}` is a downcast of `{x}`, which may be shared: {why}")));
1098
+ }
1099
+ match self.boundDepth {
1100
+ None => self.boundDepth = Some(depth + 1),
1101
+ Some(_) => return Some(Err(format!("`{v}` is bound more than once"))),
1102
+ }
1103
+ Some(Ok(()))
1104
+ }
1105
+
1065
1106
  fn stmt(&mut self, s: &Stmt, tail: bool, live: bool, depth: usize) {
1066
1107
  let v = self.v.to_string();
1067
1108
  match &s.kind {
@@ -1140,12 +1181,24 @@ impl<'a> Scan<'a> {
1140
1181
  if m.cases.iter().any(|c| matches!(c.patterns.get(k), Some(CasePattern::Name(_)))) {
1141
1182
  self.fail(format!("`{v}` is also held by a pattern binding"));
1142
1183
  }
1184
+ // A downcast `T as o` moves the value into `o` only if `v` is dead in
1185
+ // that arm and after the match; otherwise `o` is a second holder.
1186
+ if m.cases.iter().any(|c| {
1187
+ matches!(c.patterns.get(k), Some(CasePattern::As { .. }))
1188
+ && (live || self.mentionsBlock(&c.body) || c.guard.as_ref().is_some_and(|g| self.mentions(g)))
1189
+ }) {
1190
+ self.fail(format!("`{v}` is also held by a downcast binding"));
1191
+ }
1143
1192
  } else {
1144
1193
  self.expr(sub, false, live || inCases || m.subjects.iter().skip(k + 1).any(|x| self.mentions(x)));
1145
1194
  }
1146
1195
  }
1147
1196
  for c in &m.cases {
1197
+ match self.downcastMove(m, c, tail, depth) {
1198
+ Some(Ok(())) => {}
1199
+ Some(Err(why)) => self.fail(why),
1148
- self.checkPatterns(&c.patterns);
1200
+ None => self.checkPatterns(&c.patterns),
1201
+ }
1149
1202
  if let Some(g) = &c.guard {
1150
1203
  self.expr(g, false, true);
1151
1204
  }
compiler/driver/src/lib.rs CHANGED
@@ -146,10 +146,7 @@ pub fn check(source: &Source, opts: &PassOptions) -> Result<TypedInfo, Vec<Diagn
146
146
  pub fn check_with(source: &Source, opts: &PassOptions, passes: &[Pass]) -> Result<TypedInfo, Vec<Diagnostic>> {
147
147
  let (result, info) = checkProgram(source);
148
148
  let mut st = State { pre: preUnionSource(source), result, info, fip: Vec::new() };
149
- // The rewrite passes don't know traits yet (dispatch, downcasts): a program with one is
150
- // only checked.
151
- let hasTraits = source.items.iter().any(|i| matches!(i, plum_core::ast::Item::Trait(_)));
152
- if st.result.is_ok() && !hasTraits {
149
+ if st.result.is_ok() {
153
150
  if opts.explain && !(opts.fusion && opts.fbip) && !plum_core::fip::origins(&st.pre).isEmpty() {
154
151
  eprintln!("fusion: fip fun is not enforced: it needs the uniqueness proof, which --no-fusion and --no-fbip switch off");
155
152
  }
@@ -236,6 +233,10 @@ fn runPass(pass: &Pass, original: &Source, opts: &PassOptions, st: &mut State) {
236
233
  /// The checked program before union lowering: own generics applied and `for` loops lowered.
237
234
  fn preUnionSource(source: &Source) -> Source {
238
235
  let mut cur = source.clone();
236
+ if let Some(expanded) = plum_core::trait_defaults::expandDefaults(&cur) {
237
+ cur = expanded;
238
+ plum_core::ast::numberIds(&mut cur);
239
+ }
239
240
  while let Some(applied) = plum_checker::applyOwnGenerics(&cur) {
240
241
  cur = applied;
241
242
  plum_core::ast::numberIds(&mut cur);
@@ -246,5 +247,6 @@ fn preUnionSource(source: &Source) -> Source {
246
247
  cur = plum_core::forms::finish(&cur);
247
248
  plum_core::ast::numberIds(&mut cur);
248
249
  }
250
+ plum_core::trait_defaults::dropTraitBodies(&mut cur);
249
251
  cur
250
252
  }
compiler/wasm-codegen/src/calls.rs CHANGED
@@ -266,6 +266,14 @@ pub(crate) fn compileMethodCallAs(
266
266
  ctx: &LocalCtx,
267
267
  state: &mut ModuleState,
268
268
  ) -> Result<(), String> {
269
+ // A call on a trait object: its dispatcher.
270
+ if let Some(d) = dispatcherFor(obj_ty, method) {
271
+ let (func_idx, sig) = d?;
272
+ compileExpr(object, body, ctx, state)?;
273
+ compileCallArgs(method, &call.args, &sig, body, ctx, state)?;
274
+ emitCall(func_idx, &sig, call.tail, result_expr, body, ctx);
275
+ return Ok(());
276
+ }
269
277
  // A call the checker resolved to a generic instantiation.
270
278
  if let Some((func_idx, sig)) = ctx
271
279
  .call_inst
compiler/wasm-codegen/src/context.rs CHANGED
@@ -281,6 +281,12 @@ 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 program's traits.
285
+ pub(crate) traits: Option<std::rc::Rc<plum_checker::traits::Traits>>,
286
+ /// (trait object type, method) -> its dispatcher (see `traits.rs`).
287
+ pub(crate) dispatchers: HashMap<DispatchKey, (u32, FuncSig)>,
288
+ /// Trait object type -> its `==` helper, when an implementer has an `eq` method.
289
+ pub(crate) trait_eq: HashMap<PlumType, u32>,
284
290
  }
285
291
 
286
292
  impl GenState {
compiler/wasm-codegen/src/driver.rs CHANGED
@@ -6,43 +6,46 @@ use crate::*;
6
6
 
7
7
  /// State shared by the registration stages, in the order they fill it.
8
8
  pub(crate) struct Setup<'a> {
9
- source: &'a ast::Source,
9
+ pub(crate) source: &'a ast::Source,
10
- extra_exports: &'a [(String, String)],
10
+ pub(crate) extra_exports: &'a [(String, String)],
11
- base_types: UnitTypes,
11
+ pub(crate) base_types: UnitTypes,
12
- inst_types: Vec<UnitTypes>,
12
+ pub(crate) inst_types: Vec<UnitTypes>,
13
- instantiations: Vec<plum_checker::Instantiation>,
13
+ pub(crate) instantiations: Vec<plum_checker::Instantiation>,
14
- call_inst: HashMap<(Option<usize>, ast::NodeId, bool), usize>,
14
+ pub(crate) call_inst: HashMap<(Option<usize>, ast::NodeId, bool), usize>,
15
- op_calls: HashMap<ast::NodeId, std::rc::Rc<ast::FnCall>>,
15
+ pub(crate) op_calls: HashMap<ast::NodeId, std::rc::Rc<ast::FnCall>>,
16
- global_env: TypeEnv,
16
+ pub(crate) global_env: TypeEnv,
17
- methods: MethodEnv,
17
+ pub(crate) methods: MethodEnv,
18
- enum_variants: EnumVariants,
18
+ pub(crate) enum_variants: EnumVariants,
19
- enum_params: EnumParams,
19
+ pub(crate) enum_params: EnumParams,
20
- min_required: plum_checker::MinRequiredArgs,
20
+ pub(crate) min_required: plum_checker::MinRequiredArgs,
21
- primitive_generics: plum_checker::PrimitiveGenerics,
21
+ pub(crate) primitive_generics: plum_checker::PrimitiveGenerics,
22
- eg: EnumGenerics,
22
+ pub(crate) eg: EnumGenerics,
23
- units: Vec<UnitDef<'a>>,
23
+ pub(crate) units: Vec<UnitDef<'a>>,
24
- known_fns: HashSet<String>,
24
+ pub(crate) known_fns: HashSet<String>,
25
- type_apps: Vec<PlumType>,
25
+ pub(crate) type_apps: Vec<PlumType>,
26
- type_funs: Vec<PlumType>,
26
+ pub(crate) type_funs: Vec<PlumType>,
27
- module: WasmModule,
27
+ pub(crate) module: WasmModule,
28
- gc_types: Option<GcTypeRegistry>,
28
+ pub(crate) gc_types: Option<GcTypeRegistry>,
29
- value_names: Vec<String>,
29
+ pub(crate) value_names: Vec<String>,
30
- func_ids: HashMap<String, u32>,
30
+ pub(crate) func_ids: HashMap<String, u32>,
31
- func_sigs: HashMap<String, FuncSig>,
31
+ pub(crate) func_sigs: HashMap<String, FuncSig>,
32
32
  /// (key, import index, wrapper params, results, leading receiver params the host import lacks)
33
- extern_wrappers: Vec<(String, u32, Vec<ValType>, Vec<ValType>, usize)>,
33
+ pub(crate) extern_wrappers: Vec<(String, u32, Vec<ValType>, Vec<ValType>, usize)>,
34
- singleton_globals: HashMap<(PlumType, String), u32>,
34
+ pub(crate) singleton_globals: HashMap<(PlumType, String), u32>,
35
- start_body: Vec<u8>,
35
+ pub(crate) start_body: Vec<u8>,
36
- start_func_idx: u32,
36
+ pub(crate) start_func_idx: u32,
37
- closure_call_types: HashMap<ClosureSigKey, u32>,
37
+ pub(crate) closure_call_types: HashMap<ClosureSigKey, u32>,
38
- inst_funcs: HashMap<usize, (u32, FuncSig)>,
38
+ pub(crate) inst_funcs: HashMap<usize, (u32, FuncSig)>,
39
- raw_closures: Vec<(usize, RawClosure<'a>)>,
39
+ pub(crate) raw_closures: Vec<(usize, RawClosure<'a>)>,
40
- named_fn_refs: HashSet<(String, PlumType)>,
40
+ pub(crate) named_fn_refs: HashSet<(String, PlumType)>,
41
- closure_type_indices: Vec<u32>,
41
+ pub(crate) closure_type_indices: Vec<u32>,
42
- closures: HashMap<(usize, usize), ClosureInfo>,
42
+ pub(crate) closures: HashMap<(usize, usize), ClosureInfo>,
43
- closure_asts: HashMap<(usize, usize), &'a ast::Closure>,
43
+ pub(crate) closure_asts: HashMap<(usize, usize), &'a ast::Closure>,
44
- named_fn_values: HashMap<(String, PlumType), u32>,
44
+ pub(crate) named_fn_values: HashMap<(String, PlumType), u32>,
45
- const_inits: Vec<(String, ConstInit<'a>, u32)>,
45
+ pub(crate) const_inits: Vec<(String, ConstInit<'a>, u32)>,
46
+ pub(crate) traits: std::rc::Rc<plum_checker::traits::Traits>,
47
+ pub(crate) inst_index: HashMap<(String, Vec<PlumType>), usize>,
48
+ pub(crate) dispatch_errors: Vec<String>,
46
49
  }
47
50
 
48
51
  pub(crate) fn unitTypesOf<'t>(inst_types: &'t [UnitTypes], base_types: &'t UnitTypes, u: &UnitDef) -> &'t UnitTypes {
@@ -88,6 +91,8 @@ impl<'a> Setup<'a> {
88
91
  inst_expr_types,
89
92
  call_inst,
90
93
  op_calls,
94
+ traits,
95
+ inst_index,
91
96
  ..
92
97
  } = typed;
93
98
  // Per-instantiation expression types, split out by instantiation id.
@@ -157,6 +162,9 @@ impl<'a> Setup<'a> {
157
162
  closure_asts: HashMap::new(),
158
163
  named_fn_values: HashMap::new(),
159
164
  const_inits: Vec::new(),
165
+ traits,
166
+ inst_index,
167
+ dispatch_errors: Vec::new(),
160
168
  }
161
169
  }
162
170
 
@@ -164,11 +172,21 @@ impl<'a> Setup<'a> {
164
172
  pub(crate) fn planUnits(&mut self) {
165
173
  let Setup { source, eg, methods, enum_variants, enum_params, min_required, primitive_generics, instantiations, units, known_fns, .. } = self;
166
174
  // ---- units: every non-generic fn, plus one per reached instantiation ----
175
+ // A trait's own default bodies are never called: a call on a trait object goes to the
176
+ // value's type, which has its own copy of each default (`plum_core::trait_defaults`).
177
+ let trait_names: HashSet<&str> = source
178
+ .items
179
+ .iter()
180
+ .filter_map(|i| match i {
181
+ ast::Item::Trait(t) => Some(t.name.as_str()),
182
+ _ => None,
183
+ })
184
+ .collect();
167
185
  let all_fns: Vec<&ast::Fn> = source
168
186
  .items
169
187
  .iter()
170
188
  .filter_map(|item| match item {
171
- ast::Item::Fn(f) if !f.is_extern => Some(f),
189
+ ast::Item::Fn(f) if !f.is_extern && !f.type_param.as_deref().is_some_and(|t| trait_names.contains(t)) => Some(f),
172
190
  _ => None,
173
191
  })
174
192
  .collect();
compiler/wasm-codegen/src/expr.rs CHANGED
@@ -186,6 +186,9 @@ pub(crate) fn compileExpr(
186
186
  }
187
187
  ast::Expr { kind: ast::ExprKind::Compare(c), .. } => {
188
188
  let left_ty = inferLocalType(&c.left, ctx);
189
+ if isTraitObjectTy(&left_ty) {
190
+ return compileTraitEq(c, &left_ty, body, ctx, state);
191
+ }
189
192
  if let PlumType::TNamed(vn) = &left_ty {
190
193
  if isValueTy(&left_ty) {
191
194
  // Fieldwise equality (a value enum with an `eq` method took the
compiler/wasm-codegen/src/fnbody.rs CHANGED
@@ -64,6 +64,9 @@ impl<'a> Collector<'a> {
64
64
  self.bind(n, ty.clone());
65
65
  }
66
66
  }
67
+ ast::CasePattern::As { ty, name } => {
68
+ self.bind(name, asPatternType(ty, &self.types.subst));
69
+ }
67
70
  ast::CasePattern::Class { name, fields, .. } => {
68
71
  let key = patKey(pat);
69
72
  let slot = self.next_nested_class_slot;
compiler/wasm-codegen/src/freevars.rs CHANGED
@@ -78,7 +78,7 @@ pub(crate) fn fvCollectBoundBlock(block: &ast::Block, bound: &mut std::collectio
78
78
 
79
79
  pub(crate) fn fvCollectPatternBindings(pat: &ast::CasePattern, bound: &mut std::collections::HashSet<String>) {
80
80
  match pat {
81
- ast::CasePattern::Name(n) => {
81
+ ast::CasePattern::Name(n) | ast::CasePattern::As { name: n, .. } => {
82
82
  bound.insert(n.clone());
83
83
  }
84
84
  ast::CasePattern::Class { fields, .. } => {
compiler/wasm-codegen/src/lib.rs CHANGED
@@ -28,6 +28,7 @@ mod keys;
28
28
  mod matching;
29
29
  mod module;
30
30
  mod stmts;
31
+ mod traits;
31
32
  mod units;
32
33
  mod values;
33
34
 
@@ -49,6 +50,7 @@ pub(crate) use keys::*;
49
50
  pub(crate) use matching::*;
50
51
  pub use module::*;
51
52
  pub(crate) use stmts::*;
53
+ pub(crate) use traits::*;
52
54
  pub(crate) use units::*;
53
55
  pub(crate) use values::*;
54
56
 
@@ -105,37 +107,17 @@ pub fn compile(source: &ast::Source, opts: &CompileOptions) -> Result<Output, Ve
105
107
  if opts.tests {
106
108
  let prog = plum_core::tests_lower::lowerTests(source);
107
109
  let typed = plum_driver::check(&prog.source, &opts.passes)?;
108
- noTraits(&prog.source)?;
109
110
  let mut extra = prog.extraExports.clone();
110
111
  extra.extend(gameExports(game));
111
112
  let (wasm, fn_keys) = compileSourceInner(&prog.source, &extra, typed).map_err(codegenDiag)?;
112
113
  Ok(Output { wasm, fn_keys, test_names: prog.names, isGame: game })
113
114
  } else {
114
115
  let typed = plum_driver::check(source, &opts.passes)?;
115
- noTraits(source)?;
116
116
  let (wasm, fn_keys) = compileSourceInner(source, &gameExports(game), typed).map_err(codegenDiag)?;
117
117
  Ok(Output { wasm, fn_keys, test_names: Vec::new(), isGame: game })
118
118
  }
119
119
  }
120
120
 
121
- /// Traits are checked but not compiled yet: a program that declares one stops here with a
122
- /// diagnostic at the first trait.
123
- fn noTraits(source: &ast::Source) -> Result<(), Vec<Diagnostic>> {
124
- match source.items.iter().find_map(|i| match i {
125
- ast::Item::Trait(t) => Some(t),
126
- _ => None,
127
- }) {
128
- Some(t) => Err(vec![Diagnostic::new(
129
- DiagKind::Codegen,
130
- t.file.clone(),
131
- t.line,
132
- t.column,
133
- format!("trait '{}': traits not yet supported in codegen", t.name),
134
- )]),
135
- None => Ok(()),
136
- }
137
- }
138
-
139
121
  /// `layout <Name>: flat|boxed` for every struct, as decided by `plum_core::layout`.
140
122
  pub fn explainLayouts(source: &ast::Source) -> Vec<String> {
141
123
  source
@@ -242,6 +224,10 @@ fn compileSourceUnits(
242
224
  setup.emitStrConstructor();
243
225
  setup.registerClosureCallTypes();
244
226
  setup.registerUnitFns();
227
+ setup.registerDispatchers();
228
+ if !setup.dispatch_errors.is_empty() {
229
+ return Err(setup.dispatch_errors.join("\n"));
230
+ }
245
231
  setup.discoverClosures();
246
232
  setup.registerClosureTypes();
247
233
  setup.registerClosureFns();
compiler/wasm-codegen/src/matching.rs CHANGED
@@ -341,8 +341,47 @@ pub(crate) fn compileCasePositions(
341
341
  let pat = &case.patterns[pos];
342
342
  let (subject_vt, scratch_local) = all_subjects[pos];
343
343
  match pat {
344
- ast::CasePattern::As { ty, .. } => {
344
+ ast::CasePattern::As { ty, name } => {
345
+ let subject_ty = ctx
346
+ .subject_ptypes
347
+ .borrow()
348
+ .get(&scratch_local)
349
+ .cloned()
350
+ .unwrap_or_else(|| plumTypeFromValtypeHint(subject_vt));
351
+ let target = asTarget(ty, &subject_ty, ctx.unit_subst, ctx.gc_types);
352
+ let bind = |cast: Option<u32>, t: &PlumType, body: &mut Vec<u8>| -> Result<(), String> {
353
+ let idx = ctx
354
+ .locals
355
+ .get(name)
356
+ .copied()
345
- return Err(format!("`{ty} as ..`: traits not yet supported in codegen"));
357
+ .ok_or_else(|| format!("internal codegen error: missing binding local '{}'", name))?;
358
+ Instruction::LocalGet(scratch_local).encode(body);
359
+ if let Some(tag) = cast {
360
+ Instruction::RefCastNonNull(HeapType::Concrete(tag)).encode(body);
361
+ }
362
+ Instruction::LocalSet(idx).encode(body);
363
+ ctx.type_env.borrow_mut().insert(name.clone(), TypeScheme::mono(t.clone()));
364
+ Ok(())
365
+ };
366
+ match target {
367
+ AsTarget::Always(t) => {
368
+ bind(None, &t, body)?;
369
+ compileCasePositions(case, pos + 1, all_subjects, rest, result_vt, exhaustive_fallback, body, ctx, state)
370
+ }
371
+ AsTarget::Never => compileMatchArmsMulti(rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state),
372
+ AsTarget::Test(tag, t) => {
373
+ Instruction::LocalGet(scratch_local).encode(body);
374
+ Instruction::RefTestNonNull(HeapType::Concrete(tag)).encode(body);
375
+ Instruction::If(blockTypeFor(result_vt)).encode(body);
376
+ let _tg = TailDepth::enter(&ctx.tail_depth);
377
+ bind(Some(tag), &t, body)?;
378
+ compileCasePositions(case, pos + 1, all_subjects, rest, result_vt, exhaustive_fallback, body, ctx, state)?;
379
+ Instruction::Else.encode(body);
380
+ compileMatchArmsMulti(rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state)?;
381
+ Instruction::End.encode(body);
382
+ Ok(())
383
+ }
384
+ }
346
385
  }
347
386
  ast::CasePattern::Wildcard => {
348
387
  // Always matches this position; move on to the next one.
@@ -743,7 +782,45 @@ pub(crate) fn compileFieldPatterns(
743
782
  let inst_vt = plumTypeToValtype(field_ty);
744
783
 
745
784
  match pat {
746
- ast::CasePattern::As { ty, .. } => Err(format!("`{ty} as ..`: traits not yet supported in codegen")),
785
+ ast::CasePattern::As { ty, name } => {
786
+ let target = asTarget(ty, field_ty, ctx.unit_subst, ctx.gc_types);
787
+ let idx = ctx
788
+ .locals
789
+ .get(name)
790
+ .copied()
791
+ .ok_or_else(|| format!("internal codegen error: missing binding local '{}'", name))?;
792
+ let load = |cast: Option<u32>, t: &PlumType, body: &mut Vec<u8>| -> Result<(), String> {
793
+ if isValueTy(field_ty) {
794
+ return Err(format!("codegen: `{ty} as {name}` on a field of the value type {field_ty}"));
795
+ }
796
+ emitContainerField(body, ctx, container_local, container_type_idx, fpos, leaf_map);
797
+ if let Some(tag) = cast {
798
+ Instruction::RefCastNonNull(HeapType::Concrete(tag)).encode(body);
799
+ }
800
+ Instruction::LocalSet(idx).encode(body);
801
+ ctx.type_env.borrow_mut().insert(name.clone(), TypeScheme::mono(t.clone()));
802
+ Ok(())
803
+ };
804
+ match target {
805
+ AsTarget::Always(t) => {
806
+ load(None, &t, body)?;
807
+ compileFieldPatterns(fields, field_types, inst_types, fpos + 1, container_local, container_type_idx, leaf_map, rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state, on_match)
808
+ }
809
+ AsTarget::Never => compileMatchArmsMulti(rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state),
810
+ AsTarget::Test(tag, t) => {
811
+ emitContainerField(body, ctx, container_local, container_type_idx, fpos, leaf_map);
812
+ Instruction::RefTestNonNull(HeapType::Concrete(tag)).encode(body);
813
+ Instruction::If(blockTypeFor(result_vt)).encode(body);
814
+ let _tg = TailDepth::enter(&ctx.tail_depth);
815
+ load(Some(tag), &t, body)?;
816
+ compileFieldPatterns(fields, field_types, inst_types, fpos + 1, container_local, container_type_idx, leaf_map, rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state, on_match)?;
817
+ Instruction::Else.encode(body);
818
+ compileMatchArmsMulti(rest, all_subjects, result_vt, exhaustive_fallback, body, ctx, state)?;
819
+ Instruction::End.encode(body);
820
+ Ok(())
821
+ }
822
+ }
823
+ }
747
824
  ast::CasePattern::Wildcard => compileFieldPatterns(
748
825
  fields,
749
826
  field_types,
compiler/wasm-codegen/src/traits.rs ADDED
@@ -0,0 +1,320 @@
1
+ //! Trait objects.
2
+ //!
3
+ //! A trait object (`Actor`, `Actor[Msg]`) is an `anyref` to the value itself: every type
4
+ //! that implements a trait is a heap struct (see `plum_core::layout`), so an implementer
5
+ //! becomes a trait object with no instruction, and the value's wasm-gc type is its tag.
6
+ //! A method call on a trait object calls the trait's dispatcher, one wasm function per
7
+ //! (trait object type, method): a `ref.test` per type that implements the trait in the
8
+ //! program (whole-program, the same code a `match` makes), each arm a `return_call` of that
9
+ //! type's own method (or its copy of the default, see `plum_core::trait_defaults`).
10
+
11
+ use crate::*;
12
+ use plum_checker::traits::Traits;
13
+
14
+ /// The program's traits (set by `Setup::registerDispatchers`).
15
+ pub(crate) fn programTraits() -> std::rc::Rc<Traits> {
16
+ withGen(|s| s.traits.clone()).unwrap_or_default()
17
+ }
18
+
19
+ /// Whether `ty` is a trait object of this program.
20
+ pub(crate) fn isTraitObjectTy(ty: &PlumType) -> bool {
21
+ programTraits().traitObject(ty).is_some()
22
+ }
23
+
24
+ /// The concrete types of the program (registered in `reg`) that implement the trait object
25
+ /// `obj`, in registry order.
26
+ pub(crate) fn implementersOf(obj: &PlumType, reg: &GcTypeRegistry, traits: &Traits) -> Vec<PlumType> {
27
+ let Some((name, args)) = traits.traitObject(obj) else { return Vec::new() };
28
+ reg.instances
29
+ .iter()
30
+ .filter(|c| {
31
+ traits.entriesOf(c).iter().any(|e| {
32
+ e.trait_name == name
33
+ && e.args.len() == args.len()
34
+ && e.args.iter().zip(args).all(|(a, b)| canonTy(a) == canonTy(b))
35
+ })
36
+ })
37
+ .cloned()
38
+ .collect()
39
+ }
40
+
41
+ /// The heap type a value of the implementer `c` has (its tag): a struct's one variant, or an
42
+ /// enum's supertype.
43
+ pub(crate) fn tagIdx(c: &PlumType, reg: &GcTypeRegistry) -> Option<u32> {
44
+ reg.classIdx(c).or_else(|| reg.superIdx(c))
45
+ }
46
+
47
+ /// One dispatcher to build: the trait object type and the method.
48
+ pub(crate) type DispatchKey = (PlumType, String);
49
+
50
+ /// The dispatcher of `obj.method(..)`, if `obj` is a trait object.
51
+ pub(crate) fn dispatcherFor(obj: &PlumType, method: &str) -> Option<Result<(u32, FuncSig), String>> {
52
+ if !isTraitObjectTy(obj) {
53
+ return None;
54
+ }
55
+ let key = (canonTy(obj), method.to_string());
56
+ Some(withGen(|s| s.dispatchers.get(&key).cloned()).ok_or_else(|| {
57
+ format!("internal codegen error: no dispatcher for {}.{}", obj, method)
58
+ }))
59
+ }
60
+
61
+ /// The `==` helper of trait object `obj`, when one of its implementers has an `eq` method.
62
+ pub(crate) fn traitEqHelper(obj: &PlumType) -> Option<u32> {
63
+ withGen(|s| s.trait_eq.get(&canonTy(obj)).copied())
64
+ }
65
+
66
+ /// Every method call on a trait object and every `==` with a trait object on its left in
67
+ /// `body`, typed by `types`.
68
+ pub(crate) fn traitSites(body: &ast::FnBody, types: &UnitTypes, traits: &Traits, calls: &mut Vec<DispatchKey>, eqs: &mut Vec<PlumType>) {
69
+ let mut visit = |e: &ast::Expr| match &e.kind {
70
+ ast::ExprKind::Attribute(a) => {
71
+ if let ast::AttrKind::Method(call) = &a.attr {
72
+ if let Some(t) = types.get(&a.object.id) {
73
+ if traits.traitObject(t).is_some() && !hasFreeTy(t) {
74
+ let k = (canonTy(t), call.name.clone());
75
+ if !calls.contains(&k) {
76
+ calls.push(k);
77
+ }
78
+ }
79
+ }
80
+ }
81
+ }
82
+ ast::ExprKind::Compare(c) if matches!(c.op, ast::CmpOp::Eq | ast::CmpOp::Neq | ast::CmpOp::NotEq2) => {
83
+ if let Some(t) = types.get(&c.left.id) {
84
+ if traits.traitObject(t).is_some() && !hasFreeTy(t) && !eqs.contains(&canonTy(t)) {
85
+ eqs.push(canonTy(t));
86
+ }
87
+ }
88
+ }
89
+ _ => {}
90
+ };
91
+ match body {
92
+ ast::FnBody::Expr(e) => plum_core::visit::walkRef(e, &mut visit),
93
+ ast::FnBody::Block(b) => plum_core::visit::walkBlockRef(b, &mut visit),
94
+ ast::FnBody::Extern => {}
95
+ }
96
+ }
97
+
98
+ /// The wasm function and signature of `c`'s method `method`: a plain method, or the
99
+ /// instantiation of a generic implementer's method.
100
+ fn implementerMethod(
101
+ c: &PlumType,
102
+ method: &str,
103
+ func_ids: &HashMap<String, u32>,
104
+ func_sigs: &HashMap<String, FuncSig>,
105
+ inst_funcs: &HashMap<usize, (u32, FuncSig)>,
106
+ inst_index: &HashMap<(String, Vec<PlumType>), usize>,
107
+ ) -> Option<(u32, FuncSig)> {
108
+ match c {
109
+ PlumType::TApp(n, args) => {
110
+ let id = inst_index.get(&(format!("{n}.{method}"), args.clone()))?;
111
+ inst_funcs.get(id).cloned()
112
+ }
113
+ _ => {
114
+ let n = plum_checker::nominalName(c)?;
115
+ let key = format!("{n}::{method}");
116
+ Some((*func_ids.get(&key)?, func_sigs.get(&key)?.clone()))
117
+ }
118
+ }
119
+ }
120
+
121
+ /// The signature of the dispatcher of `obj.method`: `self` as `anyref`, then the trait's
122
+ /// parameters with `Self` as the trait object.
123
+ fn dispatcherSig(obj: &PlumType, method: &str, traits: &Traits, reg: &GcTypeRegistry) -> Result<FuncSig, String> {
124
+ let sig = traits
125
+ .methodSig(obj, method, obj)
126
+ .ok_or_else(|| format!("codegen: {obj} has no method '{method}'"))?;
127
+ let PlumType::TFun(params, ret) = sig else {
128
+ return Err(format!("codegen: {obj}.{method} is not a method"));
129
+ };
130
+ let mut vts = vec![ValType::Ref(RefType::ANYREF)];
131
+ for p in &params {
132
+ leafTypes(p, reg, &mut vts);
133
+ }
134
+ let ret_vt = if matches!(*ret, PlumType::TUnit) { Vec::new() } else { flatValtypes(&ret, reg) };
135
+ Ok(FuncSig {
136
+ params: vts,
137
+ ret: ret_vt,
138
+ param_defaults: vec![None; params.len()],
139
+ decl_params: params,
140
+ decl_ret: *ret,
141
+ inst: None,
142
+ })
143
+ }
144
+
145
+ impl<'a> Setup<'a> {
146
+ /// One dispatcher per (trait object type, method) called somewhere, and one `==` helper
147
+ /// per trait object compared whose implementers have an `eq` method. Needs every unit's
148
+ /// wasm function (`registerUnitFns`).
149
+ pub(crate) fn registerDispatchers(&mut self) {
150
+ let traits = self.traits.clone();
151
+ withGen(|s| s.traits = Some(traits.clone()));
152
+ if traits.isEmpty() {
153
+ return;
154
+ }
155
+ let mut calls: Vec<DispatchKey> = Vec::new();
156
+ let mut eqs: Vec<PlumType> = Vec::new();
157
+ for u in &self.units {
158
+ let types = unitTypesOf(&self.inst_types, &self.base_types, u);
159
+ traitSites(&u.f.body, types, &traits, &mut calls, &mut eqs);
160
+ }
161
+ let reg = self.gc_types.clone().expect("registry built");
162
+ for (obj, method) in calls {
163
+ let sig = match dispatcherSig(&obj, &method, &traits, &reg) {
164
+ Ok(s) => s,
165
+ Err(e) => {
166
+ self.dispatch_errors.push(e);
167
+ continue;
168
+ }
169
+ };
170
+ let mut b: Vec<u8> = vec![0u8];
171
+ for c in implementersOf(&obj, &reg, &traits) {
172
+ let (Some(tag), Some((f, csig))) = (
173
+ tagIdx(&c, &reg),
174
+ implementerMethod(&c, &method, &self.func_ids, &self.func_sigs, &self.inst_funcs, &self.inst_index),
175
+ ) else {
176
+ self.dispatch_errors.push(format!("codegen: {c} has no compiled method '{method}' for a call on {obj}"));
177
+ continue;
178
+ };
179
+ if csig.params.len() != sig.params.len() || !csig.ret.iter().zip(&sig.ret).all(|(a, b)| a == b || isRefTo(*b, *a)) || csig.ret.len() != sig.ret.len() {
180
+ self.dispatch_errors.push(format!(
181
+ "codegen: {c}.{method} can't be called through {obj}: a parameter or result that mentions Self inside another type is not supported"
182
+ ));
183
+ continue;
184
+ }
185
+ Instruction::LocalGet(0).encode(&mut b);
186
+ Instruction::RefTestNonNull(HeapType::Concrete(tag)).encode(&mut b);
187
+ Instruction::If(BlockType::Empty).encode(&mut b);
188
+ Instruction::LocalGet(0).encode(&mut b);
189
+ Instruction::RefCastNonNull(HeapType::Concrete(tag)).encode(&mut b);
190
+ let mut ok = true;
191
+ for (i, (want, have)) in csig.params.iter().zip(&sig.params).enumerate().skip(1) {
192
+ Instruction::LocalGet(i as u32).encode(&mut b);
193
+ if want != have {
194
+ // A `Self` parameter: the trait object is cast to the type.
195
+ match want {
196
+ ValType::Ref(RefType { heap_type: HeapType::Concrete(idx), .. }) => {
197
+ Instruction::RefCastNonNull(HeapType::Concrete(*idx)).encode(&mut b)
198
+ }
199
+ _ => ok = false,
200
+ }
201
+ }
202
+ }
203
+ if !ok {
204
+ self.dispatch_errors.push(format!("codegen: {c}.{method}: its parameters don't fit {obj}'s"));
205
+ }
206
+ Instruction::ReturnCall(f).encode(&mut b);
207
+ Instruction::End.encode(&mut b);
208
+ }
209
+ Instruction::Unreachable.encode(&mut b);
210
+ Instruction::End.encode(&mut b);
211
+ let t = self.module.addType(&sig.params, &sig.ret);
212
+ let idx = self.module.addFunction(t, &b);
213
+ self.module.nameFunction(idx, &format!("dispatch.{obj}.{method}"));
214
+ withGen(|s| s.dispatchers.insert((obj.clone(), method.clone()), (idx, sig)));
215
+ }
216
+ for obj in eqs {
217
+ let with_eq: Vec<(PlumType, u32, u32)> = implementersOf(&obj, &reg, &traits)
218
+ .into_iter()
219
+ .filter_map(|c| {
220
+ let (f, _) = implementerMethod(&c, "eq", &self.func_ids, &self.func_sigs, &self.inst_funcs, &self.inst_index)?;
221
+ Some((c.clone(), tagIdx(&c, &reg)?, f))
222
+ })
223
+ .collect();
224
+ if with_eq.is_empty() {
225
+ continue;
226
+ }
227
+ // (a: anyref, b: anyref) -> i32: same type and that type's `eq`, else identity.
228
+ let mut b: Vec<u8> = vec![0u8];
229
+ for (_, tag, f) in &with_eq {
230
+ for l in 0..2 {
231
+ Instruction::LocalGet(l).encode(&mut b);
232
+ Instruction::RefTestNonNull(HeapType::Concrete(*tag)).encode(&mut b);
233
+ }
234
+ Instruction::I32And.encode(&mut b);
235
+ Instruction::If(BlockType::Empty).encode(&mut b);
236
+ for l in 0..2 {
237
+ Instruction::LocalGet(l).encode(&mut b);
238
+ Instruction::RefCastNonNull(HeapType::Concrete(*tag)).encode(&mut b);
239
+ }
240
+ Instruction::ReturnCall(*f).encode(&mut b);
241
+ Instruction::End.encode(&mut b);
242
+ }
243
+ for l in 0..2 {
244
+ Instruction::LocalGet(l).encode(&mut b);
245
+ Instruction::RefCastNullable(RefType::EQREF.heap_type).encode(&mut b);
246
+ }
247
+ Instruction::RefEq.encode(&mut b);
248
+ Instruction::End.encode(&mut b);
249
+ let any = ValType::Ref(RefType::ANYREF);
250
+ let t = self.module.addType(&[any, any], &[ValType::I32]);
251
+ let idx = self.module.addFunction(t, &b);
252
+ self.module.nameFunction(idx, &format!("eq.{obj}"));
253
+ withGen(|s| s.trait_eq.insert(obj.clone(), idx));
254
+ }
255
+ }
256
+ }
257
+
258
+ /// `sub` is a concrete reference type and `sup` is `anyref`: a result that fits by subtyping.
259
+ fn isRefTo(sup: ValType, sub: ValType) -> bool {
260
+ sup == ValType::Ref(RefType::ANYREF) && matches!(sub, ValType::Ref(_))
261
+ }
262
+
263
+ /// `left == right` (or `!=`) with a trait object on the left: the same type and equal values
264
+ /// by that type's `eq` method, else identity (a type's `==` without an `eq` method).
265
+ pub(crate) fn compileTraitEq(
266
+ c: &ast::CompareExpr,
267
+ left_ty: &PlumType,
268
+ body: &mut Vec<u8>,
269
+ ctx: &LocalCtx,
270
+ state: &mut ModuleState,
271
+ ) -> Result<(), String> {
272
+ match traitEqHelper(left_ty) {
273
+ Some(f) => {
274
+ compileExpr(&c.left, body, ctx, state)?;
275
+ compileExpr(&c.right, body, ctx, state)?;
276
+ Instruction::Call(f).encode(body);
277
+ }
278
+ None => {
279
+ compileExpr(&c.left, body, ctx, state)?;
280
+ Instruction::RefCastNullable(RefType::EQREF.heap_type).encode(body);
281
+ compileExpr(&c.right, body, ctx, state)?;
282
+ Instruction::RefCastNullable(RefType::EQREF.heap_type).encode(body);
283
+ Instruction::RefEq.encode(body);
284
+ }
285
+ }
286
+ if matches!(c.op, ast::CmpOp::Neq | ast::CmpOp::NotEq2) {
287
+ Instruction::I32Eqz.encode(body);
288
+ }
289
+ Ok(())
290
+ }
291
+
292
+ /// What a downcast pattern `ty as name` does against a subject of type `subject`.
293
+ pub(crate) enum AsTarget {
294
+ /// The subject is already of the type (a generic `T as x` where `T` is the subject's type).
295
+ Always(PlumType),
296
+ /// No value of the subject's type is ever of this type.
297
+ Never,
298
+ /// A `ref.test` against the type's tag.
299
+ Test(u32, PlumType),
300
+ }
301
+
302
+ /// The type a downcast pattern names: a declared type, or (in an instantiated body) the
303
+ /// type a generic parameter stands for.
304
+ pub(crate) fn asPatternType(ty: &str, subst: &Subst) -> PlumType {
305
+ subst.get(ty).cloned().unwrap_or_else(|| plum_checker::plumTypeFromName(ty))
306
+ }
307
+
308
+ pub(crate) fn asTarget(ty: &str, subject: &PlumType, subst: &Subst, reg: &GcTypeRegistry) -> AsTarget {
309
+ let target = asPatternType(ty, subst);
310
+ if canonTy(&target) == canonTy(subject) {
311
+ return AsTarget::Always(target);
312
+ }
313
+ if !isTraitObjectTy(subject) || isTraitObjectTy(&target) || isValueTy(&target) {
314
+ return AsTarget::Never;
315
+ }
316
+ match tagIdx(&target, reg) {
317
+ Some(idx) => AsTarget::Test(idx, target),
318
+ None => AsTarget::Never,
319
+ }
320
+ }
compiler/wasm-codegen/tests/wasm_codegen/fusion_alloc_test.rs CHANGED
@@ -654,3 +654,133 @@ fn self_spread_hazard_stays_a_copy() {
654
654
  let engine = engine(false);
655
655
  assert_eq!(runInt(&engine, &wasm).0, 605);
656
656
  }
657
+
658
+ // ---- through a trait object ----
659
+
660
+ fn compileFbip(source: &plum_core::ast::Source, fbip: bool) -> Vec<u8> {
661
+ let opts = plum_wasm_codegen::CompileOptions {
662
+ passes: plum_driver::PassOptions { fbip, explain: false, ..plum_driver::PassOptions::default() },
663
+ ..Default::default()
664
+ };
665
+ let bytes = plum_wasm_codegen::compile(source, &opts)
666
+ .map(|o| o.wasm)
667
+ .unwrap_or_else(|e| panic!("compile failed: {}", e.iter().map(|d| d.to_string()).collect::<Vec<_>>().join("\n")));
668
+ wasmparser::validate(&bytes).expect("valid wasm");
669
+ bytes
670
+ }
671
+
672
+ /// `struct.new`s in fn `name` and its compiler-made versions (`name$unique`).
673
+ fn newsIn(wasm: &[u8], name: &str) -> usize {
674
+ functions(wasm)
675
+ .iter()
676
+ .filter(|f| f.name == name || f.name.starts_with(&format!("{name}$")))
677
+ .map(|f| f.news.len())
678
+ .sum()
679
+ }
680
+
681
+ const ACTORS: &str = "trait Actor =
682
+ fun key(self) -> Int
683
+ fun step(self) -> Self = self
684
+
685
+ struct Ship(label: Str, x: Int, y: Int) is Actor =
686
+ fun key(self) -> Int = self.x + self.y
687
+ fun step(self) -> Ship = Ship(..self, x: self.x + 1)
688
+
689
+ struct Rock(label: Str, n: Int) is Actor =
690
+ fun key(self) -> Int = self.n
691
+
692
+ fun rock() -> Actor = Rock(label: \"r\", n: 3)
693
+
694
+ ";
695
+
696
+ /// `Ship(..self, ..)` in `Ship.step`, reached only through the trait's dispatcher, still writes
697
+ /// the ship in place when the trait object is unshared; with `--no-fbip` each step copies.
698
+ #[test]
699
+ fn self_spread_through_dispatch_is_in_place() {
700
+ let body = "fun spin(a: Actor, n: Int) -> Actor = if n == 0 then a else spin(a.step(), n - 1)
701
+
702
+ fun main() -> Int =
703
+ a := spin(Ship(label: \"a\", x: 0, y: 7), 1000)
704
+ a.key() + spin(rock(), 10).key()
705
+ ";
706
+ let src = load("trait_self_spread", &format!("{PRE}{ACTORS}{body}"));
707
+ let wasm = compileFbip(&src, true);
708
+ assert_eq!(newsIn(&wasm, "Ship.step"), 0, "the step writes the ship in place");
709
+ assert_eq!(runInt(&engine(false), &wasm).0, 1010);
710
+ let copying = compileFbip(&src, false);
711
+ assert_eq!(newsIn(&copying, "Ship.step"), 1, "--no-fbip: each step copies");
712
+ assert_eq!(runInt(&engine(false), &copying).0, 1010);
713
+ }
714
+
715
+ /// A downcast moves the unshared trait object into its binder: `Ship(..s, ..)` in the arm
716
+ /// reuses the ship; with `--no-fbip` it copies.
717
+ #[test]
718
+ fn spread_of_a_downcast_binder_is_in_place() {
719
+ let body = "fun still(a: Actor) -> Actor =
720
+ match a
721
+ Ship as s => Ship(..s, x: 0)
722
+ _ => a
723
+
724
+ fun main() -> Int =
725
+ a := still(Ship(label: \"b\", x: 4, y: 7))
726
+ a.key() + still(rock()).key()
727
+ ";
728
+ let src = load("trait_downcast_spread", &format!("{PRE}{ACTORS}{body}"));
729
+ let wasm = compileFbip(&src, true);
730
+ assert_eq!(newsIn(&wasm, "still"), 0, "the arm writes the ship in place");
731
+ assert_eq!(runInt(&engine(false), &wasm).0, 10);
732
+ let copying = compileFbip(&src, false);
733
+ assert!(newsIn(&copying, "still") >= 1, "--no-fbip: the arm copies");
734
+ assert_eq!(runInt(&engine(false), &copying).0, 10);
735
+ }
736
+
737
+ /// The downcast binder is not unique when the trait object is read again in the arm.
738
+ #[test]
739
+ fn downcast_binder_shares_a_live_subject() {
740
+ let body = "fun still(a: Actor) -> Int =
741
+ match a
742
+ Ship as s =>
743
+ t := Ship(..s, x: 0)
744
+ t.key() * 100 + a.key()
745
+ _ => a.key()
746
+
747
+ fun main() -> Int =
748
+ _ := rock()
749
+ still(Ship(label: \"b\", x: 4, y: 7))
750
+ ";
751
+ let src = load("trait_downcast_live", &format!("{PRE}{ACTORS}{body}"));
752
+ let wasm = compileFbip(&src, true);
753
+ assert!(newsIn(&wasm, "still") >= 1, "the subject is read after the spread: a copy");
754
+ assert_eq!(runInt(&engine(false), &wasm).0, 711);
755
+ }
756
+
757
+ /// The scene walk's shape: each node's actor is stepped through the trait and the node rebuilt.
758
+ /// The actors are written in place (no allocation per node per tick); `--no-fbip` copies them.
759
+ #[test]
760
+ fn stepping_a_tree_of_trait_objects_is_in_place() {
761
+ let body = "enum Line =
762
+ | Node(a: Actor, rest: Line)
763
+ | End
764
+
765
+ fun stepAll(xs: Line) -> Line = match xs
766
+ Node(a, rest) => Node(a: a.step(), rest: stepAll(rest))
767
+ End => End
768
+
769
+ fun build(n: Int) -> Line = if n == 0 then End else Node(a: Ship(label: \"s\", x: n, y: 0), rest: build(n - 1))
770
+
771
+ fun run(xs: Line, k: Int) -> Line = if k == 0 then xs else run(stepAll(xs), k - 1)
772
+
773
+ fun total(xs: Line) -> Int = match xs
774
+ Node(a, rest) => a.key() + total(rest)
775
+ End => 0
776
+
777
+ fun main() -> Int = total(run(Node(a: rock(), rest: build(10)), 100))
778
+ ";
779
+ let src = load("trait_tree_step", &format!("{PRE}{ACTORS}{body}"));
780
+ let wasm = compileFbip(&src, true);
781
+ assert_eq!(newsIn(&wasm, "Ship.step"), 0);
782
+ assert_eq!(runInt(&engine(false), &wasm).0, 1058);
783
+ let copying = compileFbip(&src, false);
784
+ assert_eq!(newsIn(&copying, "Ship.step"), 1);
785
+ assert_eq!(runInt(&engine(false), &copying).0, 1058);
786
+ }
tests/traits/dispatch.plum ADDED
@@ -0,0 +1,53 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Str
4
+ import std/List
5
+
6
+ trait Actor =
7
+ fun key(self) -> Int
8
+ fun step(self, dt: Float) -> Self = self
9
+ fun hit(self, p: Int) -> Bool = self.key() == p
10
+ fun name(self) -> Str = "actor"
11
+
12
+ struct Orb(id: Int, vx: Float) is Actor =
13
+ fun key(self) -> Int = self.id
14
+ fun step(self, dt: Float) -> Orb = Orb(..self, vx: self.vx + dt)
15
+ fun name(self) -> Str = "orb"
16
+
17
+ struct Label(id: Int, text: Str) is Actor =
18
+ fun key(self) -> Int = self.id
19
+
20
+ fun keyOf(a: Actor) -> Int = a.key()
21
+
22
+ fun stepAll(xs: List[Actor], dt: Float) -> List[Actor] = xs.map(|a| a.step(dt))
23
+
24
+ fun speed(a: Actor) -> Float =
25
+ match a
26
+ Orb as o => o.vx
27
+ _ => -1.0
28
+
29
+ test "a call on a trait object goes to the value's own method"
30
+ o := Orb(id: 1, vx: 2.0)
31
+ l := Label(id: 2, text: "hi")
32
+ assert keyOf(o) == 1
33
+ assert keyOf(l) == 2
34
+
35
+ test "a default runs when the type doesn't override it"
36
+ a: Actor := Label(id: 2, text: "hi")
37
+ b: Actor := Orb(id: 3, vx: 0.0)
38
+ assert a.name() == "actor"
39
+ assert b.name() == "orb"
40
+ assert a.hit(2)
41
+ assert !b.hit(2)
42
+
43
+ test "a Self-returning method on a trait object returns a trait object"
44
+ xs: List[Actor] := [Orb(id: 1, vx: 1.0), Label(id: 2, text: "a")]
45
+ ys := stepAll(xs, 0.5)
46
+ assert speed(ys.get(0).unwrap()) == 1.5
47
+ assert speed(ys.get(1).unwrap()) == -1.0
48
+
49
+ test "a Self-returning method on a concrete type returns that type"
50
+ o := Orb(id: 1, vx: 1.0).step(1.0)
51
+ assert o.vx == 2.0
52
+ l := Label(id: 2, text: "t").step(1.0)
53
+ assert l.text == "t"
tests/traits/kinds.plum ADDED
@@ -0,0 +1,257 @@
1
+ import std/Int
2
+ import std/Float
3
+ import std/Str
4
+ import std/List
5
+ import std/Option
6
+
7
+ # Trait objects: enums as implementers, downcasts (also through a generic), bounds,
8
+ # generic implementers, a trait returning its own trait object, and `==`.
9
+
10
+ trait Shape =
11
+ fun area(self) -> Float
12
+ fun big(self) -> Bool = self.area() > 10.0
13
+
14
+ enum Fig is Shape =
15
+ | Circle(r: Float)
16
+ | Square(s: Float)
17
+ | Dot
18
+
19
+ fun area(self) -> Float = match self
20
+ Circle(r) => 3.0 * r * r
21
+ Square(s) => s * s
22
+ Dot => 0.0
23
+
24
+ struct Rect(w: Float, h: Float) is Shape =
25
+ fun area(self) -> Float = self.w * self.h
26
+
27
+ fun total(xs: List[Shape]) -> Float = xs.fold(0.0, |acc, x| acc + x.area())
28
+
29
+ trait Actor =
30
+ fun key(self) -> Int
31
+ fun step(self, dt: Float) -> Self = self
32
+
33
+ struct Orb(id: Int, vx: Float) is Actor =
34
+ fun key(self) -> Int = self.id
35
+ fun step(self, dt: Float) -> Orb = Orb(..self, vx: self.vx + dt)
36
+
37
+ struct Label(id: Int, text: Str) is Actor =
38
+ fun key(self) -> Int = self.id
39
+
40
+ fun still(a: Actor) -> Actor =
41
+ match a
42
+ Orb as o => Orb(..o, vx: 0.0)
43
+ _ => a
44
+
45
+ fun speed(a: Actor) -> Float =
46
+ match a
47
+ Orb as o => o.vx
48
+ Label as l => -1.0
49
+ _ => -2.0
50
+
51
+ fun textOf(a: Actor) -> Str =
52
+ match a
53
+ Label as l => l.text
54
+ _ => ""
55
+
56
+ # A downcast through a generic parameter, as `findAs[T]` does.
57
+ fun findAs[T](xs: List[Actor], id: Int) -> Option[T] = match xs
58
+ Cons(a, rest) =>
59
+ if a.key() == id
60
+ match a
61
+ T as t => Some(t)
62
+ _ => None
63
+ else
64
+ findAs(rest, id)
65
+ Nil => None
66
+
67
+ fun updateAs[T](xs: List[Actor], f: fn(T) -> T) -> List[Actor] = xs.map(|a| match a
68
+ T as t =>
69
+ b: Actor := f(t)
70
+ b
71
+ _ => a)
72
+
73
+ fun firstOrbSpeed(o: Option[Actor]) -> Float = match o
74
+ Some(Orb as b) => b.vx
75
+ Some(_) => -1.0
76
+ None => -2.0
77
+
78
+ fun asItself[T](a: Actor, proto: Option[T]) -> Int =
79
+ match a
80
+ T as t => 1
81
+ _ => 0
82
+
83
+ fun stepT[T: Actor](x: T, dt: Float) -> T = x.step(dt)
84
+
85
+ fun keyT[T: Actor](x: T) -> Int = x.key() * 10
86
+
87
+ struct Pt(x: Int, y: Int) is Named =
88
+ fun name(self) -> Str = "pt"
89
+ fun eq(self, other: Pt) -> Bool = self.x == other.x && self.y == other.y
90
+
91
+ struct Tag(t: Str) is Named =
92
+ fun name(self) -> Str = self.t
93
+
94
+ trait Named =
95
+ fun name(self) -> Str
96
+
97
+ trait Reducer[M] =
98
+ fun update(self, msg: M) -> Self
99
+ fun count(self, msg: M) -> Int = 1
100
+
101
+ struct RunState(score: Int) is Reducer[Int] =
102
+ fun update(self, msg: Int) -> RunState = RunState(score: self.score + msg)
103
+
104
+ struct Words(n: Int) is Reducer[Str] =
105
+ fun update(self, msg: Str) -> Words = Words(n: self.n + msg.length())
106
+ fun count(self, msg: Str) -> Int = self.n
107
+
108
+ fun replay[M](r: Reducer[M], msgs: List[M]) -> Reducer[M] = msgs.fold(r, |a, m| a.update(m))
109
+
110
+ fun replayB[S: Reducer[M], M](s: S, msgs: List[M]) -> S = msgs.fold(s, |a, m| a.update(m))
111
+
112
+ struct Store[S: Reducer[M], M](state: S, n: Int) =
113
+ fun dispatch(self, msg: M) -> Store[S, M] = Store(state: self.state.update(msg), n: self.n + 1)
114
+
115
+ enum Msg = Collected(id: Int) | Hurt | StartPressed
116
+
117
+ trait Thing[M] =
118
+ fun key(self) -> Int
119
+ fun input(self, e: Int) -> Option[M] = None
120
+ fun step(self, dt: Float) -> Self = self
121
+
122
+ struct Box[M](id: Int, w: Float) is Thing[M] =
123
+ fun key(self) -> Int = self.id
124
+ fun step(self, dt: Float) -> Box[M] = Box(..self, w: self.w + dt)
125
+
126
+ struct Button[M](id: Int, onClick: M) is Thing[M] =
127
+ fun key(self) -> Int = self.id
128
+ fun input(self, e: Int) -> Option[M] = if e == self.id then Some(self.onClick) else None
129
+
130
+ struct Gem(id: Int) is Thing[Msg] =
131
+ fun key(self) -> Int = self.id
132
+ fun input(self, e: Int) -> Option[Msg] = if e == self.id then Some(Collected(id: self.id)) else None
133
+
134
+ fun clicks(xs: List[Thing[Msg]], e: Int) -> List[Msg] = xs.fold([], |acc, a| match a.input(e)
135
+ Some(m) => Cons(m, acc)
136
+ None => acc)
137
+
138
+ struct World(score: Int)
139
+
140
+ trait Screen[S, M] =
141
+ fun name(self) -> Str
142
+ fun react(self, state: S, msg: M) -> Self = self
143
+ fun next(self, state: S, msg: M) -> Option[Screen[S, M]] = None
144
+
145
+ struct Title(n: Int) is Screen[World, Msg] =
146
+ fun name(self) -> Str = "title"
147
+ fun next(self, state: World, msg: Msg) -> Option[Screen[World, Msg]] = match msg
148
+ StartPressed => Some(Play(lives: 3))
149
+ _ => None
150
+
151
+ struct Play(lives: Int) is Screen[World, Msg] =
152
+ fun name(self) -> Str = "play {self.lives}"
153
+ fun react(self, state: World, msg: Msg) -> Play = match msg
154
+ Hurt => Play(lives: self.lives - 1)
155
+ _ => self
156
+
157
+ fun advance(s: Screen[World, Msg], st: World, m: Msg) -> Screen[World, Msg] =
158
+ r := s.react(st, m)
159
+ match r.next(st, m)
160
+ Some(n) => n
161
+ None => r
162
+
163
+ test "an enum implements a trait"
164
+ xs: List[Shape] := [Circle(r: 1.0), Square(s: 2.0), Dot, Rect(w: 2.0, h: 3.0)]
165
+ assert total(xs) == 13.0
166
+ assert Circle(r: 3.0).big()
167
+ sq: Shape := Square(s: 1.0)
168
+ assert !sq.big()
169
+
170
+ test "a downcast binds the value with its own type"
171
+ assert speed(Orb(id: 1, vx: 2.5)) == 2.5
172
+ assert speed(Label(id: 2, text: "x")) == -1.0
173
+ assert speed(still(Orb(id: 1, vx: 2.5))) == 0.0
174
+ assert textOf(still(Label(id: 2, text: "keep"))) == "keep"
175
+
176
+ test "a downcast through a generic parameter"
177
+ xs: List[Actor] := [Orb(id: 1, vx: 2.0), Label(id: 2, text: "two")]
178
+ o: Option[Orb] := findAs(xs, 1)
179
+ assert o.unwrap().vx == 2.0
180
+ l: Option[Label] := findAs(xs, 2)
181
+ assert l.unwrap().text == "two"
182
+ no: Option[Label] := findAs(xs, 1)
183
+ assert no.isNone()
184
+ ys := updateAs(xs, |o: Orb| Orb(..o, vx: o.vx * 10.0))
185
+ assert speed(ys.get(0).unwrap()) == 20.0
186
+ assert textOf(ys.get(1).unwrap()) == "two"
187
+
188
+ test "a bounded generic calls the type's own methods"
189
+ o := stepT(Orb(id: 1, vx: 1.0), 2.0)
190
+ assert o.vx == 3.0
191
+ l := stepT(Label(id: 4, text: "x"), 2.0)
192
+ assert l.text == "x"
193
+ assert keyT(l) == 40
194
+ a: Actor := o
195
+ assert keyT(a) == 10
196
+
197
+ test "== on trait objects: the same value, or false"
198
+ o := Orb(id: 1, vx: 1.0)
199
+ a: Actor := o
200
+ b: Actor := o
201
+ c: Actor := Orb(id: 1, vx: 1.0)
202
+ l: Actor := Label(id: 1, text: "x")
203
+ assert a == b
204
+ assert a == o
205
+ assert a != l
206
+ assert a != c
207
+
208
+ test "== on trait objects uses the type's eq"
209
+ a: Named := Pt(x: 1, y: 2)
210
+ b: Named := Pt(x: 1, y: 2)
211
+ c: Named := Pt(x: 1, y: 3)
212
+ t: Named := Tag(t: "pt")
213
+ assert a == b
214
+ assert a != c
215
+ assert a != t
216
+ assert t == t
217
+
218
+ test "a trait with type parameters, as an object and as a bound"
219
+ r: Reducer[Int] := RunState(score: 0)
220
+ r2 := replay(r, [1, 2, 3])
221
+ assert r2.count(0) == 1
222
+ w: Reducer[Str] := Words(n: 0)
223
+ assert replay(w, ["ab", "c"]).count("") == 3
224
+ s := replayB(RunState(score: 1), [4, 5])
225
+ assert s.score == 10
226
+ st := Store(state: RunState(score: 0), n: 0).dispatch(4).dispatch(5)
227
+ assert st.state.score == 9 && st.n == 2
228
+
229
+ test "generic implementers in a list of a generic trait object"
230
+ b: Box[Msg] := Box(id: 1, w: 2.0)
231
+ bt: Button[Msg] := Button(id: 2, onClick: StartPressed)
232
+ xs: List[Thing[Msg]] := [b, bt, Gem(id: 3)]
233
+ assert clicks(xs, 2).length() == 1
234
+ assert clicks(xs, 3).length() == 1
235
+ assert clicks(xs, 1).length() == 0
236
+ assert xs.fold(0, |n, a| n + a.key()) == 6
237
+ ints: List[Thing[Int]] := [Box(id: 5, w: 1.0), Button(id: 6, onClick: 60)]
238
+ assert ints.fold(0, |n, a| n + a.input(6).unwrapOr(0)) == 60
239
+
240
+ test "a trait returning an option of its own trait object"
241
+ s: Screen[World, Msg] := Title(n: 0)
242
+ w := World(score: 0)
243
+ assert advance(s, w, Hurt).name() == "title"
244
+ p := advance(s, w, StartPressed)
245
+ assert p.name() == "play 3"
246
+ assert advance(p, w, Hurt).name() == "play 2"
247
+
248
+ test "a downcast inside a constructor pattern"
249
+ assert firstOrbSpeed(Some(Orb(id: 1, vx: 4.0))) == 4.0
250
+ assert firstOrbSpeed(Some(Label(id: 1, text: "l"))) == -1.0
251
+ assert firstOrbSpeed(None) == -2.0
252
+
253
+ test "a generic downcast matches only its own type"
254
+ no: Option[Orb] := None
255
+ nl: Option[Label] := None
256
+ assert asItself(Label(id: 1, text: "l"), no) == 0
257
+ assert asItself(Label(id: 1, text: "l"), nl) == 1