plum

#treesitter#compiler#wasm

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

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


133dab1 — Peter John 2026-11-09T13:08:53+05:30
Traits: parser and checker (actor-trait tasks 1 and 2)
Files changed (53) hide show
  1. compiler/checker/src/callcheck.rs +38 -1
  2. compiler/checker/src/callsites.rs +17 -0
  3. compiler/checker/src/declchecks.rs +40 -2
  4. compiler/checker/src/fncheck.rs +5 -3
  5. compiler/checker/src/infer.rs +6 -0
  6. compiler/checker/src/lib.rs +5 -0
  7. compiler/checker/src/matchcheck.rs +13 -0
  8. compiler/checker/src/patterns.rs +58 -0
  9. compiler/checker/src/program.rs +6 -0
  10. compiler/checker/src/state.rs +9 -0
  11. compiler/checker/src/stmt.rs +3 -0
  12. compiler/checker/src/tables.rs +14 -2
  13. compiler/checker/src/traits.rs +656 -0
  14. compiler/checker/src/unification.rs +28 -3
  15. compiler/checker/tests/checker/main.rs +1 -0
  16. compiler/checker/tests/checker/traits_tests.rs +560 -0
  17. compiler/core/src/ast.rs +99 -2
  18. compiler/core/src/binders.rs +1 -0
  19. compiler/core/src/blocks.rs +2 -0
  20. compiler/core/src/builtin_usage.rs +6 -0
  21. compiler/core/src/ctors.rs +2 -0
  22. compiler/core/src/drive.rs +1 -0
  23. compiler/core/src/enum_checks.rs +6 -0
  24. compiler/core/src/forms.rs +4 -2
  25. compiler/core/src/generics.rs +8 -2
  26. compiler/core/src/loader.rs +1 -0
  27. compiler/core/src/modules.rs +1 -1
  28. compiler/core/src/parser.rs +76 -8
  29. compiler/core/src/question.rs +1 -0
  30. compiler/core/src/rename.rs +1 -1
  31. compiler/core/src/spread_paths.rs +1 -1
  32. compiler/core/src/tail.rs +1 -1
  33. compiler/core/src/tests_lower.rs +2 -0
  34. compiler/core/src/uniqueness.rs +1 -0
  35. compiler/core/src/visit.rs +1 -0
  36. compiler/core/tests/core/main.rs +1 -0
  37. compiler/core/tests/core/parser_test.rs +3 -2
  38. compiler/core/tests/core/traits_parse_test.rs +165 -0
  39. compiler/driver/src/lib.rs +4 -1
  40. compiler/lsp/src/completion.rs +12 -0
  41. compiler/lsp/src/main.rs +1 -1
  42. compiler/tooling/tree-sitter-plum/grammar.js +28 -3
  43. compiler/tooling/tree-sitter-plum/queries/plum/format.scm +33 -0
  44. compiler/tooling/tree-sitter-plum/queries/plum/highlights.scm +3 -0
  45. compiler/tooling/tree-sitter-plum/queries/plum/indents.scm +2 -0
  46. compiler/tooling/tree-sitter-plum/src/grammar.json +0 -0
  47. compiler/tooling/tree-sitter-plum/src/node-types.json +0 -0
  48. compiler/tooling/tree-sitter-plum/src/parser.c +0 -0
  49. compiler/tooling/tree-sitter-plum/test/corpus/traits.txt +191 -0
  50. compiler/tooling/vscode-plum/syntaxes/plum.tmLanguage.json +1 -1
  51. compiler/wasm-codegen/src/emit.rs +1 -0
  52. compiler/wasm-codegen/src/lib.rs +20 -0
  53. compiler/wasm-codegen/src/matching.rs +4 -0
compiler/checker/src/callcheck.rs CHANGED
@@ -169,6 +169,9 @@ pub(crate) fn inferClassCallRaw(
169
169
  }
170
170
  }
171
171
  let built = substVars(&result, &binds);
172
+ if let Some(msg) = unmetTypeBound(&resolveRecorded(&built), ctx) {
173
+ return Err(format!("{}(..): {}", call.type_name, msg));
174
+ }
172
175
  checkVariantPinned(info, &call.type_name, built, expected)
173
176
  }
174
177
  // Positional/generic-payload variant (`Next(T)`, constructed via `Expr::FnCall`
@@ -282,7 +285,35 @@ pub(crate) fn inferMethodCall(
282
285
  }
283
286
  // A method on a generic parameter: duck-typed — checked when the enclosing generic body is
284
287
  // checked per concrete instantiation.
285
- if let PlumType::TParam(_) = obj_ty {
288
+ if let PlumType::TParam(p) = obj_ty {
289
+ // A parameter bounded by traits (`[T: Show]`) has the bounds' methods, `Self` being
290
+ // `T`; one with no bounds is duck-typed, checked per instantiation.
291
+ match boundMethodSig(p, name) {
292
+ Some(Ok(sig)) => {
293
+ let mut names = Vec::new();
294
+ freeTParams(&sig, &mut names);
295
+ let owner: BTreeMap<String, PlumType> = names
296
+ .into_iter()
297
+ .filter(|n| withCheck(|s| s.scope.borrow().isGeneric(n)))
298
+ .map(|n| (n.clone(), PlumType::TParam(n)))
299
+ .collect();
300
+ let PlumType::TFun(params, ret) = instSig(&sig, &owner) else {
301
+ unreachable!("a trait method's signature is a TFun")
302
+ };
303
+ let mut binds = Binds::new();
304
+ if let Some(exp) = expected {
305
+ bindMatch(&ret, exp, &mut binds);
306
+ }
307
+ let label = format!("method '{}.{}'", p, name);
308
+ checkCallArgs(&label, &params, args, params.len(), env, ctx, &mut binds)?;
309
+ return Ok(substVars(&ret, &binds));
310
+ }
311
+ Some(Err(msg)) => {
312
+ markResolution();
313
+ return Err(msg);
314
+ }
315
+ None => {}
316
+ }
286
317
  // The generic body is only structurally checked here: the call's
287
318
  // result is a wildcard, and the real check happens per instantiation.
288
319
  return Ok(PlumType::TVar("_".to_string()));
@@ -299,6 +330,12 @@ pub(crate) fn inferMethodCall(
299
330
  return Ok(PlumType::TVar("_".to_string()));
300
331
  };
301
332
  let Some(sig) = ctx.methods.get(&(class_name.to_string(), name.to_string())) else {
333
+ if isTraitObject(obj_ty) {
334
+ return Err(format!(
335
+ "{} has no method '{}': a trait object has only the methods of trait {}",
336
+ obj_ty, name, class_name
337
+ ));
338
+ }
302
339
  // `rec.add(a, b)` where `add` is an fn-typed FIELD (a "record of
303
340
  // functions"): calls the stored closure. A method of the same name wins
304
341
  // (it is found just above), so this is only reached when there is none.
compiler/checker/src/callsites.rs CHANGED
@@ -177,6 +177,23 @@ pub(crate) fn registerCalls(
177
177
  None => cs.name.clone(),
178
178
  };
179
179
  let key = (item.clone(), args.clone());
180
+ if !st.info.inst_index.contains_key(&key) {
181
+ let bounds: Vec<(String, Vec<PlumType>)> = {
182
+ let traits = currentTraits();
183
+ let mut b: Vec<(String, Vec<PlumType>)> = Vec::new();
184
+ if let Some(r) = &f.type_param {
185
+ b.extend(traits.typeBounds.get(r).into_iter().flatten().cloned());
186
+ }
187
+ b.extend(traits.fnBounds.get(&(f.type_param.clone(), f.name.clone())).into_iter().flatten().cloned());
188
+ b
189
+ };
190
+ if !bounds.is_empty() {
191
+ if let Some(msg) = unmetBound(&plum_core::diag::sourceName(&item), &gens, &args, &bounds) {
192
+ let e = CheckError::at(cs.line, cs.column, format!("{}call '{}': {}", parent_chain, plum_core::diag::sourceName(&cs.name), msg));
193
+ withCheck(|s| s.bound_errors.borrow_mut().push(e));
194
+ }
195
+ }
196
+ }
180
197
  if let Some(&existing) = st.info.inst_index.get(&key) {
181
198
  st.info
182
199
  .call_inst
compiler/checker/src/declchecks.rs CHANGED
@@ -114,6 +114,11 @@ pub(crate) fn checkUnknownTypes(source: &ast::Source) -> Vec<CheckError> {
114
114
  }
115
115
  }
116
116
  known.extend(source.primitives.iter().map(|p| p.name.as_str()));
117
+ for item in &source.items {
118
+ if let ast::Item::Trait(t) = item {
119
+ known.insert(t.name.as_str());
120
+ }
121
+ }
117
122
  let owners = plum_core::generics::ownerGenerics(source);
118
123
  let mut errors = Vec::new();
119
124
  fn walk(
@@ -146,7 +151,7 @@ pub(crate) fn checkUnknownTypes(source: &ast::Source) -> Vec<CheckError> {
146
151
  if let Some(r) = &f.returns {
147
152
  walk(r, &sc, &known, &mut bad);
148
153
  }
149
- for n in bad {
154
+ for n in bad.into_iter().filter(|n| n != ast::SELF_TYPE) {
150
155
  errors.push(CheckError::at(
151
156
  f.line,
152
157
  f.column,
@@ -154,13 +159,46 @@ pub(crate) fn checkUnknownTypes(source: &ast::Source) -> Vec<CheckError> {
154
159
  ));
155
160
  }
156
161
  }
162
+ // A trait's method signatures: `Self` is the implementing type.
163
+ ast::Item::Trait(t) => {
164
+ for m in &t.methods {
165
+ let mut owner: Vec<String> = t.generics.iter().map(|g| g.name.clone()).collect();
166
+ owner.push(ast::SELF_TYPE.to_string());
167
+ let sc = Scope::of(&owner, &m.sig);
168
+ let mut bad = Vec::new();
169
+ for p in &m.sig.params {
170
+ match &p.ty {
171
+ ast::ParamType::Type(t) => walk(t, &sc, &known, &mut bad),
172
+ ast::ParamType::Fn(ps, r) => {
173
+ ps.iter().for_each(|t| walk(t, &sc, &known, &mut bad));
174
+ if let Some(r) = r {
175
+ walk(r, &sc, &known, &mut bad);
176
+ }
177
+ }
178
+ }
179
+ }
180
+ if let Some(r) = &m.sig.returns {
181
+ walk(r, &sc, &known, &mut bad);
182
+ }
183
+ for n in bad {
184
+ errors.push(CheckError::at(
185
+ m.sig.line,
186
+ m.sig.column,
187
+ format!("trait '{}': method '{}': unknown type {}", t.name, m.sig.name, n),
188
+ ));
189
+ }
190
+ }
191
+ }
157
192
  ast::Item::Enum(e) => {
158
193
  let sc = Scope::named(&enumGenericParams(e));
159
194
  let mut bad = Vec::new();
160
195
  for v in &e.variants {
161
196
  v.fields.iter().for_each(|t| walk(t, &sc, &known, &mut bad));
162
197
  }
163
- for n in bad {
198
+ for t in &e.implements {
199
+ walk(t, &sc, &known, &mut bad);
200
+ }
201
+ for n in bad.into_iter().filter(|n| n != ast::SELF_TYPE) {
164
202
  errors.push(CheckError::at(e.line, e.column, format!("{}: unknown type {}", e.name, n)));
165
203
  }
166
204
  }
compiler/checker/src/fncheck.rs CHANGED
@@ -28,9 +28,11 @@ pub(crate) fn checkFn(f: &ast::Fn, global_env: &TypeEnv, ctx: &CheckCtx) -> Vec<
28
28
  None => Vec::new(),
29
29
  };
30
30
  withFnScope(f, &owner, || {
31
+ withBounds(f, || {
31
- let mut errors = checkParamDefaults(f, global_env, ctx);
32
+ let mut errors = checkParamDefaults(f, global_env, ctx);
32
- errors.append(&mut checkFnBody(f, global_env, ctx));
33
+ errors.append(&mut checkFnBody(f, global_env, ctx));
33
- errors
34
+ errors
35
+ })
34
36
  })
35
37
  }
36
38
 
compiler/checker/src/infer.rs CHANGED
@@ -424,6 +424,9 @@ pub(crate) fn inferExprInner(
424
424
  let tenv = bindCondEnv(&t.condition, env, ctx)?;
425
425
  let tt = inferExprWith(&t.then, &tenv, ctx, expected)?;
426
426
  let et = inferExprWith(&t.else_, env, ctx, expected)?;
427
+ if let Some(j) = joinTrait(expected, &[tt.clone(), et.clone()], ctx) {
428
+ return Ok(j);
429
+ }
427
430
  unify(&tt, &et, ctx).map_err(|e| format!("inline if branches: {}", e))?;
428
431
  // Each branch pins what the other leaves open (`if c then Ok(4) else
429
432
  // Err(5)`: `Result[Int, _t1]` / `Result[_t2, Int]`); binding them both
@@ -592,6 +595,9 @@ pub(crate) fn inferExprInner(
592
595
  ast::Expr { kind: ast::ExprKind::Attribute(attr), .. } => {
593
596
  let obj_ty = resolveRecorded(&inferExpr(&attr.object, env, ctx)?);
594
597
  match &attr.attr {
598
+ ast::AttrKind::Field(field_name) if isTraitObject(&obj_ty) => Err(format!(
599
+ "no field '{field_name}' on {obj_ty}: a trait object has only its trait's methods; match `Type as x` to read a type's fields"
600
+ )),
595
601
  ast::AttrKind::Field(field_name) => match &obj_ty {
596
602
  // `Str` is an ordinary class with a real field; a generic
597
603
  // class substitutes its receiver's type arguments.
compiler/checker/src/lib.rs CHANGED
@@ -20,6 +20,7 @@ mod program;
20
20
  mod recording;
21
21
  mod stmt;
22
22
  mod tables;
23
+ pub mod traits;
23
24
  mod typeconv;
24
25
  mod unification;
25
26
  pub mod types;
@@ -46,6 +47,7 @@ pub use program::*;
46
47
  pub(crate) use recording::*;
47
48
  pub(crate) use stmt::*;
48
49
  pub use tables::*;
50
+ pub use traits::*;
49
51
  pub use typeconv::*;
50
52
  pub use unification::*;
51
53
 
@@ -82,6 +84,9 @@ pub struct TypedInfo {
82
84
  /// The program with its `for` loops lowered (see `plum_core::forms`): the
83
85
  /// source the types above belong to, and the one codegen must compile.
84
86
  pub lowered: Option<std::rc::Rc<ast::Source>>,
87
+ /// The program's traits: what implements each `(trait, arguments)` (see
88
+ /// `Traits::implementerSets`), the trait methods' signatures and the bounds of generics.
89
+ pub traits: std::rc::Rc<traits::Traits>,
85
90
  }
86
91
 
87
92
  /// One reached instantiation of a generic fn or method of a generic type.
compiler/checker/src/matchcheck.rs CHANGED
@@ -215,6 +215,19 @@ pub(crate) fn checkMatch(
215
215
  }
216
216
 
217
217
  if let [subject_ty] = subject_types.as_slice() {
218
+ let subject = resolveRecorded(subject_ty);
219
+ if isTraitObject(&subject)
220
+ && !m.cases.iter().any(|c| c.guard.is_none() && c.patterns.len() == 1 && patCatchAll(&c.patterns[0]))
221
+ {
222
+ errors.push(CheckError::at(
223
+ fn_pos.0,
224
+ fn_pos.1,
225
+ format!(
226
+ "fn '{}': non-exhaustive match on {}: add a `_ =>` arm (a {} can be any type that implements it)",
227
+ fn_name, subject, subject
228
+ ),
229
+ ));
230
+ }
218
231
  let rows: Vec<Vec<&ast::CasePattern>> = m
219
232
  .cases
220
233
  .iter()
compiler/checker/src/patterns.rs CHANGED
@@ -54,6 +54,20 @@ pub(crate) fn checkPattern(
54
54
  }
55
55
  }
56
56
  }
57
+ if let ast::CasePattern::Class { name, .. } = pat {
58
+ let subject = resolveRecorded(subject_ty);
59
+ if isTraitObject(&subject) {
60
+ return Err(format!(
61
+ "a {subject} is matched by type: `{name} as x` (a downcast) or `_`, not `{name}(..)`"
62
+ ));
63
+ }
64
+ }
65
+ if let ast::CasePattern::Name(n) = pat {
66
+ let subject = resolveRecorded(subject_ty);
67
+ if isTraitObject(&subject) && n.chars().next().is_some_and(|c| c.is_uppercase()) {
68
+ return Err(format!("a {subject} is matched by type: `{n} as x` (a downcast) or `_`"));
69
+ }
70
+ }
57
71
  match pat {
58
72
  ast::CasePattern::Wildcard => Ok(()),
59
73
  ast::CasePattern::Int(_) => unify(subject_ty, &PlumType::TInt, ctx),
@@ -76,6 +90,22 @@ pub(crate) fn checkPattern(
76
90
  Ok(())
77
91
  }
78
92
  }
93
+ ast::CasePattern::As { ty, name } => {
94
+ let target = downcastTarget(ty, ctx)?;
95
+ let subject = resolveRecorded(subject_ty);
96
+ if isTraitObject(&subject) {
97
+ if isTraitObject(&target) {
98
+ return Err(format!("`{ty} as {name}`: {ty} is a trait; a downcast names a type"));
99
+ }
100
+ if !matches!(target, PlumType::TParam(_)) && !implementsTrait(&target, &subject) {
101
+ return Err(format!("`{ty} as {name}`: {ty} does not implement {subject}, so a {subject} is never a {ty}"));
102
+ }
103
+ } else if !matches!(subject, PlumType::TVar(_) | PlumType::TParam(_)) && subject != target {
104
+ return Err(format!("`{ty} as {name}` needs a trait object to match on; found {subject}"));
105
+ }
106
+ env.insert(name.clone(), TypeScheme::mono(target));
107
+ Ok(())
108
+ }
79
109
  ast::CasePattern::Class { name, fields, .. } => match ctx.enum_variants.get(name) {
80
110
  // Also how a record-shaped, single-variant enum (the `type X = ...`
81
111
  // replacement) destructures — its one variant already IS the whole
@@ -110,3 +140,31 @@ pub(crate) fn checkPattern(
110
140
  },
111
141
  }
112
142
  }
143
+
144
+ /// The type a downcast pattern `ty as name` binds: a declared non-generic type, or a generic
145
+ /// parameter in scope (its type in an instantiated body).
146
+ fn downcastTarget(ty: &str, ctx: &CheckCtx) -> Result<PlumType, String> {
147
+ if withCheck(|s| s.scope.borrow().isGeneric(ty)) {
148
+ if let Some(t) = typeParamBinding(ty) {
149
+ return Ok(t);
150
+ }
151
+ return Ok(PlumType::TParam(ty.to_string()));
152
+ }
153
+ if isTraitObject(&PlumType::TNamed(ty.to_string())) {
154
+ return Ok(PlumType::TNamed(ty.to_string()));
155
+ }
156
+ let declared = ctx.enum_variants.values().find(|i| i.enum_name == ty);
157
+ match declared {
158
+ Some(info) if !info.generics.is_empty() => Err(format!(
159
+ "`{ty} as ..`: {ty} is generic; a downcast names a type with no type parameters"
160
+ )),
161
+ Some(_) => Ok(plumTypeFromName(ty)),
162
+ None if ctx.enum_variants.contains_key(ty) => Err(format!(
163
+ "`{ty} as ..`: {ty} is a variant; a downcast names a type"
164
+ )),
165
+ None => {
166
+ markResolution();
167
+ Err(format!("`{ty} as ..`: unknown type {ty}"))
168
+ }
169
+ }
170
+ }
compiler/checker/src/program.rs CHANGED
@@ -193,6 +193,10 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
193
193
  .map(|(l, c, m)| CheckError::at(*l, *c, m.clone())),
194
194
  );
195
195
  let (mut global_env, methods, enum_variants) = buildGlobalTables(source);
196
+ let traits = std::rc::Rc::new(buildTraits(source));
197
+ withCheck(|s| *s.traits.borrow_mut() = traits.clone());
198
+ errors.extend(checkTraitDecls(source, &traits, &methods));
199
+ errors.extend(selfOutsideTrait(source));
196
200
  // Shared fields of subtyped traits; codegen fills them in (see `addTraitParams`).
197
201
  let enum_params = EnumParams::new();
198
202
  let min_required = buildMinRequiredArgs(source);
@@ -380,6 +384,8 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
380
384
  registerCalls(&mut inst, &fn_by_key, &ctx, Some(id));
381
385
  }
382
386
 
387
+ errors.extend(withCheck(|s| std::mem::take(&mut *s.bound_errors.borrow_mut())));
388
+ inst.info.traits = traits;
383
389
  let result = if errors.is_empty() {
384
390
  Ok(())
385
391
  } else {
compiler/checker/src/state.rs CHANGED
@@ -71,6 +71,15 @@ pub(crate) struct CheckState {
71
71
  /// The names of the top-level functions and constants (the keys of the global env).
72
72
  pub(crate) globals: RefCell<std::collections::HashSet<String>>,
73
73
  pub(crate) scope_site: RefCell<Option<(String, usize, String)>>,
74
+ /// The traits of the program being checked (`traits::buildTraits`).
75
+ pub(crate) traits: RefCell<std::rc::Rc<crate::traits::Traits>>,
76
+ /// The bounds of the generics in scope of the body being checked (`[T: Show]`).
77
+ pub(crate) cur_bounds: RefCell<BTreeMap<String, Vec<PlumType>>>,
78
+ /// Instantiations whose type arguments don't meet a bound, found as they are registered.
79
+ pub(crate) bound_errors: RefCell<Vec<crate::types::CheckError>>,
80
+ /// Set while `unify` compares the parts of a type (`List[Actor]` against `List[Orb]`): a
81
+ /// trait object accepts an implementer only as a whole value, not inside another type.
82
+ pub(crate) no_coerce: Cell<bool>,
74
83
  }
75
84
 
76
85
  thread_local! {
compiler/checker/src/stmt.rs CHANGED
@@ -30,6 +30,9 @@ pub(crate) fn inferBlockValue(
30
30
  let msg = first.message.strip_prefix("fn '': ").unwrap_or(&first.message).to_string();
31
31
  return Err(msg);
32
32
  }
33
+ if let Some(j) = joinTrait(expected, &vals, ctx) {
34
+ return Ok(j);
35
+ }
33
36
  let mut vals = vals.into_iter();
34
37
  let Some(joined) = vals.next() else {
35
38
  return Ok(PlumType::TVar("_".to_string()));
compiler/checker/src/tables.rs CHANGED
@@ -48,13 +48,23 @@ pub type MinRequiredArgs = BTreeMap<(Option<String>, String), usize>;
48
48
  /// Primitives have no variants, so they don't live in `EnumVariants`.
49
49
  pub type PrimitiveGenerics = BTreeMap<String, Vec<String>>;
50
50
 
51
+ /// Generic traits are here too (`Reducer[M]`): like a primitive, a trait has generics and
52
+ /// methods but no variants.
51
53
  pub fn buildPrimitiveGenerics(source: &ast::Source) -> PrimitiveGenerics {
52
- source
54
+ let mut out: PrimitiveGenerics = source
53
55
  .primitives
54
56
  .iter()
55
57
  .filter(|p| !p.generics.is_empty())
56
58
  .map(|p| (p.name.clone(), p.generics.clone()))
57
- .collect()
59
+ .collect();
60
+ for item in &source.items {
61
+ if let ast::Item::Trait(t) = item {
62
+ if !t.generics.is_empty() {
63
+ out.insert(t.name.clone(), t.generics.iter().map(|g| g.name.clone()).collect());
64
+ }
65
+ }
66
+ }
67
+ out
58
68
  }
59
69
 
60
70
  /// `(type, name)` of every function declared in a type body without `self`: a
@@ -89,6 +99,7 @@ pub fn buildMinRequiredArgs(source: &ast::Source) -> MinRequiredArgs {
89
99
  result.insert((f.type_param.clone(), f.name.clone()), required);
90
100
  }
91
101
  }
102
+ addTraitMethods(&buildTraits(source), &mut MethodEnv::new(), Some(&mut result));
92
103
  result
93
104
  }
94
105
 
@@ -214,5 +225,6 @@ pub fn buildGlobalTables(source: &ast::Source) -> (TypeEnv, MethodEnv, EnumVaria
214
225
  }
215
226
  }
216
227
 
228
+ addTraitMethods(&buildTraits(source), &mut methods, None);
217
229
  (global_env, methods, enum_variants)
218
230
  }
compiler/checker/src/traits.rs ADDED
@@ -0,0 +1,656 @@
1
+ //! Traits: their declarations, `is` conformance, trait objects and generic bounds.
2
+ //!
3
+ //! A trait's name used as a type (`Actor`, `Reducer[Msg]`) is a trait object: a value of
4
+ //! any type that implements the trait. It is `TNamed`/`TApp` of the trait's name, and
5
+ //! `unify` accepts an implementer where one is expected (never the other way: the only
6
+ //! downcast is the `Type as name` pattern). The trait's methods are in the method table
7
+ //! under the trait's name, with `Self` as the trait object; a default a type doesn't
8
+ //! override is in it under the type's name too, with `Self` as that type.
9
+
10
+ use crate::*;
11
+
12
+ /// One method of a trait.
13
+ #[derive(Debug, Clone, PartialEq)]
14
+ pub struct TraitMethodInfo {
15
+ pub name: String,
16
+ /// Its type without `self` (`TFun`), with `Self` as `TParam(SELF_TYPE)` and the trait's
17
+ /// generics as `TParam`s.
18
+ pub sig: PlumType,
19
+ pub hasDefault: bool,
20
+ pub hasSelf: bool,
21
+ /// Arguments a call must give (the params before the first with a default).
22
+ pub minRequired: usize,
23
+ pub line: usize,
24
+ pub column: usize,
25
+ }
26
+
27
+ #[derive(Debug, Clone, PartialEq)]
28
+ pub struct TraitInfo {
29
+ pub name: String,
30
+ pub file: String,
31
+ pub line: usize,
32
+ pub column: usize,
33
+ pub generics: Vec<String>,
34
+ pub methods: Vec<TraitMethodInfo>,
35
+ }
36
+
37
+ impl TraitInfo {
38
+ pub fn method(&self, name: &str) -> Option<&TraitMethodInfo> {
39
+ self.methods.iter().find(|m| m.name == name)
40
+ }
41
+ }
42
+
43
+ /// One `is` entry of a type.
44
+ #[derive(Debug, Clone, PartialEq)]
45
+ pub struct ImplEntry {
46
+ /// The trait as written, the type's own generics as `TParam`s (`Reducer[Msg]`).
47
+ pub ty: PlumType,
48
+ pub trait_name: String,
49
+ pub args: Vec<PlumType>,
50
+ }
51
+
52
+ /// The program's traits, what implements them, and the bounds of generic parameters.
53
+ #[derive(Debug, Clone, Default, PartialEq)]
54
+ pub struct Traits {
55
+ pub traits: BTreeMap<String, TraitInfo>,
56
+ /// Type name -> (its own generics, its `is` entries in order).
57
+ pub impls: BTreeMap<String, (Vec<String>, Vec<ImplEntry>)>,
58
+ /// `(receiver, fn name)` -> the bounds of the fn's own generics.
59
+ pub fnBounds: BTreeMap<(Option<String>, String), Vec<(String, Vec<PlumType>)>>,
60
+ /// Type name -> the bounds of its own generics.
61
+ pub typeBounds: BTreeMap<String, Vec<(String, Vec<PlumType>)>>,
62
+ }
63
+
64
+ impl Traits {
65
+ pub fn isEmpty(&self) -> bool {
66
+ self.traits.is_empty()
67
+ }
68
+
69
+ pub fn isTrait(&self, name: &str) -> bool {
70
+ self.traits.contains_key(name)
71
+ }
72
+
73
+ /// The trait `ty` is an object of: `Actor` -> ("Actor", []), `Reducer[Msg]` -> ("Reducer", [Msg]).
74
+ pub fn traitObject<'a>(&self, ty: &'a PlumType) -> Option<(&'a str, &'a [PlumType])> {
75
+ match ty {
76
+ PlumType::TNamed(n) if self.isTrait(n) => Some((n.as_str(), &[])),
77
+ PlumType::TApp(n, args) if self.isTrait(n) => Some((n.as_str(), args.as_slice())),
78
+ _ => None,
79
+ }
80
+ }
81
+
82
+ /// The `is` entries of the type `ty` (`Orb`, `Queue[Int]`), with the type's
83
+ /// arguments substituted.
84
+ pub fn entriesOf(&self, ty: &PlumType) -> Vec<ImplEntry> {
85
+ let (name, args): (&str, &[PlumType]) = match ty {
86
+ PlumType::TNamed(n) => (n, &[]),
87
+ PlumType::TApp(n, a) => (n, a),
88
+ _ => return Vec::new(),
89
+ };
90
+ let Some((gens, entries)) = self.impls.get(name) else {
91
+ return Vec::new();
92
+ };
93
+ let s: BTreeMap<String, PlumType> = if args.len() == gens.len() {
94
+ appSubst(gens, args)
95
+ } else {
96
+ gens.iter().map(|g| (g.clone(), PlumType::TVar("_".to_string()))).collect()
97
+ };
98
+ entries
99
+ .iter()
100
+ .map(|e| ImplEntry {
101
+ ty: types::substitute(&e.ty, &s),
102
+ trait_name: e.trait_name.clone(),
103
+ args: e.args.iter().map(|a| types::substitute(a, &s)).collect(),
104
+ })
105
+ .collect()
106
+ }
107
+
108
+ /// Whether a value of type `ty` is accepted as the trait object `tr`: a type that
109
+ /// declares `is tr`, or a generic parameter bounded by it (`bounds`, in scope).
110
+ pub fn implements(&self, ty: &PlumType, tr: &PlumType, bounds: &BTreeMap<String, Vec<PlumType>>) -> bool {
111
+ let Some((name, args)) = self.traitObject(tr) else {
112
+ return false;
113
+ };
114
+ let fits = |e_name: &str, e_args: &[PlumType]| {
115
+ e_name == name && e_args.len() == args.len() && e_args.iter().zip(args).all(|(a, b)| sameType(a, b))
116
+ };
117
+ match ty {
118
+ PlumType::TParam(p) => bounds.get(p).is_some_and(|bs| {
119
+ bs.iter().any(|b| matches!(self.traitObject(b), Some((n, a)) if fits(n, a)))
120
+ }),
121
+ _ => self.entriesOf(ty).iter().any(|e| fits(&e.trait_name, &e.args)),
122
+ }
123
+ }
124
+
125
+ /// The signature of trait method `method` of the trait object `tr`, with `Self` as `self_ty`.
126
+ pub fn methodSig(&self, tr: &PlumType, method: &str, self_ty: &PlumType) -> Option<PlumType> {
127
+ let (name, args) = self.traitObject(tr)?;
128
+ let t = self.traits.get(name)?;
129
+ let m = t.method(method)?;
130
+ let mut s = appSubst(&t.generics, args);
131
+ s.insert(ast::SELF_TYPE.to_string(), self_ty.clone());
132
+ Some(types::substitute(&m.sig, &s))
133
+ }
134
+
135
+ /// The types implementing the trait `name` with arguments `args`, in declaration
136
+ /// order: the dispatch set of the trait object `name[args]`. A generic implementer
137
+ /// whose `is` entry mentions its own parameters is listed under its entry as written.
138
+ pub fn implementers(&self, name: &str, args: &[PlumType]) -> Vec<String> {
139
+ let mut out = Vec::new();
140
+ for (ty, (_, entries)) in &self.impls {
141
+ if entries.iter().any(|e| e.trait_name == name && e.args.len() == args.len() && e.args.iter().zip(args).all(|(a, b)| a == b)) {
142
+ out.push(ty.clone());
143
+ }
144
+ }
145
+ out
146
+ }
147
+
148
+ /// Every `(trait, arguments)` some type implements, with its implementers (one set per
149
+ /// trait and arguments), in the order of the type names.
150
+ pub fn implementerSets(&self) -> Vec<((String, Vec<PlumType>), Vec<String>)> {
151
+ let mut out: Vec<((String, Vec<PlumType>), Vec<String>)> = Vec::new();
152
+ for (ty, (_, entries)) in &self.impls {
153
+ for e in entries {
154
+ let key = (e.trait_name.clone(), e.args.clone());
155
+ match out.iter_mut().find(|(k, _)| *k == key) {
156
+ Some((_, v)) => {
157
+ if !v.contains(ty) {
158
+ v.push(ty.clone());
159
+ }
160
+ }
161
+ None => out.push((key, vec![ty.clone()])),
162
+ }
163
+ }
164
+ }
165
+ out
166
+ }
167
+ }
168
+
169
+ /// Equal types, an unresolved variable matching anything.
170
+ fn sameType(a: &PlumType, b: &PlumType) -> bool {
171
+ use PlumType::*;
172
+ match (a, b) {
173
+ (TVar(_), _) | (_, TVar(_)) => true,
174
+ (TApp(x, xs), TApp(y, ys)) => x == y && xs.len() == ys.len() && xs.iter().zip(ys).all(|(p, q)| sameType(p, q)),
175
+ (TFun(ps, r), TFun(qs, s)) => ps.len() == qs.len() && ps.iter().zip(qs).all(|(p, q)| sameType(p, q)) && sameType(r, s),
176
+ _ => a == b,
177
+ }
178
+ }
179
+
180
+ /// The `TFun` of `f` (without `self`) under the current generic scope.
181
+ fn fnSig(f: &ast::Fn) -> PlumType {
182
+ PlumType::TFun(
183
+ f.params.iter().map(|p| paramTypeG(&p.ty)).collect(),
184
+ Box::new(f.returns.as_ref().map(plumTypeFromAstG).unwrap_or(PlumType::TUnit)),
185
+ )
186
+ }
187
+
188
+ fn minRequired(f: &ast::Fn) -> usize {
189
+ f.params
190
+ .iter()
191
+ .take_while(|p| !(matches!(p.ty, ast::ParamType::Type(_)) && p.default.is_some()))
192
+ .count()
193
+ }
194
+
195
+ fn convBounds(params: &[ast::GenericParam]) -> Vec<(String, Vec<PlumType>)> {
196
+ params
197
+ .iter()
198
+ .filter(|g| !g.bounds.is_empty())
199
+ .map(|g| (g.name.clone(), g.bounds.iter().map(plumTypeFromAstG).collect()))
200
+ .collect()
201
+ }
202
+
203
+ /// The traits of `source`, the `is` entries of its types and the bounds of its generics.
204
+ pub fn buildTraits(source: &ast::Source) -> Traits {
205
+ let mut out = Traits::default();
206
+ let owners = plum_core::generics::ownerGenerics(source);
207
+ for item in &source.items {
208
+ match item {
209
+ ast::Item::Trait(t) => {
210
+ let generics: Vec<String> = t.generics.iter().map(|g| g.name.clone()).collect();
211
+ let mut scopeNames = generics.clone();
212
+ scopeNames.push(ast::SELF_TYPE.to_string());
213
+ let methods = t
214
+ .methods
215
+ .iter()
216
+ .map(|m| {
217
+ let saved = setScope(Scope::of(&scopeNames, &m.sig), None);
218
+ let sig = fnSig(&m.sig);
219
+ restoreScope(saved);
220
+ TraitMethodInfo {
221
+ name: m.sig.name.clone(),
222
+ sig,
223
+ hasDefault: m.hasDefault,
224
+ hasSelf: m.sig.has_self,
225
+ minRequired: minRequired(&m.sig),
226
+ line: m.sig.line,
227
+ column: m.sig.column,
228
+ }
229
+ })
230
+ .collect();
231
+ out.traits.entry(t.name.clone()).or_insert(TraitInfo {
232
+ name: t.name.clone(),
233
+ file: t.file.clone(),
234
+ line: t.line,
235
+ column: t.column,
236
+ generics,
237
+ methods,
238
+ });
239
+ }
240
+ ast::Item::Enum(e) => {
241
+ let gens = enumGenericParams(e);
242
+ let saved = setScope(Scope::named(&gens), None);
243
+ if !e.implements.is_empty() {
244
+ let entries = e
245
+ .implements
246
+ .iter()
247
+ .map(|t| ImplEntry {
248
+ ty: plumTypeFromAstG(t),
249
+ trait_name: t.name.clone(),
250
+ args: t.generics.iter().map(plumTypeFromAstG).collect(),
251
+ })
252
+ .collect();
253
+ out.impls.insert(e.name.clone(), (gens.clone(), entries));
254
+ }
255
+ let b = convBounds(&e.generics);
256
+ if !b.is_empty() {
257
+ out.typeBounds.insert(e.name.clone(), b);
258
+ }
259
+ restoreScope(saved);
260
+ }
261
+ ast::Item::Fn(f) if !f.bounds.is_empty() => {
262
+ let saved = setScope(Scope::in_(&owners, f), None);
263
+ let b = f
264
+ .bounds
265
+ .iter()
266
+ .map(|(n, ts)| (n.clone(), ts.iter().map(plumTypeFromAstG).collect()))
267
+ .collect();
268
+ restoreScope(saved);
269
+ out.fnBounds.insert((f.type_param.clone(), f.name.clone()), b);
270
+ }
271
+ _ => {}
272
+ }
273
+ }
274
+ out
275
+ }
276
+
277
+ /// The type of `self` in a method of `name` (a type or a trait): `Orb`, `Queue[T]`.
278
+ fn selfTypeOf(name: &str, generics: &[String]) -> PlumType {
279
+ if generics.is_empty() {
280
+ plumTypeFromName(name)
281
+ } else {
282
+ PlumType::TApp(name.to_string(), generics.iter().map(|g| PlumType::TParam(g.clone())).collect())
283
+ }
284
+ }
285
+
286
+ /// Adds the trait methods to `methods`: every trait method under the trait's name (`Self`
287
+ /// the trait object), and each default a type inherits under the type's name (`Self` the
288
+ /// type). Also their minimum argument counts.
289
+ pub fn addTraitMethods(traits: &Traits, methods: &mut MethodEnv, min_required: Option<&mut MinRequiredArgs>) {
290
+ let mut req: Vec<((Option<String>, String), usize)> = Vec::new();
291
+ for t in traits.traits.values() {
292
+ let selfTy = selfTypeOf(&t.name, &t.generics);
293
+ let s: BTreeMap<String, PlumType> = [(ast::SELF_TYPE.to_string(), selfTy)].into();
294
+ for m in &t.methods {
295
+ methods.insert((t.name.clone(), m.name.clone()), types::substitute(&m.sig, &s));
296
+ req.push(((Some(t.name.clone()), m.name.clone()), m.minRequired));
297
+ }
298
+ }
299
+ for (ty, (gens, entries)) in &traits.impls {
300
+ let selfTy = selfTypeOf(ty, gens);
301
+ for e in entries {
302
+ let Some(t) = traits.traits.get(&e.trait_name) else { continue };
303
+ for m in t.methods.iter().filter(|m| m.hasDefault) {
304
+ let key = (ty.clone(), m.name.clone());
305
+ if methods.contains_key(&key) {
306
+ continue;
307
+ }
308
+ if let Some(sig) = traits.methodSig(&e.ty, &m.name, &selfTy) {
309
+ methods.insert(key, sig);
310
+ req.push(((Some(ty.clone()), m.name.clone()), m.minRequired));
311
+ }
312
+ }
313
+ }
314
+ }
315
+ if let Some(mr) = min_required {
316
+ for (k, n) in req {
317
+ mr.entry(k).or_insert(n);
318
+ }
319
+ }
320
+ }
321
+
322
+ /// The traits of the program being checked.
323
+ pub(crate) fn currentTraits() -> std::rc::Rc<Traits> {
324
+ withCheck(|s| s.traits.borrow().clone())
325
+ }
326
+
327
+ /// The bounds of the generics in scope of the body being checked.
328
+ pub(crate) fn currentBounds() -> BTreeMap<String, Vec<PlumType>> {
329
+ withCheck(|s| s.cur_bounds.borrow().clone())
330
+ }
331
+
332
+ /// `ty` is a trait object of the program being checked.
333
+ pub(crate) fn isTraitObject(ty: &PlumType) -> bool {
334
+ let traits = currentTraits();
335
+ traits.traitObject(ty).is_some()
336
+ }
337
+
338
+ /// Whether a `ty` is accepted where the trait object `tr` is expected.
339
+ pub(crate) fn implementsTrait(ty: &PlumType, tr: &PlumType) -> bool {
340
+ currentTraits().implements(ty, tr, &currentBounds())
341
+ }
342
+
343
+ /// The bounds in scope inside `f`: its owner type's and its own.
344
+ pub(crate) fn boundsOf(f: &ast::Fn) -> BTreeMap<String, Vec<PlumType>> {
345
+ let traits = currentTraits();
346
+ let mut out: BTreeMap<String, Vec<PlumType>> = BTreeMap::new();
347
+ if let Some(owner) = &f.type_param {
348
+ for (g, bs) in traits.typeBounds.get(owner).into_iter().flatten() {
349
+ out.entry(g.clone()).or_default().extend(bs.iter().cloned());
350
+ }
351
+ }
352
+ for (g, bs) in traits.fnBounds.get(&(f.type_param.clone(), f.name.clone())).into_iter().flatten() {
353
+ out.entry(g.clone()).or_default().extend(bs.iter().cloned());
354
+ }
355
+ out
356
+ }
357
+
358
+ /// Runs `body` with the bounds of `f` in scope.
359
+ pub(crate) fn withBounds<R>(f: &ast::Fn, body: impl FnOnce() -> R) -> R {
360
+ let b = boundsOf(f);
361
+ let saved = withCheck(|s| std::mem::replace(&mut *s.cur_bounds.borrow_mut(), b));
362
+ let r = body();
363
+ withCheck(|s| *s.cur_bounds.borrow_mut() = saved);
364
+ r
365
+ }
366
+
367
+ /// A method call on a value of generic type `T` bounded by traits: the bound's method, with
368
+ /// `Self` as `T`. `None` if `T` has no bounds (the call is checked per instantiation).
369
+ pub(crate) fn boundMethodSig(param: &str, method: &str) -> Option<Result<PlumType, String>> {
370
+ let bounds = currentBounds();
371
+ let bs = bounds.get(param).filter(|b| !b.is_empty())?;
372
+ let traits = currentTraits();
373
+ let selfTy = PlumType::TParam(param.to_string());
374
+ for b in bs {
375
+ if let Some(sig) = traits.methodSig(b, method, &selfTy) {
376
+ return Some(Ok(sig));
377
+ }
378
+ }
379
+ let names: Vec<String> = bs.iter().map(|b| b.to_string()).collect();
380
+ Some(Err(format!("{param} has no method '{method}': its bounds ({}) don't declare one", names.join(" + "))))
381
+ }
382
+
383
+ /// The bounds of the generics `gens` of an item with bounds `bounds`, checked against the
384
+ /// type arguments `args`: the first one not met, as a message.
385
+ pub(crate) fn unmetBound(
386
+ item: &str,
387
+ gens: &[String],
388
+ args: &[PlumType],
389
+ bounds: &[(String, Vec<PlumType>)],
390
+ ) -> Option<String> {
391
+ let traits = currentTraits();
392
+ let s = appSubst(gens, args);
393
+ for (g, bs) in bounds {
394
+ let Some(arg) = s.get(g) else { continue };
395
+ if hasFreeVars(arg) {
396
+ continue;
397
+ }
398
+ for b in bs {
399
+ let want = types::substitute(b, &s);
400
+ if hasFreeVars(&want) {
401
+ continue;
402
+ }
403
+ if !traits.implements(arg, &want, &BTreeMap::new()) && !sameType(arg, &want) {
404
+ return Some(format!("{arg} does not implement {want} (the bound of {g} in {item})"));
405
+ }
406
+ }
407
+ }
408
+ None
409
+ }
410
+
411
+ /// The bounds of the generics of the type `ty` (`Store[RunState, Msg]`) that its
412
+ /// arguments don't meet, as a message.
413
+ pub(crate) fn unmetTypeBound(ty: &PlumType, ctx: &CheckCtx) -> Option<String> {
414
+ let PlumType::TApp(name, args) = ty else { return None };
415
+ let traits = currentTraits();
416
+ let bounds = traits.typeBounds.get(name)?;
417
+ unmetBound(name, enumGenericsOf(name, ctx), args, bounds)
418
+ }
419
+
420
+ /// The checks of trait declarations and of each type's `is` entries against the methods
421
+ /// each type declares (`methods` is the method table).
422
+ pub(crate) fn checkTraitDecls(source: &ast::Source, traits: &Traits, methods: &MethodEnv) -> Vec<CheckError> {
423
+ let declared: std::collections::HashSet<(String, String)> = source
424
+ .items
425
+ .iter()
426
+ .filter_map(|i| match i {
427
+ ast::Item::Fn(f) => f.type_param.clone().map(|t| (t, f.name.clone())),
428
+ _ => None,
429
+ })
430
+ .collect();
431
+ let mut errors = Vec::new();
432
+ let types: BTreeMap<&str, &ast::Enum> = source
433
+ .items
434
+ .iter()
435
+ .filter_map(|i| match i {
436
+ ast::Item::Enum(e) => Some((e.name.as_str(), e)),
437
+ _ => None,
438
+ })
439
+ .collect();
440
+ for item in &source.items {
441
+ let ast::Item::Trait(t) = item else { continue };
442
+ let prev = (!t.file.is_empty()).then(|| setCurrentFile(&t.file));
443
+ if types.contains_key(t.name.as_str()) || source.primitives.iter().any(|p| p.name == t.name) {
444
+ errors.push(CheckError::resolution(t.line, t.column, format!("trait '{}' has the same name as a type", t.name)));
445
+ }
446
+ let mut seen: Vec<&str> = Vec::new();
447
+ for m in &t.methods {
448
+ if seen.contains(&m.sig.name.as_str()) {
449
+ errors.push(CheckError::resolution(
450
+ m.sig.line,
451
+ m.sig.column,
452
+ format!("trait '{}' declares method '{}' twice", t.name, m.sig.name),
453
+ ));
454
+ }
455
+ seen.push(&m.sig.name);
456
+ if !m.sig.has_self {
457
+ errors.push(CheckError::resolution(
458
+ m.sig.line,
459
+ m.sig.column,
460
+ format!("trait '{}': method '{}' must take self first", t.name, m.sig.name),
461
+ ));
462
+ }
463
+ if m.sig.is_extern || m.sig.is_export {
464
+ errors.push(CheckError::resolution(
465
+ m.sig.line,
466
+ m.sig.column,
467
+ format!("trait '{}': method '{}' can't be extern or export", t.name, m.sig.name),
468
+ ));
469
+ }
470
+ }
471
+ if let Some(p) = prev {
472
+ setCurrentFile(&p);
473
+ }
474
+ }
475
+ // A bound names a trait, with its type arguments.
476
+ let mut checkBounds = |bounds: &[(String, Vec<ast::Type>)], line: usize, column: usize, what: &str| {
477
+ for (g, bs) in bounds {
478
+ for b in bs {
479
+ match traits.traits.get(&b.name) {
480
+ None => errors.push(CheckError::resolution(
481
+ line,
482
+ column,
483
+ format!("{what}: the bound {} of {g} is not a trait", b.name),
484
+ )),
485
+ Some(t) if t.generics.len() != b.generics.len() => errors.push(CheckError::resolution(
486
+ line,
487
+ column,
488
+ format!(
489
+ "{what}: the bound {} of {g}: trait {} takes {} type argument(s), got {}",
490
+ b.name,
491
+ t.name,
492
+ t.generics.len(),
493
+ b.generics.len()
494
+ ),
495
+ )),
496
+ Some(_) => {}
497
+ }
498
+ }
499
+ }
500
+ };
501
+ for item in &source.items {
502
+ match item {
503
+ ast::Item::Fn(f) if !f.bounds.is_empty() => checkBounds(&f.bounds, f.line, f.column, &format!("fn '{}'", f.name)),
504
+ ast::Item::Enum(e) => {
505
+ let b: Vec<(String, Vec<ast::Type>)> =
506
+ e.generics.iter().filter(|g| !g.bounds.is_empty()).map(|g| (g.name.clone(), g.bounds.clone())).collect();
507
+ checkBounds(&b, e.line, e.column, &e.name);
508
+ }
509
+ _ => {}
510
+ }
511
+ }
512
+ for e in types.values() {
513
+ if e.implements.is_empty() {
514
+ continue;
515
+ }
516
+ let Some((gens, entries)) = traits.impls.get(&e.name) else { continue };
517
+ let selfTy = selfTypeOf(&e.name, gens);
518
+ let at = |m: String| CheckError::resolution(e.line, e.column, m);
519
+ for (i, (written, entry)) in e.implements.iter().zip(entries).enumerate() {
520
+ let Some(t) = traits.traits.get(&entry.trait_name) else {
521
+ errors.push(at(format!("{}: `is {}`: {} is not a trait", e.name, entry.ty, written.name)));
522
+ continue;
523
+ };
524
+ if entry.args.len() != t.generics.len() {
525
+ errors.push(at(format!(
526
+ "{}: `is {}`: trait {} takes {} type argument(s), got {}",
527
+ e.name,
528
+ entry.ty,
529
+ t.name,
530
+ t.generics.len(),
531
+ entry.args.len()
532
+ )));
533
+ continue;
534
+ }
535
+ if let Some(dup) = entries[..i].iter().find(|o| o.trait_name == entry.trait_name) {
536
+ if dup.ty == entry.ty {
537
+ errors.push(at(format!("{}: duplicate `is` entry {}", e.name, entry.ty)));
538
+ } else if let Some(m) = t.methods.first() {
539
+ errors.push(at(format!(
540
+ "{}: implements {} twice ({} and {}): a type has one method per name, so '{}' can't have both signatures",
541
+ e.name, t.name, dup.ty, entry.ty, m.name
542
+ )));
543
+ }
544
+ continue;
545
+ }
546
+ for m in &t.methods {
547
+ let Some(expected) = traits.methodSig(&entry.ty, &m.name, &selfTy) else { continue };
548
+ let key = (e.name.clone(), m.name.clone());
549
+ let Some(found) = methods.get(&key).filter(|_| declared.contains(&key)) else {
550
+ if !m.hasDefault {
551
+ errors.push(at(format!(
552
+ "{} is missing method '{}' of {}: fun {}(self{}) -> {}",
553
+ e.name,
554
+ m.name,
555
+ entry.ty,
556
+ m.name,
557
+ match &expected {
558
+ PlumType::TFun(ps, _) => ps.iter().map(|p| format!(", {p}")).collect::<String>(),
559
+ _ => String::new(),
560
+ },
561
+ match &expected {
562
+ PlumType::TFun(_, r) => r.to_string(),
563
+ _ => String::new(),
564
+ }
565
+ )));
566
+ }
567
+ continue;
568
+ };
569
+ let static_ = source.items.iter().any(|i| {
570
+ matches!(i, ast::Item::Fn(f) if f.type_param.as_deref() == Some(e.name.as_str()) && f.name == m.name && !f.has_self)
571
+ });
572
+ if *found != expected || static_ {
573
+ errors.push(at(format!(
574
+ "{}.{}: its signature differs from {}'s: expected (self{}) -> {}, found {}{}",
575
+ e.name,
576
+ m.name,
577
+ entry.ty,
578
+ match &expected {
579
+ PlumType::TFun(ps, _) => ps.iter().map(|p| format!(", {p}")).collect::<String>(),
580
+ _ => String::new(),
581
+ },
582
+ match &expected {
583
+ PlumType::TFun(_, r) => r.to_string(),
584
+ _ => String::new(),
585
+ },
586
+ if static_ { "a static (no self) " } else { "" },
587
+ match found {
588
+ PlumType::TFun(ps, r) => format!(
589
+ "({}) -> {}",
590
+ std::iter::once("self".to_string()).chain(ps.iter().map(|p| p.to_string())).collect::<Vec<_>>().join(", "),
591
+ r
592
+ ),
593
+ other => other.to_string(),
594
+ }
595
+ )));
596
+ }
597
+ }
598
+ }
599
+ }
600
+ errors
601
+ }
602
+
603
+ /// `Self` written outside a trait's method signatures and default bodies.
604
+ pub(crate) fn selfOutsideTrait(source: &ast::Source) -> Vec<CheckError> {
605
+ let traitNames: std::collections::HashSet<&str> = source
606
+ .items
607
+ .iter()
608
+ .filter_map(|i| match i {
609
+ ast::Item::Trait(t) => Some(t.name.as_str()),
610
+ _ => None,
611
+ })
612
+ .collect();
613
+ let msg = || "`Self` is only allowed in a trait: in a type's own methods write the type's name".to_string();
614
+ let mut errors = Vec::new();
615
+ for item in &source.items {
616
+ match item {
617
+ ast::Item::Fn(f) => {
618
+ if f.type_param.as_deref().is_some_and(|t| traitNames.contains(t)) {
619
+ continue;
620
+ }
621
+ if f.params.iter().any(|p| p.ty.mentionsSelf()) || f.returns.as_ref().is_some_and(|r| r.mentionsSelf()) {
622
+ errors.push(CheckError::resolution(f.line, f.column, format!("fn '{}': {}", f.name, msg())));
623
+ }
624
+ }
625
+ ast::Item::Enum(e) => {
626
+ if e.variants.iter().flat_map(|v| v.fields.iter()).any(|t| t.mentionsSelf())
627
+ || e.implements.iter().any(|t| t.mentionsSelf())
628
+ {
629
+ errors.push(CheckError::resolution(e.line, e.column, format!("{}: {}", e.name, msg())));
630
+ }
631
+ }
632
+ _ => {}
633
+ }
634
+ }
635
+ errors
636
+ }
637
+
638
+ /// The type of branches `vals` that are values of different types implementing one trait:
639
+ /// the trait object the context expects, else the first branch that is a trait object every
640
+ /// branch fits. `None` when no trait object joins them (or they need none).
641
+ pub(crate) fn joinTrait(expected: Option<&PlumType>, vals: &[PlumType], ctx: &CheckCtx) -> Option<PlumType> {
642
+ if currentTraits().isEmpty() || vals.len() < 2 {
643
+ return None;
644
+ }
645
+ let vals: Vec<PlumType> = vals.iter().map(resolveRecorded).collect();
646
+ if vals.windows(2).all(|w| w[0] == w[1]) {
647
+ return None;
648
+ }
649
+ let candidates = expected.map(resolveRecorded).into_iter().chain(vals.iter().cloned());
650
+ for c in candidates {
651
+ if isTraitObject(&c) && vals.iter().all(|v| unify(&c, v, ctx).is_ok()) {
652
+ return Some(c);
653
+ }
654
+ }
655
+ None
656
+ }
compiler/checker/src/unification.rs CHANGED
@@ -147,7 +147,7 @@ pub fn unify(t1: &PlumType, t2: &PlumType, ctx: &CheckCtx) -> Result<(), String>
147
147
  // Structural generics: same base, arguments unify pairwise.
148
148
  (PlumType::TApp(a, xs), PlumType::TApp(b, ys)) if a == b && xs.len() == ys.len() => {
149
149
  for (x, y) in xs.iter().zip(ys.iter()) {
150
- unify(x, y, ctx)
150
+ unifyPart(x, y, ctx)
151
151
  .map_err(|e| format!("type mismatch: expected {}, found {} ({})", t1, t2, e))?;
152
152
  }
153
153
  Ok(())
@@ -192,14 +192,39 @@ pub fn unify(t1: &PlumType, t2: &PlumType, ctx: &CheckCtx) -> Result<(), String>
192
192
  }
193
193
  (PlumType::TFun(ps1, r1), PlumType::TFun(ps2, r2)) if ps1.len() == ps2.len() => {
194
194
  for (p1, p2) in ps1.iter().zip(ps2.iter()) {
195
- unify(p1, p2, ctx)?;
195
+ unifyPart(p1, p2, ctx)?;
196
+ }
197
+ unifyPart(r1, r2, ctx)
198
+ }
199
+ // A trait object accepts a value of any type that implements the trait (never the
200
+ // other way round: `Type as name` in a `match` is the only downcast).
201
+ (expected, actual) if isTraitObject(expected) => {
202
+ let implements = implementsTrait(actual, expected);
203
+ if implements && !withCheck(|s| s.no_coerce.get()) {
204
+ Ok(())
205
+ } else if implements {
206
+ Err(format!(
207
+ "type mismatch: expected {expected}, found {actual} (inside another type a value must already be a {expected})"
208
+ ))
209
+ } else if isTraitObject(actual) || matches!(actual, PlumType::TFun(..)) {
210
+ Err(format!("type mismatch: expected {}, found {}", t1, t2))
211
+ } else {
212
+ Err(format!("type mismatch: {} does not implement {}", actual, expected))
196
213
  }
197
- unify(r1, r2, ctx)
198
214
  }
199
215
  _ => Err(format!("type mismatch: expected {}, found {}", t1, t2)),
200
216
  }
201
217
  }
202
218
 
219
+ /// `unify` of a part of a type (an argument of a generic, a parameter or result of a fn
220
+ /// type): equal types only, a trait object accepting no implementer there.
221
+ fn unifyPart(t1: &PlumType, t2: &PlumType, ctx: &CheckCtx) -> Result<(), String> {
222
+ let prev = withCheck(|s| s.no_coerce.replace(true));
223
+ let r = unify(t1, t2, ctx);
224
+ withCheck(|s| s.no_coerce.set(prev));
225
+ r
226
+ }
227
+
203
228
  /// True if `expr` (looking through parens) is a direct construction/reference
204
229
  /// of exactly the enum variant named `variant_name` — a bare payload-free
205
230
  /// reference (`Red`), a positional-payload construction (`Circle(1)`), or a
compiler/checker/tests/checker/main.rs CHANGED
@@ -12,3 +12,4 @@ mod fusion_pipeline_test;
12
12
  mod inline_variants_tests;
13
13
  mod question_tests;
14
14
  mod syntax_tests;
15
+ mod traits_tests;
compiler/checker/tests/checker/traits_tests.rs ADDED
@@ -0,0 +1,560 @@
1
+ #![allow(non_snake_case)]
2
+ //! Traits: conformance, trait objects, `Self`, downcasts and bounds (checker only: codegen
3
+ //! doesn't compile traits yet).
4
+ use plum_checker::types::PlumType;
5
+
6
+ const PRE: &str = "import std/Str\nimport std/Int\nimport std/Float\nimport std/List\n\nfun show(s: Str) = Unit\n\n";
7
+
8
+ const ACTOR: &str = "trait Actor =
9
+ fun key(self) -> Int
10
+ fun step(self, dt: Float) -> Self = self
11
+ fun hit(self, p: Int) -> Bool = self.key() == p
12
+
13
+ struct Orb(id: Int, vx: Float) is Actor =
14
+ fun key(self) -> Int = self.id
15
+ fun step(self, dt: Float) -> Orb = Orb(..self, vx: self.vx + dt)
16
+
17
+ struct Label(id: Int, text: Str) is Actor =
18
+ fun key(self) -> Int = self.id
19
+
20
+ struct Rock(id: Int)
21
+
22
+ ";
23
+
24
+ fn check(src: &str) -> Result<plum_checker::TypedInfo, Vec<String>> {
25
+ let source = plum_test_support::load("traits", &format!("{PRE}{src}")).unwrap_or_else(|e| panic!("load failed: {e}"));
26
+ let (r, info) = plum_checker::checkProgram(&source);
27
+ r.map(|()| info).map_err(|es| es.into_iter().map(|e| e.message).collect())
28
+ }
29
+
30
+ fn ok(src: &str) -> plum_checker::TypedInfo {
31
+ check(src).unwrap_or_else(|es| panic!("expected no errors, got:\n{}", es.join("\n")))
32
+ }
33
+
34
+ /// The program fails to check with an error containing `want`.
35
+ fn fails(src: &str, want: &str) {
36
+ match check(src) {
37
+ Ok(_) => panic!("expected an error containing {want:?}, but it checked"),
38
+ Err(es) => assert!(es.iter().any(|e| e.contains(want)), "no error contains {want:?}:\n{}", es.join("\n")),
39
+ }
40
+ }
41
+
42
+ #[test]
43
+ fn implementersAreTraitObjects() {
44
+ ok(&format!(
45
+ "{ACTOR}fun stepAll(xs: List[Actor], dt: Float) -> List[Actor] = xs.map(|a| a.step(dt))
46
+
47
+ fun first(a: Actor) -> Int = a.key()
48
+
49
+ fun main() =
50
+ o := Orb(id: 1, vx: 2.0)
51
+ l := Label(id: 2, text: \"hi\")
52
+ xs: List[Actor] := [o, l]
53
+ ys := stepAll(xs, 1.0)
54
+ _ := first(o)
55
+ _ := first(l)
56
+ show(\"{{ys.length()}}\")
57
+ "
58
+ ));
59
+ }
60
+
61
+ #[test]
62
+ fn selfReturnIsTheTraitObjectOrTheConcreteType() {
63
+ // On a trait object `step` returns an Actor; on a concrete type, that type (also for a
64
+ // default the type doesn't override).
65
+ ok(&format!(
66
+ "{ACTOR}fun main() =
67
+ o := Orb(id: 1, vx: 2.0).step(1.0)
68
+ l := Label(id: 2, text: \"hi\").step(1.0)
69
+ a: Actor := o
70
+ b := a.step(1.0)
71
+ show(\"{{o.vx}} {{l.text}} {{b.key()}} {{l.hit(2)}}\")
72
+ "
73
+ ));
74
+ fails(
75
+ &format!("{ACTOR}fun f(a: Actor) -> Orb = a.step(1.0)\n"),
76
+ "expected Orb, found Actor",
77
+ );
78
+ }
79
+
80
+ #[test]
81
+ fn defaultsCallTheTraitsMethods() {
82
+ ok(&format!("{ACTOR}fun main() = show(\"{{Label(id: 1, text: \"a\").hit(1)}}\")\n"));
83
+ // a default sees `self` as the trait object: only the trait's methods
84
+ fails(
85
+ "trait T =
86
+ fun key(self) -> Int
87
+ fun twice(self) -> Int = self.id * 2
88
+ ",
89
+ "no field 'id' on T",
90
+ );
91
+ fails(
92
+ "trait T =
93
+ fun key(self) -> Int
94
+ fun twice(self) -> Int = self.other()
95
+ ",
96
+ "T has no method 'other'",
97
+ );
98
+ }
99
+
100
+ #[test]
101
+ fn missingRequiredMethod() {
102
+ fails(
103
+ "trait Actor =
104
+ fun key(self) -> Int
105
+ fun name(self) -> Str = \"x\"
106
+
107
+ struct Orb(id: Int) is Actor
108
+ ",
109
+ "Orb is missing method 'key' of Actor",
110
+ );
111
+ }
112
+
113
+ #[test]
114
+ fn methodSignatureDiffers() {
115
+ fails(
116
+ "trait Actor =
117
+ fun key(self) -> Int
118
+
119
+ struct Orb(id: Int) is Actor =
120
+ fun key(self) -> Float = 1.0
121
+ ",
122
+ "Orb.key: its signature differs from Actor's",
123
+ );
124
+ // a typo'd override of an optional method doesn't fall back to the default
125
+ fails(
126
+ "trait Actor =
127
+ fun key(self) -> Int
128
+ fun hit(self, p: Int) -> Bool = false
129
+
130
+ struct Orb(id: Int) is Actor =
131
+ fun key(self) -> Int = self.id
132
+ fun hit(self, p: Float) -> Bool = true
133
+ ",
134
+ "Orb.hit: its signature differs from Actor's",
135
+ );
136
+ // `Self` is replaced by the type
137
+ fails(
138
+ "trait Actor =
139
+ fun step(self) -> Self
140
+
141
+ struct Orb(id: Int) is Actor =
142
+ fun step(self) -> Int = 1
143
+ ",
144
+ "expected (self) -> Orb",
145
+ );
146
+ }
147
+
148
+ #[test]
149
+ fn selfOutsideATrait() {
150
+ fails("struct Orb(id: Int) =\n fun me(self) -> Self = self\n", "`Self` is only allowed in a trait");
151
+ fails("fun f(x: Self) -> Int = 1\n", "`Self` is only allowed in a trait");
152
+ }
153
+
154
+ #[test]
155
+ fn methodNotInTheTrait() {
156
+ fails(
157
+ &format!("{ACTOR}fun f(a: Actor) -> Float = a.vx\n"),
158
+ "no field 'vx' on Actor",
159
+ );
160
+ fails(
161
+ &format!("{ACTOR}fun f(a: Actor) -> Int = a.size()\n"),
162
+ "Actor has no method 'size'",
163
+ );
164
+ }
165
+
166
+ #[test]
167
+ fn nonImplementerUsedAsTheTrait() {
168
+ fails(
169
+ &format!("{ACTOR}fun f(a: Actor) -> Int = a.key()\n\nfun main() = show(\"{{f(Rock(id: 1))}}\")\n"),
170
+ "Rock does not implement Actor",
171
+ );
172
+ fails(&format!("{ACTOR}fun f() -> Actor = 3\n"), "Int does not implement Actor");
173
+ // no downcast without a pattern
174
+ fails(&format!("{ACTOR}fun f(a: Actor) -> Orb = a\n"), "expected Orb, found Actor");
175
+ }
176
+
177
+ #[test]
178
+ fn downcastPattern() {
179
+ let info = ok(&format!(
180
+ "{ACTOR}fun still(a: Actor) -> Actor =
181
+ match a
182
+ Orb as o => Orb(..o, vx: 0.0)
183
+ _ => a
184
+
185
+ fun speed(a: Actor) -> Float =
186
+ match a
187
+ Orb as o => o.vx
188
+ Label as l => 0.0
189
+ _ => -1.0
190
+
191
+ fun main() = show(\"{{still(Label(id: 1, text: \"a\")).key()}} {{speed(Orb(id: 1, vx: 2.0))}}\")
192
+ "
193
+ ));
194
+ // `o` is typed as the concrete type
195
+ let lowered = info.lowered.clone().expect("lowered");
196
+ let _ = lowered;
197
+ assert!(info.expr_types.values().any(|t| *t == PlumType::TNamed("Orb".to_string())));
198
+ }
199
+
200
+ #[test]
201
+ fn downcastToANonImplementer() {
202
+ fails(
203
+ &format!("{ACTOR}fun f(a: Actor) -> Int =\n match a\n Rock as r => r.id\n _ => 0\n"),
204
+ "Rock does not implement Actor",
205
+ );
206
+ }
207
+
208
+ #[test]
209
+ fn downcastNeedsATraitObjectAndAFallback() {
210
+ fails(
211
+ &format!("{ACTOR}fun f(a: Actor) -> Int =\n match a\n Orb as o => o.id\n"),
212
+ "non-exhaustive match on Actor",
213
+ );
214
+ fails(
215
+ &format!("{ACTOR}fun f(o: Orb) -> Int =\n match o\n Label as l => l.id\n _ => 0\n"),
216
+ "needs a trait object",
217
+ );
218
+ }
219
+
220
+ #[test]
221
+ fn downcastBinderThatShadowsALocal() {
222
+ // the match-arm binder pass renames `o` in the arm; the outer `o` stays an Int
223
+ ok(&format!(
224
+ "{ACTOR}fun f(a: Actor) -> Int =
225
+ o := 5
226
+ k := match a
227
+ Orb as o => o.id
228
+ _ => 0
229
+ k + o
230
+ "
231
+ ));
232
+ }
233
+
234
+ #[test]
235
+ fn duplicateIsEntry() {
236
+ fails(
237
+ "trait Actor =\n fun key(self) -> Int\n\nstruct Orb(id: Int) is Actor, Actor =\n fun key(self) -> Int = self.id\n",
238
+ "duplicate `is` entry Actor",
239
+ );
240
+ }
241
+
242
+ #[test]
243
+ fn isNamesATrait() {
244
+ fails("struct Orb(id: Int) is Rocks\n\nstruct Rocks(n: Int)\n", "Rocks is not a trait");
245
+ }
246
+
247
+ #[test]
248
+ fn enumImplementsATrait() {
249
+ ok("trait Shape =
250
+ fun area(self) -> Float
251
+ fun big(self) -> Bool = self.area() > 10.0
252
+
253
+ enum Fig is Shape =
254
+ | Circle(r: Float)
255
+ | Square(s: Float)
256
+
257
+ fun area(self) -> Float = match self
258
+ Circle(r) => 3.0 * r * r
259
+ Square(s) => s * s
260
+
261
+ fun total(xs: List[Shape]) -> Float = xs.fold(0.0, |acc, x| acc + x.area())
262
+
263
+ fun main() =
264
+ xs: List[Shape] := [Circle(r: 1.0), Square(s: 2.0)]
265
+ show(\"{total(xs)} {Circle(r: 3.0).big()}\")
266
+ ");
267
+ }
268
+
269
+ const REDUCER: &str = "trait Reducer[M] =
270
+ fun update(self, msg: M) -> Self
271
+ fun count(self, msg: M) -> Int = 1
272
+
273
+ struct RunState(score: Int) is Reducer[Int] =
274
+ fun update(self, msg: Int) -> RunState = RunState(score: self.score + msg)
275
+
276
+ struct Words(n: Int) is Reducer[Str] =
277
+ fun update(self, msg: Str) -> Words = Words(n: self.n + 1)
278
+
279
+ ";
280
+
281
+ #[test]
282
+ fn traitWithTypeParameters() {
283
+ let info = ok(&format!(
284
+ "{REDUCER}fun replay[M](r: Reducer[M], msgs: List[M]) -> Reducer[M] = msgs.fold(r, |a, m| a.update(m))
285
+
286
+ fun main() =
287
+ r: Reducer[Int] := RunState(score: 0)
288
+ r2 := replay(r, [1, 2])
289
+ w: Reducer[Str] := Words(n: 0)
290
+ show(\"{{r2.count(1)}} {{w.update(\"a\").count(\"b\")}}\")
291
+ "
292
+ ));
293
+ // one implementer set per (trait, arguments)
294
+ let sets = info.traits.implementerSets();
295
+ let get = |args: Vec<PlumType>| sets.iter().find(|(k, _)| k.0 == "Reducer" && k.1 == args).map(|(_, v)| v.clone());
296
+ assert_eq!(get(vec![PlumType::TInt]), Some(vec!["RunState".to_string()]));
297
+ assert_eq!(get(vec![plum_checker::types::strType()]), Some(vec!["Words".to_string()]));
298
+ assert_eq!(info.traits.implementers("Reducer", &[PlumType::TInt]), vec!["RunState".to_string()]);
299
+ }
300
+
301
+ #[test]
302
+ fn traitArgumentsMustMatch() {
303
+ fails(
304
+ &format!("{REDUCER}fun main() =\n r: Reducer[Str] := RunState(score: 0)\n show(\"x\")\n"),
305
+ "RunState does not implement Reducer[Str]",
306
+ );
307
+ fails(
308
+ "trait Reducer[M] =\n fun update(self, msg: M) -> Self\n\nstruct S(n: Int) is Reducer =\n fun update(self, msg: Int) -> S = self\n",
309
+ "trait Reducer takes 1 type argument(s), got 0",
310
+ );
311
+ fails(
312
+ "trait Reducer[M] =\n fun update(self, msg: M) -> Self\n\nstruct S(n: Int) is Reducer[Int] =\n fun update(self, msg: Str) -> S = self\n",
313
+ "S.update: its signature differs from Reducer[Int]'s",
314
+ );
315
+ }
316
+
317
+ #[test]
318
+ fn sameTraitTwiceWithDifferentArguments() {
319
+ fails(
320
+ "trait Reducer[M] =\n fun update(self, msg: M) -> Self\n\nstruct S(n: Int) is Reducer[Int], Reducer[Str] =\n fun update(self, msg: Int) -> S = self\n",
321
+ "implements Reducer twice",
322
+ );
323
+ }
324
+
325
+ #[test]
326
+ fn boundsOnFunctions() {
327
+ ok(&format!(
328
+ "{REDUCER}fun replay[S: Reducer[M], M](s: S, msgs: List[M]) -> S = msgs.fold(s, |a, m| a.update(m))
329
+
330
+ fun main() =
331
+ s := replay(RunState(score: 0), [1, 2, 3])
332
+ show(\"{{s.score}}\")
333
+ "
334
+ ));
335
+ // the result is `S`, the concrete type: no downcast
336
+ fails(
337
+ &format!("{REDUCER}fun replay[S: Reducer[M], M](s: S, msgs: List[M]) -> S = msgs.fold(s, |a, m| a.update(m))\n\nfun main() =\n s := replay(Rock(n: 1), [1])\n show(\"x\")\n\nstruct Rock(n: Int)\n"),
338
+ "Rock does not implement Reducer[Int]",
339
+ );
340
+ }
341
+
342
+ #[test]
343
+ fn boundMethodsInTheBody() {
344
+ // a bounded `T` has the bound's methods and nothing else
345
+ fails(
346
+ &format!("{ACTOR}fun f[T: Actor](x: T) -> Int = x.size()\n\nfun main() = show(\"{{f(Orb(id: 1, vx: 1.0))}}\")\n"),
347
+ "T has no method 'size'",
348
+ );
349
+ ok(&format!(
350
+ "{ACTOR}fun f[T: Actor](x: T) -> T = x.step(1.0)
351
+
352
+ fun g[T: Actor](x: T) -> Actor = x
353
+
354
+ fun main() =
355
+ o := f(Orb(id: 1, vx: 1.0))
356
+ show(\"{{o.vx}} {{g(o).key()}}\")
357
+ "
358
+ ));
359
+ }
360
+
361
+ #[test]
362
+ fn severalBounds() {
363
+ ok(&format!(
364
+ "{ACTOR}trait Named =
365
+ fun name(self) -> Str
366
+
367
+ struct Ship(id: Int) is Actor, Named =
368
+ fun key(self) -> Int = self.id
369
+ fun name(self) -> Str = \"ship\"
370
+
371
+ fun tag[T: Actor + Named](x: T) -> Str = \"{{x.name()}}{{x.key()}}\"
372
+
373
+ fun main() = show(tag(Ship(id: 1)))
374
+ "
375
+ ));
376
+ fails(
377
+ &format!("{ACTOR}trait Named =\n fun name(self) -> Str\n\nfun tag[T: Actor + Named](x: T) -> Str = x.name()\n\nfun main() = show(tag(Orb(id: 1, vx: 1.0)))\n"),
378
+ "Orb does not implement Named",
379
+ );
380
+ }
381
+
382
+ #[test]
383
+ fn boundsOnStructs() {
384
+ ok(&format!(
385
+ "{REDUCER}struct Store[S: Reducer[M], M](state: S, n: Int) =
386
+ fun dispatch(self, msg: M) -> Store[S, M] = Store(..self, state: self.state.update(msg))
387
+
388
+ fun main() =
389
+ st := Store(state: RunState(score: 0), n: 0).dispatch(4)
390
+ show(\"{{st.state.score}}\")
391
+ "
392
+ ));
393
+ fails(
394
+ &format!("{REDUCER}struct Store[S: Reducer[M], M](state: S, m: M)\n\nstruct Rock(n: Int)\n\nfun main() =\n st := Store(state: Rock(n: 1), m: 1)\n show(\"x\")\n"),
395
+ "Rock does not implement Reducer[Int]",
396
+ );
397
+ }
398
+
399
+ #[test]
400
+ fn boundsNameTraits() {
401
+ fails("struct Rock(n: Int)\n\nfun f[T: Rock](x: T) -> T = x\n", "the bound Rock of T is not a trait");
402
+ fails(
403
+ "trait Reducer[M] =\n fun update(self, msg: M) -> Self\n\nstruct Store[S: Reducer](s: S)\n",
404
+ "trait Reducer takes 1 type argument(s), got 0",
405
+ );
406
+ }
407
+
408
+ #[test]
409
+ fn traitObjectsAreMatchedByType() {
410
+ fails(
411
+ &format!("{ACTOR}fun f(a: Actor) -> Int =\n match a\n Orb(i, v) => i\n _ => 0\n"),
412
+ "is matched by type",
413
+ );
414
+ }
415
+
416
+ #[test]
417
+ fn traitMethodsTakeSelf() {
418
+ fails("trait T =\n fun make() -> Int\n", "method 'make' must take self first");
419
+ fails("trait T =\n fun a(self) -> Int\n fun a(self) -> Int\n", "declares method 'a' twice");
420
+ }
421
+
422
+ #[test]
423
+ fn coercionIsOfWholeValuesOnly() {
424
+ // a `List[Orb]` is not a `List[Actor]`, nor a `fn(Orb) -> Orb` a `fn(Actor) -> Actor`
425
+ fails(
426
+ &format!("{ACTOR}fun f(xs: List[Orb]) -> List[Actor] = xs\n"),
427
+ "inside another type a value must already be a Actor",
428
+ );
429
+ fails(
430
+ &format!("{ACTOR}fun app(f: fn(Actor) -> Actor, a: Actor) -> Actor = f(a)\n\nfun g(o: Orb) -> Orb = o\n\nfun h(a: Actor) -> Actor = app(g, a)\n"),
431
+ "type mismatch",
432
+ );
433
+ // a branch join to the trait the context expects
434
+ ok(&format!(
435
+ "{ACTOR}fun pick(c: Bool, o: Orb, l: Label) -> Actor = if c then o else l
436
+
437
+ fun pick2(c: Bool, o: Orb, l: Label) -> Actor =
438
+ if c
439
+ o
440
+ else
441
+ l
442
+
443
+ fun main() = show(\"{{pick(true, Orb(id: 1, vx: 1.0), Label(id: 2, text: \"a\")).key()}}\")
444
+ "
445
+ ));
446
+ }
447
+
448
+ #[test]
449
+ fn traitObjectEquality() {
450
+ ok(&format!("{ACTOR}fun same(a: Actor, b: Actor) -> Bool = a == b\n\nfun same2(a: Actor, o: Orb) -> Bool = a == o\n"));
451
+ }
452
+
453
+ const GAME: &str = "trait Actor[M] =
454
+ fun key(self) -> Int
455
+ fun input(self, e: Int) -> Option[M] = None
456
+ fun step(self, dt: Float) -> Self = self
457
+
458
+ struct Box[M](id: Int, w: Float) is Actor[M] =
459
+ fun key(self) -> Int = self.id
460
+
461
+ struct Button[M](id: Int, onClick: M) is Actor[M] =
462
+ fun key(self) -> Int = self.id
463
+ fun input(self, e: Int) -> Option[M] = Some(self.onClick)
464
+
465
+ enum Msg = Collected(id: Int) | Hurt | StartPressed
466
+
467
+ struct Orb(id: Int, vx: Float) is Actor[Msg] =
468
+ fun key(self) -> Int = self.id
469
+ fun step(self, dt: Float) -> Orb = Orb(..self, vx: self.vx + dt)
470
+
471
+ ";
472
+
473
+ #[test]
474
+ fn genericTypeImplementsAGenericTraitWithItsOwnParameter() {
475
+ let info = ok(&format!(
476
+ "{GAME}fun tree() -> List[Actor[Msg]] =
477
+ b: Box[Msg] := Box(id: 1, w: 2.0)
478
+ bt: Button[Msg] := Button(id: 2, onClick: StartPressed)
479
+ xs: List[Actor[Msg]] := [b, bt, Orb(id: 3, vx: 1.0)]
480
+ xs
481
+
482
+ fun clicks(xs: List[Actor[Msg]]) -> List[Option[Msg]] = xs.map(|a| a.input(0))
483
+
484
+ fun stepped(b: Box[Int]) -> Box[Int] = b.step(1.0)
485
+
486
+ fun keys(xs: List[Actor[Int]]) -> Int = xs.fold(0, |n, a| n + a.key())
487
+
488
+ fun main() =
489
+ bi: Box[Int] := Box(id: 1, w: 1.0)
490
+ ys: List[Actor[Int]] := [bi, Button(id: 2, onClick: 7)]
491
+ show(\"{{tree().length()}} {{clicks(tree()).length()}} {{keys(ys)}} {{stepped(bi).w}}\")
492
+ "
493
+ ));
494
+ // `Box[M]` is listed once, under its entry `Actor[M]`; `Orb` under `Actor[Msg]`
495
+ let sets = info.traits.implementerSets();
496
+ assert!(sets.iter().any(|(k, v)| k.0 == "Actor" && k.1 == vec![PlumType::TParam("M".to_string())] && v.contains(&"Box".to_string())), "{sets:?}");
497
+ assert!(sets.iter().any(|(k, v)| k.0 == "Actor" && k.1 == vec![PlumType::TNamed("Msg".to_string())] && v == &vec!["Orb".to_string()]), "{sets:?}");
498
+ // `Orb` is an `Actor[Msg]` only, `Box[Int]` an `Actor[Int]` only
499
+ fails(
500
+ &format!("{GAME}fun f() -> Actor[Int] = Orb(id: 1, vx: 1.0)\n"),
501
+ "Orb does not implement Actor[Int]",
502
+ );
503
+ fails(
504
+ &format!("{GAME}fun f(b: Box[Int]) -> Actor[Msg] = b\n"),
505
+ "Box[Int] does not implement Actor[Msg]",
506
+ );
507
+ // the generic type's methods must fit the trait with its own parameter
508
+ fails(
509
+ "trait Actor[M] =\n fun input(self, e: Int) -> Option[M]\n\nstruct Box[M](id: Int) is Actor[M] =\n fun input(self, e: Int) -> Option[Int] = None\n",
510
+ "Box.input: its signature differs from Actor[M]'s",
511
+ );
512
+ }
513
+
514
+ #[test]
515
+ fn traitWithTwoParametersReturningItsOwnTraitObject() {
516
+ ok(&format!(
517
+ "{GAME}struct RunState(score: Int)
518
+
519
+ trait Screen[S, M] =
520
+ fun name(self) -> Str
521
+ fun react(self, state: S, msg: M) -> Self = self
522
+ fun next(self, state: S, msg: M) -> Option[Screen[S, M]] = None
523
+
524
+ struct Title(n: Int) is Screen[RunState, Msg] =
525
+ fun name(self) -> Str = \"title\"
526
+ fun next(self, state: RunState, msg: Msg) -> Option[Screen[RunState, Msg]] = match msg
527
+ StartPressed => Some(Play(lives: 3))
528
+ _ => None
529
+
530
+ struct Play(lives: Int) is Screen[RunState, Msg] =
531
+ fun name(self) -> Str = \"play\"
532
+ fun react(self, state: RunState, msg: Msg) -> Play = match msg
533
+ Hurt => Play(lives: self.lives - 1)
534
+ _ => self
535
+
536
+ fun advance(s: Screen[RunState, Msg], st: RunState, m: Msg) -> Screen[RunState, Msg] =
537
+ r := s.react(st, m)
538
+ match r.next(st, m)
539
+ Some(n) => n
540
+ None => r
541
+
542
+ fun main() =
543
+ s: Screen[RunState, Msg] := Title(n: 0)
544
+ show(advance(s, RunState(score: 0), StartPressed).name())
545
+ "
546
+ ));
547
+ fails(
548
+ &format!(
549
+ "{GAME}struct RunState(score: Int)\n\ntrait Screen[S, M] =\n fun next(self, state: S, msg: M) -> Option[Screen[S, M]]\n\nstruct Title(n: Int) is Screen[RunState, Msg] =\n fun next(self, state: RunState, msg: Msg) -> Option[Screen[RunState, Int]] = None\n"
550
+ ),
551
+ "Title.next: its signature differs from Screen[RunState, Msg]'s",
552
+ );
553
+ }
554
+
555
+ #[test]
556
+ fn traitsDontCompileYet() {
557
+ 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();
559
+ assert!(err.contains("traits not yet supported in codegen"), "{err}");
560
+ }
compiler/core/src/ast.rs CHANGED
@@ -165,7 +165,7 @@ pub fn numberIds(src: &mut Source) {
165
165
  }
166
166
  Item::Const(c) => numberExpr(&mut c.value, false),
167
167
  Item::Test(t) => numberBlock(&mut t.body, false),
168
- Item::Enum(_) => {}
168
+ Item::Enum(_) | Item::Trait(_) => {}
169
169
  }
170
170
  }
171
171
  }
@@ -266,7 +266,7 @@ fn firstNode(src: &Source, bad: &mut dyn FnMut(NodeId) -> bool) -> Option<NodeId
266
266
  }),
267
267
  Item::Const(c) => expr(&c.value, bad),
268
268
  Item::Test(t) => block(&t.body, bad),
269
- Item::Enum(_) => None,
269
+ Item::Enum(_) | Item::Trait(_) => None,
270
270
  };
271
271
  if d.is_some() {
272
272
  return d;
@@ -357,6 +357,7 @@ impl Source {
357
357
  match item {
358
358
  Item::Fn(f) => f.file = file.to_string(),
359
359
  Item::Test(t) => t.file = file.to_string(),
360
+ Item::Trait(t) => t.file = file.to_string(),
360
361
  _ => {}
361
362
  }
362
363
  }
@@ -409,6 +410,10 @@ pub struct Import {
409
410
  #[derive(Debug, Clone, PartialEq)]
410
411
  pub enum Item {
411
412
  Enum(Enum),
413
+ /// `trait Name[..] =` + method signatures. Its default bodies are also ordinary
414
+ /// methods of the trait (`Item::Fn` with `type_param` = the trait's name, `Self`
415
+ /// written as the trait object type), so every pass sees them like any method.
416
+ Trait(Trait),
412
417
  Fn(Fn),
413
418
  Const(Const),
414
419
  Test(Test),
@@ -419,6 +424,89 @@ pub enum Item {
419
424
  #[derive(Debug, Clone, PartialEq)]
420
425
  pub struct GenericParam {
421
426
  pub name: String,
427
+ /// `[T: Show + Eq]`: the traits `T` must implement (empty = unbounded).
428
+ pub bounds: Vec<Type>,
429
+ }
430
+
431
+ /// The name a trait method's signature uses for the implementing type.
432
+ pub const SELF_TYPE: &str = "Self";
433
+
434
+ /// `trait Actor =` / `trait Reducer[M] =`: a list of method signatures.
435
+ #[derive(Debug, Clone, PartialEq)]
436
+ pub struct Trait {
437
+ pub name: String,
438
+ /// Declaring file (stamped by the loader).
439
+ pub file: String,
440
+ /// 1-based position of the `trait` keyword (0 if unknown).
441
+ pub line: usize,
442
+ pub column: usize,
443
+ pub generics: Vec<GenericParam>,
444
+ pub methods: Vec<TraitMethod>,
445
+ }
446
+
447
+ /// One method of a trait: its signature as written (with `Self`; the body is
448
+ /// always `FnBody::Extern`), and whether it has a default body.
449
+ #[derive(Debug, Clone, PartialEq)]
450
+ pub struct TraitMethod {
451
+ pub sig: Fn,
452
+ pub hasDefault: bool,
453
+ }
454
+
455
+ impl Trait {
456
+ pub fn method(&self, name: &str) -> Option<&TraitMethod> {
457
+ self.methods.iter().find(|m| m.sig.name == name)
458
+ }
459
+ /// The trait as a type inside its own declaration: `Actor`, `Reducer[M]`.
460
+ pub fn selfType(&self) -> Type {
461
+ Type {
462
+ name: self.name.clone(),
463
+ generics: self.generics.iter().map(|g| Type { name: g.name.clone(), generics: vec![] }).collect(),
464
+ }
465
+ }
466
+ }
467
+
468
+ impl Type {
469
+ /// `self` with every `Self` replaced by `with`.
470
+ pub fn replaceSelf(&self, with: &Type) -> Type {
471
+ if self.name == SELF_TYPE && self.generics.is_empty() {
472
+ return with.clone();
473
+ }
474
+ Type { name: self.name.clone(), generics: self.generics.iter().map(|g| g.replaceSelf(with)).collect() }
475
+ }
476
+ /// Whether `Self` appears anywhere in this type.
477
+ pub fn mentionsSelf(&self) -> bool {
478
+ self.name == SELF_TYPE || self.generics.iter().any(|g| g.mentionsSelf())
479
+ }
480
+ }
481
+
482
+ impl ParamType {
483
+ pub fn replaceSelf(&self, with: &Type) -> ParamType {
484
+ match self {
485
+ ParamType::Type(t) => ParamType::Type(t.replaceSelf(with)),
486
+ ParamType::Fn(ps, r) => ParamType::Fn(
487
+ ps.iter().map(|p| p.replaceSelf(with)).collect(),
488
+ r.as_ref().map(|r| Box::new(r.replaceSelf(with))),
489
+ ),
490
+ }
491
+ }
492
+ pub fn mentionsSelf(&self) -> bool {
493
+ match self {
494
+ ParamType::Type(t) => t.mentionsSelf(),
495
+ ParamType::Fn(ps, r) => ps.iter().any(|p| p.mentionsSelf()) || r.as_ref().is_some_and(|r| r.mentionsSelf()),
496
+ }
497
+ }
498
+ }
499
+
500
+ impl Fn {
501
+ /// This fn's signature with every `Self` replaced by `with`.
502
+ pub fn replaceSelf(&mut self, with: &Type) {
503
+ for p in &mut self.params {
504
+ p.ty = p.ty.replaceSelf(with);
505
+ }
506
+ if let Some(r) = &mut self.returns {
507
+ *r = r.replaceSelf(with);
508
+ }
509
+ }
422
510
  }
423
511
 
424
512
  #[derive(Debug, Clone, PartialEq)]
@@ -434,6 +522,8 @@ pub struct Enum {
434
522
  /// ...`). Empty for a non-generic enum.
435
523
  pub generics: Vec<GenericParam>,
436
524
  pub variants: Vec<EnumVariant>,
525
+ /// `is A, B[X]`: the traits this type implements, as written.
526
+ pub implements: Vec<Type>,
437
527
  /// What this declaration is: a plain `enum`, or a `struct` with its
438
528
  /// struct-only data.
439
529
  pub kind: TypeKind,
@@ -514,6 +604,9 @@ pub struct Fn {
514
604
  /// Declared type parameters: `fun map[B](..)` gives `["B"]`. Empty when the fn
515
605
  /// declares none (single-letter names are still implicit generics).
516
606
  pub generics: Vec<String>,
607
+ /// `fun f[T: Show](..)`: the bounds of the fn's own generics, `(name, traits)` for
608
+ /// each bounded one.
609
+ pub bounds: Vec<(String, Vec<Type>)>,
517
610
  /// `extern fun foo(...)` — declares a function with no Plum body, backed
518
611
  /// instead by a host-provided wasm import (see `libs/std/os.plum`'s
519
612
  /// `printLn`). `plum-checker` requires this to agree with `body` being
@@ -771,6 +864,9 @@ pub enum CasePattern {
771
864
  /// `true =>` / `false =>`
772
865
  Bool(bool),
773
866
  Name(String),
867
+ /// `Orb as o`: on a trait object, matches a value of type `ty` and binds it,
868
+ /// typed `ty`, as `name`.
869
+ As { ty: String, name: String },
774
870
  Wildcard,
775
871
  }
776
872
 
@@ -784,6 +880,7 @@ impl PartialEq for CasePattern {
784
880
  (P::Float(a), P::Float(b)) => a == b,
785
881
  (P::Bool(a), P::Bool(b)) => a == b,
786
882
  (P::Name(a), P::Name(b)) => a == b,
883
+ (P::As { ty: a, name: x }, P::As { ty: b, name: y }) => a == b && x == y,
787
884
  (P::Wildcard, P::Wildcard) => true,
788
885
  _ => false,
789
886
  }
compiler/core/src/binders.rs CHANGED
@@ -174,6 +174,7 @@ fn freshenCase(c: &mut Case, taken: &HashSet<String>) {
174
174
  fn renameBinder(p: &mut CasePattern, old: &str, new: &str) {
175
175
  match p {
176
176
  CasePattern::Name(n) if n == old => *n = new.to_string(),
177
+ CasePattern::As { name, .. } if name == old => *name = new.to_string(),
177
178
  CasePattern::Class { fields, .. } => fields.iter_mut().for_each(|f| renameBinder(f, old, new)),
178
179
  _ => {}
179
180
  }
compiler/core/src/blocks.rs CHANGED
@@ -130,6 +130,7 @@ impl Scoper<'_> {
130
130
  fn pattern(&mut self, p: &mut CasePattern) {
131
131
  match p {
132
132
  CasePattern::Name(n) if !isTag(n) => self.declare(n),
133
+ CasePattern::As { name, .. } => self.declare(name),
133
134
  CasePattern::Class { fields, .. } => fields.iter_mut().for_each(|f| self.pattern(f)),
134
135
  _ => {}
135
136
  }
@@ -331,6 +332,7 @@ pub fn prepareBlockValues(source: &mut Source) -> Vec<Diagnostic> {
331
332
  }
332
333
  }
333
334
  Item::Enum(_) => {}
335
+ Item::Trait(_) => {}
334
336
  }
335
337
  }
336
338
  errors
compiler/core/src/builtin_usage.rs CHANGED
@@ -76,6 +76,11 @@ fn walkSource(source: &Source, names: &mut Acc) -> HashSet<String> {
76
76
  Item::Fn(f) => walkFn(f, names),
77
77
  Item::Const(c) => walkExpr(&c.value, names),
78
78
  Item::Test(t) => walkStmts(&t.body.stmts, names),
79
+ Item::Trait(t) => {
80
+ for m in &t.methods {
81
+ walkFn(&m.sig, names);
82
+ }
83
+ }
79
84
  }
80
85
  }
81
86
  std::mem::take(&mut names.set)
@@ -192,6 +197,7 @@ fn walkCasePattern(pat: &CasePattern, names: &mut Acc) {
192
197
  names.insert("Str".to_string());
193
198
  }
194
199
  CasePattern::Name(_) | CasePattern::Bool(_) | CasePattern::Wildcard => {}
200
+ CasePattern::As { ty, .. } => names.insert(ty.clone()),
195
201
  }
196
202
  }
197
203
 
compiler/core/src/ctors.rs CHANGED
@@ -349,6 +349,7 @@ pub fn lowerCtors(source: &mut Source) -> Vec<String> {
349
349
  is_export: false,
350
350
  is_test: false,
351
351
  is_fip: false,
352
+ bounds: vec![],
352
353
  has_self: true,
353
354
  params: vec![],
354
355
  returns: None,
@@ -367,6 +368,7 @@ pub fn lowerCtors(source: &mut Source) -> Vec<String> {
367
368
  is_export: false,
368
369
  is_test: false,
369
370
  is_fip: false,
371
+ bounds: vec![],
370
372
  has_self: false,
371
373
  params: nparams
372
374
  .iter()
compiler/core/src/drive.rs CHANGED
@@ -1856,6 +1856,7 @@ impl Driver {
1856
1856
  is_export: false,
1857
1857
  is_test: false,
1858
1858
  is_fip: false,
1859
+ bounds: vec![],
1859
1860
  has_self: false,
1860
1861
  params,
1861
1862
  returns: cret.as_ref().map(|r| substType(r, &map)),
compiler/core/src/enum_checks.rs CHANGED
@@ -185,6 +185,12 @@ pub fn inlineVariantTypeErrors(source: &Source) -> Vec<String> {
185
185
  Item::Fn(f) => w.func(f),
186
186
  Item::Const(c) => w.expr(&c.value),
187
187
  Item::Test(t) => w.stmts(&t.body.stmts),
188
+ Item::Trait(t) => {
189
+ for m in &t.methods {
190
+ w.scope = crate::generics::Scope::in_(&typeGenerics, &m.sig);
191
+ w.func(&m.sig);
192
+ }
193
+ }
188
194
  }
189
195
  }
190
196
  w.errors
compiler/core/src/forms.rs CHANGED
@@ -248,7 +248,7 @@ pub fn prepareForms(source: &mut Source) {
248
248
  },
249
249
  Item::Test(t) => numberLoops(&mut t.body.stmts, &mut loops),
250
250
  Item::Const(c) => numberLoopsIn(&mut c.value, &mut loops),
251
- Item::Enum(_) => {}
251
+ Item::Enum(_) | Item::Trait(_) => {}
252
252
  }
253
253
  }
254
254
  source.formLoops |= loops;
@@ -408,6 +408,7 @@ pub fn finish(source: &Source) -> Source {
408
408
  applyExpr(&mut c.value, &at, &mut lifted)
409
409
  }
410
410
  Item::Enum(_) => {}
411
+ Item::Trait(_) => {}
411
412
  }
412
413
  }
413
414
  out.items.extend(lifted);
@@ -527,6 +528,7 @@ fn liftedFn(id: usize, at: &LiftSite, lift: &Lift, params: Vec<Param>, body: Vec
527
528
  is_export: false,
528
529
  is_test: false,
529
530
  is_fip: at.isFip,
531
+ bounds: vec![],
530
532
  has_self: false,
531
533
  params,
532
534
  returns: None,
@@ -771,7 +773,7 @@ fn renameStmts(stmts: &mut [Stmt], rn: &mut dyn FnMut(&mut String, bool)) {
771
773
 
772
774
  fn renamePattern(p: &mut CasePattern, rn: &mut dyn FnMut(&mut String, bool)) {
773
775
  match p {
774
- CasePattern::Name(n) => rn(n, true),
776
+ CasePattern::Name(n) | CasePattern::As { name: n, .. } => rn(n, true),
775
777
  CasePattern::Class { fields, .. } => fields.iter_mut().for_each(|f| renamePattern(f, rn)),
776
778
  _ => {}
777
779
  }
compiler/core/src/generics.rs CHANGED
@@ -88,8 +88,14 @@ pub fn fnGenerics(f: &Fn, owner: &[String]) -> Vec<String> {
88
88
  pub fn ownerGenerics(src: &Source) -> HashMap<String, Vec<String>> {
89
89
  let mut out = HashMap::new();
90
90
  for item in &src.items {
91
+ match item {
91
- if let Item::Enum(e) = item {
92
+ Item::Enum(e) => {
92
- out.insert(e.name.clone(), e.generics.iter().map(|g| g.name.clone()).collect());
93
+ out.insert(e.name.clone(), e.generics.iter().map(|g| g.name.clone()).collect());
94
+ }
95
+ Item::Trait(t) => {
96
+ out.insert(t.name.clone(), t.generics.iter().map(|g| g.name.clone()).collect());
97
+ }
98
+ _ => {}
93
99
  }
94
100
  }
95
101
  for p in &src.primitives {
compiler/core/src/loader.rs CHANGED
@@ -730,6 +730,7 @@ fn mergeItems(
730
730
  fn itemNameKey(item: &Item) -> String {
731
731
  match item {
732
732
  Item::Enum(e) => format!("enum::{}", e.name),
733
+ Item::Trait(t) => format!("enum::{}", t.name),
733
734
  Item::Const(c) => format!("const::{}", c.name),
734
735
  Item::Fn(f) => match &f.type_param {
735
736
  Some(recv) => format!("method::{}::{}", recv, f.name),
compiler/core/src/modules.rs CHANGED
@@ -630,7 +630,7 @@ fn rewriteFile(world: &World, file: usize, source: &mut Source, errors: &mut Vec
630
630
  cx.scopes = vec![HashSet::new()];
631
631
  cx.expr(&mut c.value);
632
632
  }
633
- Item::Enum(_) => {}
633
+ Item::Enum(_) | Item::Trait(_) => {}
634
634
  }
635
635
  }
636
636
  }
compiler/core/src/parser.rs CHANGED
@@ -141,6 +141,15 @@ impl<'a> AstParser<'a> {
141
141
  topLevelOrder.push(TopLevelKind::Other);
142
142
  }
143
143
  }
144
+ "trait" => {
145
+ let (t, defaults) = self.parseTrait(child);
146
+ items.push(Item::Trait(t));
147
+ topLevelOrder.push(TopLevelKind::Other);
148
+ for f in defaults {
149
+ items.push(Item::Fn(f));
150
+ topLevelOrder.push(TopLevelKind::Other);
151
+ }
152
+ }
144
153
  "primitive" => {
145
154
  let name = child
146
155
  .child_by_field_name("name")
@@ -279,10 +288,14 @@ impl<'a> AstParser<'a> {
279
288
  }
280
289
 
281
290
  fn parseGenericsField(&self, node: Node) -> Vec<GenericParam> {
282
- // generics: "[" generic,* "]"
283
291
  let Some(generics_node) = self.childrenOfKind(node, "generics").into_iter().next() else {
284
292
  return Vec::new();
285
293
  };
294
+ self.parseGenericParams(generics_node)
295
+ }
296
+
297
+ /// The parameters of a `generics` / `fn_generics` node: `[T, S: Reducer[M] + Show]`.
298
+ fn parseGenericParams(&self, generics_node: Node) -> Vec<GenericParam> {
286
299
  let mut cursor = generics_node.walk();
287
300
  let mut params: Vec<GenericParam> = Vec::new();
288
301
  for child in generics_node.named_children(&mut cursor) {
@@ -290,19 +303,65 @@ impl<'a> AstParser<'a> {
290
303
  "type_identifier" => {
291
304
  params.push(GenericParam {
292
305
  name: self.text(child),
306
+ bounds: Vec::new(),
293
307
  });
294
308
  }
309
+ "bounds" => {
310
+ if let Some(last) = params.last_mut() {
311
+ last.bounds = self
312
+ .childrenOfKind(child, "type")
313
+ .into_iter()
314
+ .map(|t| self.parseType(t))
315
+ .collect();
316
+ }
317
+ }
295
318
  _ => {}
296
319
  }
297
320
  }
298
321
  params
299
322
  }
300
323
 
324
+ /// The `is A, B[X]` clause of a struct or enum.
325
+ fn parseImplements(&self, node: Node) -> Vec<Type> {
326
+ match node.child_by_field_name("implements") {
327
+ Some(i) => self.childrenOfKind(i, "type").into_iter().map(|t| self.parseType(t)).collect(),
328
+ None => Vec::new(),
329
+ }
330
+ }
331
+
332
+ /// A `trait` declaration, and a method of the trait for each default body (`Self`
333
+ /// in its signature written as the trait object type).
334
+ fn parseTrait(&self, node: Node) -> (Trait, Vec<Fn>) {
335
+ let name = node
336
+ .child_by_field_name("name")
337
+ .map(|n| self.text(n))
338
+ .unwrap_or_default();
339
+ let generics = self.parseGenericsField(node);
340
+ let pos = node.start_position();
341
+ let mut t = Trait { name: name.clone(), file: String::new(), line: pos.row + 1, column: pos.column + 1, generics, methods: Vec::new() };
342
+ let selfTy = t.selfType();
343
+ let mut defaults = Vec::new();
344
+ for n in self.childrenOfKind(node, "fn") {
345
+ let mut f = self.parseFn(n);
346
+ f.type_param = Some(name.clone());
347
+ let hasDefault = !matches!(f.body, FnBody::Extern);
348
+ if hasDefault {
349
+ let mut d = f.clone();
350
+ d.replaceSelf(&selfTy);
351
+ defaults.push(d);
352
+ }
353
+ f.body = FnBody::Extern;
354
+ t.methods.push(TraitMethod { sig: f, hasDefault });
355
+ }
356
+ (t, defaults)
357
+ }
358
+
301
359
  fn parseEnum(&self, node: Node) -> Enum {
302
360
  // enum: "enum" type_identifier generics? "=" body
303
361
  let named: Vec<Node> = self.namedChildren(node);
304
362
  let name = named.first().map(|n| self.text(*n)).unwrap_or_default();
305
363
  let generics = self.parseGenericsField(node);
364
+ let implements = self.parseImplements(node);
306
365
  let mut cursor = node.walk();
307
366
  let variants = node
308
367
  .named_children(&mut cursor)
@@ -317,6 +376,7 @@ impl<'a> AstParser<'a> {
317
376
  column: pos.column + 1,
318
377
  generics,
319
378
  variants,
379
+ implements,
320
380
  }
321
381
  }
322
382
 
@@ -346,6 +406,7 @@ impl<'a> AstParser<'a> {
346
406
  .map(|n| self.text(n))
347
407
  .unwrap_or_default();
348
408
  let generics = self.parseGenericsField(node);
409
+ let implements = self.parseImplements(node);
349
410
  // The enum_named_field children, in order, are the constructor's fields.
350
411
  let variant = self.parseEnumVariant(node);
351
412
  let pos = node.start_position();
@@ -356,6 +417,7 @@ impl<'a> AstParser<'a> {
356
417
  column: pos.column + 1,
357
418
  generics,
358
419
  variants: vec![variant],
420
+ implements,
359
421
  }
360
422
  }
361
423
 
@@ -482,21 +544,23 @@ impl<'a> AstParser<'a> {
482
544
  let is_export = node.child_by_field_name("exportKw").is_some();
483
545
  let is_fip = node.child_by_field_name("fipKw").is_some();
484
546
 
485
- let generics: Vec<String> = node
547
+ let params_ = node
486
548
  .child_by_field_name("generics")
487
- .map(|g| {
488
- self.namedChildren(g)
489
- .into_iter()
490
- .map(|n| self.text(n))
549
+ .map(|g| self.parseGenericParams(g))
491
- .collect()
492
- })
493
550
  .unwrap_or_default();
551
+ let generics: Vec<String> = params_.iter().map(|g| g.name.clone()).collect();
552
+ let bounds: Vec<(String, Vec<Type>)> = params_
553
+ .into_iter()
554
+ .filter(|g| !g.bounds.is_empty())
555
+ .map(|g| (g.name, g.bounds))
556
+ .collect();
494
557
 
495
558
  let pos = node.start_position();
496
559
  Fn {
497
560
  file: String::new(),
498
561
  name,
499
562
  generics,
563
+ bounds,
500
564
  line: pos.row + 1,
501
565
  column: pos.column + 1,
502
566
  type_param: None,
@@ -1019,6 +1083,10 @@ impl<'a> AstParser<'a> {
1019
1083
  .collect();
1020
1084
  CasePattern::class(name, fields)
1021
1085
  }
1086
+ "as_pattern" => CasePattern::As {
1087
+ ty: inner.child_by_field_name("type").map(|n| self.text(n)).unwrap_or_default(),
1088
+ name: inner.child_by_field_name("name").map(|n| self.text(n)).unwrap_or_default(),
1089
+ },
1022
1090
  "string" => CasePattern::String(self.parseStringRaw(inner)),
1023
1091
  "integer" => CasePattern::Int(self.parseInteger(inner)),
1024
1092
  "float" => CasePattern::Float(self.parseFloat(inner)),
compiler/core/src/question.rs CHANGED
@@ -505,6 +505,7 @@ pub fn lowerQuestions(source: &mut Source) -> Vec<Diagnostic> {
505
505
  }
506
506
  }
507
507
  Item::Enum(_) => {}
508
+ Item::Trait(_) => {}
508
509
  }
509
510
  }
510
511
  errors
compiler/core/src/rename.rs CHANGED
@@ -55,7 +55,7 @@ pub fn renameStmts(stmts: &mut [Stmt], rn: &mut dyn FnMut(&mut String, Name)) {
55
55
 
56
56
  fn renamePattern(p: &mut CasePattern, rn: &mut dyn FnMut(&mut String, Name)) {
57
57
  match p {
58
- CasePattern::Name(n) => rn(n, Name::Pat),
58
+ CasePattern::Name(n) | CasePattern::As { name: n, .. } => rn(n, Name::Pat),
59
59
  CasePattern::Class { fields, .. } => fields.iter_mut().for_each(|f| renamePattern(f, rn)),
60
60
  _ => {}
61
61
  }
compiler/core/src/spread_paths.rs CHANGED
@@ -231,7 +231,7 @@ pub fn lowerSpreadPaths(source: &mut Source) -> Vec<Diagnostic> {
231
231
  },
232
232
  Item::Test(t) => visitBlock(&mut t.body, &mut visit),
233
233
  Item::Const(c) => visitExpr(&mut c.value, &mut visit),
234
- Item::Enum(_) => {}
234
+ Item::Enum(_) | Item::Trait(_) => {}
235
235
  }
236
236
  raw.extend(errs.into_iter().map(|(s, m)| (name.clone(), s, m)));
237
237
  }
compiler/core/src/tail.rs CHANGED
@@ -129,7 +129,7 @@ fn case(cx: &mut Ctx, c: &mut Case, tail: bool, ret: bool) {
129
129
 
130
130
  fn pattern(cx: &mut Ctx, p: &CasePattern) {
131
131
  match p {
132
- CasePattern::Name(n) => {
132
+ CasePattern::Name(n) | CasePattern::As { name: n, .. } => {
133
133
  cx.locals.insert(n.clone());
134
134
  }
135
135
  CasePattern::Class { fields, .. } => fields.iter().for_each(|f| pattern(cx, f)),
compiler/core/src/tests_lower.rs CHANGED
@@ -41,6 +41,7 @@ fn reportStruct() -> crate::ast::Item {
41
41
  line: 0,
42
42
  column: 0,
43
43
  generics: vec![],
44
+ implements: vec![],
44
45
  variants: vec![crate::ast::EnumVariant {
45
46
  name: REPORT_TYPE.to_string(),
46
47
  fields: vec![crate::ast::Type { name: crate::ast::STR_TYPE.to_string(), generics: vec![] }],
@@ -147,6 +148,7 @@ fn desugarTestsToFns(source: &crate::ast::Source) -> (crate::ast::Source, Vec<(S
147
148
  is_export: false,
148
149
  is_test: true,
149
150
  is_fip: false,
151
+ bounds: vec![],
150
152
  has_self: true,
151
153
  params: ioParam.clone(),
152
154
  returns: Some(crate::ast::Type {
compiler/core/src/uniqueness.rs CHANGED
@@ -1571,6 +1571,7 @@ fn build(src: &Source) -> An {
1571
1571
  params: vec![],
1572
1572
  block: Block { stmts: vec![Stmt::Expr(c.value.clone(), 0, 0)] },
1573
1573
  }),
1574
+ Item::Trait(_) => {}
1574
1575
  }
1575
1576
  }
1576
1577
  // A parameter's default runs in the fn, before its body: `fun f(h: H = H(p: Base))` stores `Base`,
compiler/core/src/visit.rs CHANGED
@@ -282,6 +282,7 @@ pub fn patternBinders(p: &CasePattern, out: &mut Vec<String>) {
282
282
  out.push(n.clone());
283
283
  }
284
284
  }
285
+ CasePattern::As { name, .. } => out.push(name.clone()),
285
286
  CasePattern::Class { fields, .. } => fields.iter().for_each(|f| patternBinders(f, out)),
286
287
  _ => {}
287
288
  }
compiler/core/tests/core/main.rs CHANGED
@@ -24,6 +24,7 @@ mod session_test;
24
24
  mod simplify_test;
25
25
  mod tail_test;
26
26
  mod tests_lower_test;
27
+ mod traits_parse_test;
27
28
  mod trmc_test;
28
29
  mod enum_checks_test;
29
30
  mod uniqueness_moves_test;
compiler/core/tests/core/parser_test.rs CHANGED
@@ -161,8 +161,9 @@ fn record_keyword_is_a_parse_error() {
161
161
  }
162
162
 
163
163
  #[test]
164
- fn bound_syntax_rejected() {
164
+ fn bound_syntax_accepted() {
165
+ // trait bounds (`[T: Show]`) are back with traits
165
- assert!(hasParseError("fun f[T: Show](x: T) -> T =\n x\n"));
166
+ assert!(!hasParseError("fun f[T: Show](x: T) -> T =\n x\n"));
166
167
  }
167
168
 
168
169
  // ---- errors: `!T`, `T?`, postfix `?`, `crash` ----
compiler/core/tests/core/traits_parse_test.rs ADDED
@@ -0,0 +1,165 @@
1
+ #![allow(non_snake_case)]
2
+ //! Parsing traits, `is` clauses, bounds and the downcast pattern.
3
+ use plum_core::ast::*;
4
+
5
+ fn ty(name: &str, generics: Vec<Type>) -> Type {
6
+ Type { name: name.to_string(), generics }
7
+ }
8
+
9
+ fn named(name: &str) -> Type {
10
+ ty(name, vec![])
11
+ }
12
+
13
+ fn traitOf<'a>(s: &'a Source, name: &str) -> &'a Trait {
14
+ s.items
15
+ .iter()
16
+ .find_map(|i| match i {
17
+ Item::Trait(t) if t.name == name => Some(t),
18
+ _ => None,
19
+ })
20
+ .expect("trait")
21
+ }
22
+
23
+ fn fnOf<'a>(s: &'a Source, recv: Option<&str>, name: &str) -> &'a Fn {
24
+ s.items
25
+ .iter()
26
+ .find_map(|i| match i {
27
+ Item::Fn(f) if f.type_param.as_deref() == recv && f.name == name => Some(f),
28
+ _ => None,
29
+ })
30
+ .expect("fn")
31
+ }
32
+
33
+ fn enumOf<'a>(s: &'a Source, name: &str) -> &'a Enum {
34
+ s.items
35
+ .iter()
36
+ .find_map(|i| match i {
37
+ Item::Enum(e) if e.name == name => Some(e),
38
+ _ => None,
39
+ })
40
+ .expect("enum")
41
+ }
42
+
43
+ #[test]
44
+ fn traitWithRequiredAndDefaultMethods() {
45
+ let s = plum_test_support::parseRawSource(
46
+ "trait Actor =
47
+ # required
48
+ fun key(self) -> Int
49
+ fun step(self, dt: Float) -> Self = self
50
+ fun paint(self, n: Int) = Unit
51
+ ",
52
+ );
53
+ let t = traitOf(&s, "Actor");
54
+ assert!(t.generics.is_empty());
55
+ let names: Vec<(&str, bool)> = t.methods.iter().map(|m| (m.sig.name.as_str(), m.hasDefault)).collect();
56
+ assert_eq!(names, vec![("key", false), ("step", true), ("paint", true)]);
57
+ // the trait keeps its signatures as written, with `Self`, and no bodies
58
+ let step = &t.method("step").unwrap().sig;
59
+ assert_eq!(step.returns, Some(named("Self")));
60
+ assert!(step.has_self);
61
+ assert!(matches!(step.body, FnBody::Extern));
62
+ // a default is also a method of the trait, `Self` written as the trait object
63
+ let d = fnOf(&s, Some("Actor"), "step");
64
+ assert_eq!(d.returns, Some(named("Actor")));
65
+ assert!(matches!(d.body, FnBody::Expr(_)));
66
+ assert!(s.items.iter().all(|i| !matches!(i, Item::Fn(f) if f.type_param.as_deref() == Some("Actor") && f.name == "key")));
67
+ }
68
+
69
+ #[test]
70
+ fn traitWithTypeParameters() {
71
+ let s = plum_test_support::parseRawSource(
72
+ "trait Reducer[M] =
73
+ fun update(self, msg: M) -> Self
74
+ fun handle(self, msg: M) -> Int = 1
75
+ ",
76
+ );
77
+ let t = traitOf(&s, "Reducer");
78
+ assert_eq!(t.generics.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(), vec!["M"]);
79
+ assert_eq!(t.selfType(), ty("Reducer", vec![named("M")]));
80
+ let d = fnOf(&s, Some("Reducer"), "handle");
81
+ assert_eq!(d.params[0].ty, ParamType::Type(named("M")));
82
+ }
83
+
84
+ #[test]
85
+ fn isClauseOnStructsAndEnums() {
86
+ let s = plum_test_support::parseRawSource(
87
+ "struct Orb(id: Int) is Actor, Reducer[Msg] =
88
+ fun key(self) -> Int = self.id
89
+
90
+ struct Mark is Actor
91
+
92
+ enum Shape is Show =
93
+ | Circle(r: Float)
94
+ | Sq
95
+
96
+ enum Dir is Show = Up | Down
97
+ ",
98
+ );
99
+ assert_eq!(enumOf(&s, "Orb").implements, vec![named("Actor"), ty("Reducer", vec![named("Msg")])]);
100
+ assert_eq!(enumOf(&s, "Mark").implements, vec![named("Actor")]);
101
+ assert_eq!(enumOf(&s, "Shape").implements, vec![named("Show")]);
102
+ assert_eq!(enumOf(&s, "Dir").implements, vec![named("Show")]);
103
+ assert_eq!(enumOf(&s, "Dir").variants.len(), 2);
104
+ }
105
+
106
+ #[test]
107
+ fn boundsOnGenerics() {
108
+ let s = plum_test_support::parseRawSource(
109
+ "struct Store[S: Reducer[M], M](state: S, m: M)
110
+
111
+ fun replay[S: Reducer[M] + Show, M, T](s: S, msgs: M, t: T) -> S = s
112
+ ",
113
+ );
114
+ let st = enumOf(&s, "Store");
115
+ assert_eq!(st.generics[0].name, "S");
116
+ assert_eq!(st.generics[0].bounds, vec![ty("Reducer", vec![named("M")])]);
117
+ assert!(st.generics[1].bounds.is_empty());
118
+ let f = fnOf(&s, None, "replay");
119
+ assert_eq!(f.generics, vec!["S", "M", "T"]);
120
+ assert_eq!(f.bounds, vec![("S".to_string(), vec![ty("Reducer", vec![named("M")]), named("Show")])]);
121
+ assert_eq!(f.returns, Some(named("S")));
122
+ }
123
+
124
+ #[test]
125
+ fn downcastPattern() {
126
+ let s = plum_test_support::parseRawSource(
127
+ "fun f(a: Actor) -> Int =
128
+ match a
129
+ Orb as o => o.id
130
+ Some(Label as l) => 1
131
+ _ => 0
132
+ ",
133
+ );
134
+ let f = fnOf(&s, None, "f");
135
+ let FnBody::Block(b) = &f.body else { panic!("block") };
136
+ let StmtKind::Match(m) = &b.stmts[0].kind else { panic!("match") };
137
+ assert_eq!(m.cases[0].patterns[0], CasePattern::As { ty: "Orb".to_string(), name: "o".to_string() });
138
+ assert_eq!(
139
+ m.cases[1].patterns[0],
140
+ CasePattern::class("Some".to_string(), vec![CasePattern::As { ty: "Label".to_string(), name: "l".to_string() }])
141
+ );
142
+ }
143
+
144
+ #[test]
145
+ fn downcastBinderThatShadowsALocalIsRenamed() {
146
+ let s = plum_test_support::parse(
147
+ "fun f(a: Actor) -> Int =
148
+ o := 5
149
+ k := match a
150
+ Orb as o => o.id
151
+ _ => 0
152
+ k + o
153
+ ",
154
+ );
155
+ let f = fnOf(&s, None, "f");
156
+ let FnBody::Block(b) = &f.body else { panic!("block") };
157
+ let text = format!("{:?}", b.stmts[1]);
158
+ let binder = text.split("As { ty: \"Orb\", name: \"").nth(1).and_then(|r| r.split('"').next()).expect("downcast binder");
159
+ assert_ne!(binder, "o", "the arm's binder shadows the outer `o`: {text}");
160
+ assert!(binder.starts_with("o'"), "{binder}");
161
+ // the arm's body reads the renamed binder
162
+ assert!(text.contains(&format!("Var(\"{binder}\")")), "{text}");
163
+ // the outer `o` is untouched
164
+ assert!(format!("{:?}", b.stmts[2]).contains("Var(\"o\")"));
165
+ }
compiler/driver/src/lib.rs CHANGED
@@ -146,7 +146,10 @@ 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(_)));
149
- if st.result.is_ok() {
152
+ if st.result.is_ok() && !hasTraits {
150
153
  if opts.explain && !(opts.fusion && opts.fbip) && !plum_core::fip::origins(&st.pre).isEmpty() {
151
154
  eprintln!("fusion: fip fun is not enforced: it needs the uniqueness proof, which --no-fusion and --no-fbip switch off");
152
155
  }
compiler/lsp/src/completion.rs CHANGED
@@ -30,6 +30,9 @@ const KEYWORDS: &[&str] = &[
30
30
  "crash",
31
31
  "struct",
32
32
  "enum",
33
+ "trait",
34
+ "is",
35
+ "as",
33
36
  "primitive",
34
37
  "import",
35
38
  "module",
@@ -79,6 +82,14 @@ pub fn topLevelItems(source: &ast::Source) -> Vec<CompletionItem> {
79
82
  });
80
83
  }
81
84
  ast::Item::Fn(_) => {}
85
+ ast::Item::Trait(t) => {
86
+ items.push(CompletionItem {
87
+ label: t.name.clone(),
88
+ kind: Some(CompletionItemKind::INTERFACE),
89
+ detail: Some("trait".to_string()),
90
+ ..Default::default()
91
+ });
92
+ }
82
93
  ast::Item::Enum(e) => {
83
94
  items.push(CompletionItem {
84
95
  label: e.name.clone(),
@@ -671,6 +682,7 @@ mod tests {
671
682
  is_export: false,
672
683
  is_test: false,
673
684
  is_fip: false,
685
+ bounds: vec![],
674
686
  has_self: false,
675
687
  params: vec![],
676
688
  returns: None,
compiler/lsp/src/main.rs CHANGED
@@ -724,6 +724,7 @@ mod tests {
724
724
  for want in [
725
725
  "primitive",
726
726
  "struct",
727
+ "trait",
727
728
  "range",
728
729
  "then",
729
730
  "true",
@@ -741,7 +742,6 @@ mod tests {
741
742
  "block",
742
743
  "indexed",
743
744
  "case",
744
- "trait",
745
745
  "override",
746
746
  "abstract",
747
747
  "implements",
compiler/tooling/tree-sitter-plum/grammar.js CHANGED
@@ -78,7 +78,7 @@ module.exports = grammar({
78
78
  seq(
79
79
  optional($.module),
80
80
  repeat($.import),
81
- repeat(choice($.enum, $.struct, $.primitive, $.fn, $.const, $.test)),
81
+ repeat(choice($.enum, $.struct, $.trait, $.primitive, $.fn, $.const, $.test)),
82
82
  ),
83
83
 
84
84
  module: ($) => seq("module", $.mod_identifier),
@@ -92,8 +92,26 @@ module.exports = grammar({
92
92
  url: ($) => sep1($.url_segment, "/"),
93
93
  url_segment: (_) => /[a-zA-Z_][a-zA-Z_0-9]*/,
94
94
 
95
+ // `[T]`, `[T: Show]`, `[S: Reducer[M], M]`, `[T: A + B]`: a parameter may be bounded by traits.
95
- generics: ($) => seq("[", commaSep1($.type_identifier), "]"),
96
+ generics: ($) => seq("[", commaSep1(seq($.type_identifier, optional($.bounds))), "]"),
96
- fn_generics: ($) => seq("[", commaSep1($.type_identifier), "]"),
97
+ fn_generics: ($) => seq("[", commaSep1(seq($.type_identifier, optional($.bounds))), "]"),
98
+ bounds: ($) => seq(":", sep1($.type, "+")),
99
+
100
+ // `is Actor` / `is A, B[X]` on a struct or enum: the traits it implements.
101
+ implements: ($) => seq("is", commaSep1($.type)),
102
+
103
+ // `trait Actor =` + method signatures: a method with no body is required, one with a
104
+ // body is optional and the body is its default.
105
+ trait: ($) =>
106
+ seq(
107
+ "trait",
108
+ field("name", $.type_identifier),
109
+ field("generics", optional($.generics)),
110
+ "=",
111
+ $._indent,
112
+ field("methods", repeat($.fn)),
113
+ $._dedent,
114
+ ),
97
115
  type: ($) =>
98
116
  choice(
99
117
  $._plain_type,
@@ -135,6 +153,7 @@ module.exports = grammar({
135
153
  "enum",
136
154
  field("name", $.type_identifier),
137
155
  field("generics", optional($.generics)),
156
+ optional(field("implements", $.implements)),
138
157
  "=",
139
158
  choice(
140
159
  seq(
@@ -414,6 +433,7 @@ module.exports = grammar({
414
433
  1,
415
434
  choice(
416
435
  $.class_pattern,
436
+ $.as_pattern,
417
437
  $.type_identifier,
418
438
  $.string,
419
439
  $.integer,
@@ -457,6 +477,10 @@ module.exports = grammar({
457
477
  field("body", choice($.expression, $.body)),
458
478
  ),
459
479
 
480
+ // `Orb as o`: on a trait object, matches a value of type `Orb` and binds it as one.
481
+ as_pattern: ($) =>
482
+ seq(field("type", $.type_identifier), "as", field("name", $.var_identifier)),
483
+
460
484
  class_pattern: ($) =>
461
485
  seq(
462
486
  $.type_identifier,
@@ -809,6 +833,7 @@ function productBody($, keyword) {
809
833
  field("name", $.type_identifier),
810
834
  field("generics", optional($.generics)),
811
835
  optional(seq("(", optional($._ctor_fields), ")")),
836
+ optional(field("implements", $.implements)),
812
837
  optional(seq("=", $._indent, field("methods", repeat(choice($.fn, $.const))), $._dedent)),
813
838
  );
814
839
  }
compiler/tooling/tree-sitter-plum/queries/plum/format.scm CHANGED
@@ -24,6 +24,9 @@
24
24
  (source
25
25
  (primitive) @allow_blank_line_before)
26
26
 
27
+ (source
28
+ (trait) @allow_blank_line_before)
29
+
27
30
  (source
28
31
  (import) @allow_blank_line_before)
29
32
 
@@ -111,6 +114,36 @@
111
114
 
112
115
  (primitive "primitive" @append_space)
113
116
 
117
+ ; `trait Name =` + method signatures, indented like a `primitive` body.
118
+ (trait "trait" @append_space)
119
+
120
+ (trait
121
+ (fn) @prepend_hardline)
122
+
123
+ (trait
124
+ (fn) @allow_blank_line_before)
125
+
126
+ (trait
127
+ (comment) @allow_blank_line_before)
128
+
129
+ (trait
130
+ "=" @append_indent_start)
131
+
132
+ (trait
133
+ (_) @append_indent_end
134
+ .)
135
+
136
+ ; `is A, B[X]`, `[T: A + B]`, `Orb as o`.
137
+ (implements "is" @prepend_space @append_space)
138
+
139
+ (implements "," @append_space)
140
+
141
+ (bounds ":" @append_space)
142
+
143
+ (bounds "+" @prepend_space @append_space)
144
+
145
+ (as_pattern "as" @prepend_space @append_space)
146
+
114
147
  (primitive
115
148
  (fn) @prepend_hardline)
116
149
 
compiler/tooling/tree-sitter-plum/queries/plum/highlights.scm CHANGED
@@ -96,6 +96,9 @@
96
96
  "enum"
97
97
  "primitive"
98
98
  "struct"
99
+ "trait"
100
+ "is"
101
+ "as"
99
102
  "fun"
100
103
  "extern"
101
104
  "export"
compiler/tooling/tree-sitter-plum/queries/plum/indents.scm CHANGED
@@ -1,6 +1,7 @@
1
1
  [
2
2
  (enum)
3
3
  (struct)
4
+ (trait)
4
5
  (primitive)
5
6
  (fn)
6
7
  (for)
@@ -20,6 +21,7 @@
20
21
  (fn)
21
22
  (enum)
22
23
  (struct)
24
+ (trait)
23
25
  (primitive)
24
26
  (match)
25
27
  ] @extend
compiler/tooling/tree-sitter-plum/src/grammar.json CHANGED
Binary file
compiler/tooling/tree-sitter-plum/src/node-types.json CHANGED
Binary file
compiler/tooling/tree-sitter-plum/src/parser.c CHANGED
Binary file
compiler/tooling/tree-sitter-plum/test/corpus/traits.txt ADDED
@@ -0,0 +1,191 @@
1
+ ==================
2
+ trait with required and default methods
3
+ ==================
4
+
5
+ trait Actor =
6
+ fun key(self) -> Int
7
+ fun step(self, dt: Float) -> Self = self
8
+
9
+ ---
10
+
11
+ (source
12
+ (trait
13
+ (type_identifier)
14
+ (fn
15
+ (fn_identifier)
16
+ (self)
17
+ (type
18
+ (type_identifier)))
19
+ (fn
20
+ (fn_identifier)
21
+ (self)
22
+ (param
23
+ (var_identifier)
24
+ (type
25
+ (type_identifier)))
26
+ (type
27
+ (type_identifier))
28
+ (expression
29
+ (primary_expression
30
+ (self))))))
31
+
32
+ ==================
33
+ trait with type parameters
34
+ ==================
35
+
36
+ trait Reducer[M] =
37
+ fun update(self, msg: M) -> Self
38
+
39
+ ---
40
+
41
+ (source
42
+ (trait
43
+ (type_identifier)
44
+ (generics
45
+ (type_identifier))
46
+ (fn
47
+ (fn_identifier)
48
+ (self)
49
+ (param
50
+ (var_identifier)
51
+ (type
52
+ (type_identifier)))
53
+ (type
54
+ (type_identifier)))))
55
+
56
+ ==================
57
+ is clause on a struct and an enum
58
+ ==================
59
+
60
+ struct Orb(id: Int) is Actor, Reducer[Msg] =
61
+ fun key(self) -> Int = self.id
62
+
63
+ enum Dir is Show = Up | Down
64
+
65
+ ---
66
+
67
+ (source
68
+ (struct
69
+ (type_identifier)
70
+ (enum_named_field
71
+ (var_identifier)
72
+ (type
73
+ (type_identifier)))
74
+ (implements
75
+ (type
76
+ (type_identifier))
77
+ (type
78
+ (type_identifier)
79
+ (type
80
+ (type_identifier))))
81
+ (fn
82
+ (fn_identifier)
83
+ (self)
84
+ (type
85
+ (type_identifier))
86
+ (expression
87
+ (primary_expression
88
+ (attribute
89
+ (primary_expression
90
+ (self))
91
+ (fn_identifier))))))
92
+ (enum
93
+ (type_identifier)
94
+ (implements
95
+ (type
96
+ (type_identifier)))
97
+ (enum_member
98
+ (type_identifier))
99
+ (enum_member
100
+ (type_identifier))))
101
+
102
+ ==================
103
+ bounds on generics
104
+ ==================
105
+
106
+ struct Store[S: Reducer[M], M](state: S)
107
+
108
+ fun tag[T: Actor + Named](x: T) -> Str = x.name()
109
+
110
+ ---
111
+
112
+ (source
113
+ (struct
114
+ (type_identifier)
115
+ (generics
116
+ (type_identifier)
117
+ (bounds
118
+ (type
119
+ (type_identifier)
120
+ (type
121
+ (type_identifier))))
122
+ (type_identifier))
123
+ (enum_named_field
124
+ (var_identifier)
125
+ (type
126
+ (type_identifier))))
127
+ (fn
128
+ (fn_identifier)
129
+ (fn_generics
130
+ (type_identifier)
131
+ (bounds
132
+ (type
133
+ (type_identifier))
134
+ (type
135
+ (type_identifier))))
136
+ (param
137
+ (var_identifier)
138
+ (type
139
+ (type_identifier)))
140
+ (type
141
+ (type_identifier))
142
+ (expression
143
+ (primary_expression
144
+ (attribute
145
+ (primary_expression
146
+ (var_identifier))
147
+ (fn_identifier)
148
+ (fn_argument_list))))))
149
+
150
+ ==================
151
+ downcast pattern
152
+ ==================
153
+
154
+ fun f(a: Actor) -> Int =
155
+ match a
156
+ Orb as o => o.id
157
+ _ => 0
158
+
159
+ ---
160
+
161
+ (source
162
+ (fn
163
+ (fn_identifier)
164
+ (param
165
+ (var_identifier)
166
+ (type
167
+ (type_identifier)))
168
+ (type
169
+ (type_identifier))
170
+ (body
171
+ (expression
172
+ (match
173
+ (expression
174
+ (primary_expression
175
+ (var_identifier)))
176
+ (case
177
+ (case_pattern
178
+ (as_pattern
179
+ (type_identifier)
180
+ (var_identifier)))
181
+ (expression
182
+ (primary_expression
183
+ (attribute
184
+ (primary_expression
185
+ (var_identifier))
186
+ (fn_identifier)))))
187
+ (case
188
+ (case_pattern)
189
+ (expression
190
+ (primary_expression
191
+ (integer)))))))))
compiler/tooling/vscode-plum/syntaxes/plum.tmLanguage.json CHANGED
@@ -44,7 +44,7 @@
44
44
  },
45
45
  {
46
46
  "name": "keyword.control.plum",
47
- "match": "\\b(import|return|continue|break|match|when|if|then|else|while|for|range|assert|todo|crash)\\b"
47
+ "match": "\\b(import|return|continue|break|match|when|if|then|else|while|for|range|assert|todo|crash|is|as)\\b"
48
48
  },
49
49
  {
50
50
  "name": "keyword.operator.range.plum",
compiler/wasm-codegen/src/emit.rs CHANGED
@@ -63,6 +63,7 @@ impl<'a> Emit<'a> {
63
63
  is_export: false,
64
64
  is_test: false,
65
65
  is_fip: false,
66
+ bounds: vec![],
66
67
  has_self: true,
67
68
  params: Vec::new(),
68
69
  returns: None,
compiler/wasm-codegen/src/lib.rs CHANGED
@@ -105,17 +105,37 @@ pub fn compile(source: &ast::Source, opts: &CompileOptions) -> Result<Output, Ve
105
105
  if opts.tests {
106
106
  let prog = plum_core::tests_lower::lowerTests(source);
107
107
  let typed = plum_driver::check(&prog.source, &opts.passes)?;
108
+ noTraits(&prog.source)?;
108
109
  let mut extra = prog.extraExports.clone();
109
110
  extra.extend(gameExports(game));
110
111
  let (wasm, fn_keys) = compileSourceInner(&prog.source, &extra, typed).map_err(codegenDiag)?;
111
112
  Ok(Output { wasm, fn_keys, test_names: prog.names, isGame: game })
112
113
  } else {
113
114
  let typed = plum_driver::check(source, &opts.passes)?;
115
+ noTraits(source)?;
114
116
  let (wasm, fn_keys) = compileSourceInner(source, &gameExports(game), typed).map_err(codegenDiag)?;
115
117
  Ok(Output { wasm, fn_keys, test_names: Vec::new(), isGame: game })
116
118
  }
117
119
  }
118
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
+
119
139
  /// `layout <Name>: flat|boxed` for every struct, as decided by `plum_core::layout`.
120
140
  pub fn explainLayouts(source: &ast::Source) -> Vec<String> {
121
141
  source
compiler/wasm-codegen/src/matching.rs CHANGED
@@ -341,6 +341,9 @@ 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, .. } => {
345
+ return Err(format!("`{ty} as ..`: traits not yet supported in codegen"));
346
+ }
344
347
  ast::CasePattern::Wildcard => {
345
348
  // Always matches this position; move on to the next one.
346
349
  compileCasePositions(
@@ -740,6 +743,7 @@ pub(crate) fn compileFieldPatterns(
740
743
  let inst_vt = plumTypeToValtype(field_ty);
741
744
 
742
745
  match pat {
746
+ ast::CasePattern::As { ty, .. } => Err(format!("`{ty} as ..`: traits not yet supported in codegen")),
743
747
  ast::CasePattern::Wildcard => compileFieldPatterns(
744
748
  fields,
745
749
  field_types,