plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
38c6ade
— Peter John
2026-11-09T14:17:45+05:30
Traits: explicit type arguments, defaults and nested Self through dispatch, generic downcasts
- compiler/checker/src/callcheck.rs +60 -1
- compiler/checker/src/callsites.rs +5 -1
- compiler/checker/src/infer.rs +9 -2
- compiler/checker/src/patterns.rs +18 -6
- compiler/checker/src/program.rs +30 -2
- compiler/checker/src/state.rs +3 -0
- compiler/checker/src/traits.rs +74 -0
- compiler/checker/src/unification.rs +9 -0
- compiler/checker/tests/checker/traits_tests.rs +88 -1
- compiler/core/src/ast.rs +14 -1
- compiler/core/src/ctors.rs +2 -0
- compiler/core/src/drive.rs +5 -0
- compiler/core/src/forms.rs +3 -1
- compiler/core/src/loader.rs +27 -1
- compiler/core/src/parser.rs +16 -3
- compiler/core/src/trait_defaults.rs +81 -0
- compiler/core/src/uniqueness.rs +68 -2
- compiler/core/tests/core/loader_test.rs +15 -0
- compiler/tooling/tree-sitter-plum/grammar.js +18 -3
- compiler/tooling/tree-sitter-plum/src/grammar.json +0 -0
- compiler/tooling/tree-sitter-plum/src/node-types.json +0 -0
- compiler/tooling/tree-sitter-plum/src/parser.c +0 -0
- compiler/tooling/tree-sitter-plum/test/corpus/traits.txt +49 -0
- compiler/wasm-codegen/src/construct.rs +1 -0
- compiler/wasm-codegen/src/expr.rs +1 -0
- compiler/wasm-codegen/src/fnbody.rs +4 -2
- compiler/wasm-codegen/src/matching.rs +5 -0
- compiler/wasm-codegen/src/stmts.rs +2 -0
- compiler/wasm-codegen/src/traits.rs +30 -8
- compiler/wasm-codegen/tests/wasm_codegen/fusion_alloc_test.rs +41 -0
- tests/traits/limits.plum +73 -0
- tests/traits/type_args.plum +66 -0
compiler/checker/src/callcheck.rs
CHANGED
|
@@ -254,6 +254,50 @@ pub(crate) fn checkCallArgs(
|
|
|
254
254
|
Ok(())
|
|
255
255
|
}
|
|
256
256
|
|
|
257
|
+
/// Binds a call's explicit type arguments (`findAs[Orb](..)`): the `i`th one is the
|
|
258
|
+
/// callee's `i`th declared generic, whose variable at this call is in `call_map`.
|
|
259
|
+
pub(crate) fn applyTypeArgs(
|
|
260
|
+
label: &str,
|
|
261
|
+
owner: Option<&str>,
|
|
262
|
+
name: &str,
|
|
263
|
+
type_args: &[ast::Type],
|
|
264
|
+
call_map: &mut BTreeMap<String, PlumType>,
|
|
265
|
+
binds: &mut Binds,
|
|
266
|
+
ctx: &CheckCtx,
|
|
267
|
+
) -> Result<(), String> {
|
|
268
|
+
if type_args.is_empty() {
|
|
269
|
+
return Ok(());
|
|
270
|
+
}
|
|
271
|
+
let declared = withCheck(|s| {
|
|
272
|
+
s.fn_generics.borrow().get(&(owner.map(str::to_string), name.to_string())).cloned()
|
|
273
|
+
});
|
|
274
|
+
let declared = declared.unwrap_or_default();
|
|
275
|
+
if declared.len() != type_args.len() {
|
|
276
|
+
return Err(format!(
|
|
277
|
+
"{label}: takes {} type argument(s), got {}",
|
|
278
|
+
declared.len(),
|
|
279
|
+
type_args.len()
|
|
280
|
+
));
|
|
281
|
+
}
|
|
282
|
+
for (g, t) in declared.iter().zip(type_args) {
|
|
283
|
+
let given = crate::typeconv::plumTypeFromAstG(t);
|
|
284
|
+
match call_map.get(g) {
|
|
285
|
+
Some(var) => {
|
|
286
|
+
let var = substVars(var, binds);
|
|
287
|
+
bindMatch(&var, &given, binds);
|
|
288
|
+
unify(&substVars(&var, binds), &given, ctx)
|
|
289
|
+
.map_err(|e| format!("{label}: type argument {g}: {e}"))?;
|
|
290
|
+
}
|
|
291
|
+
// Used only in the body (`fun isA[T](a: Actor) -> Bool`): the argument is all
|
|
292
|
+
// that sets it.
|
|
293
|
+
None => {
|
|
294
|
+
call_map.insert(g.clone(), given);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
Ok(())
|
|
299
|
+
}
|
|
300
|
+
|
|
257
301
|
pub(crate) fn inferMethodCall(
|
|
258
302
|
obj_ty: &PlumType,
|
|
259
303
|
name: &str,
|
|
@@ -261,6 +305,19 @@ pub(crate) fn inferMethodCall(
|
|
|
261
305
|
env: &TypeEnv,
|
|
262
306
|
ctx: &CheckCtx,
|
|
263
307
|
expected: Option<&PlumType>,
|
|
308
|
+
) -> Result<PlumType, String> {
|
|
309
|
+
inferMethodCallWith(obj_ty, name, args, &[], env, ctx, expected)
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/// `inferMethodCall` with the call's explicit type arguments (`t.updateAs[Orb](..)`).
|
|
313
|
+
pub(crate) fn inferMethodCallWith(
|
|
314
|
+
obj_ty: &PlumType,
|
|
315
|
+
name: &str,
|
|
316
|
+
args: &[ast::Arg],
|
|
317
|
+
type_args: &[ast::Type],
|
|
318
|
+
env: &TypeEnv,
|
|
319
|
+
ctx: &CheckCtx,
|
|
320
|
+
expected: Option<&PlumType>,
|
|
264
321
|
) -> Result<PlumType, String> {
|
|
265
322
|
// A bare `Ok(2)` / `Err(e)` receiver leaves the other Result parameter unpinned;
|
|
266
323
|
// codegen would later hit an unknown method, so reject it here.
|
|
@@ -385,6 +442,8 @@ pub(crate) fn inferMethodCall(
|
|
|
385
442
|
unreachable!("instSig preserves the TFun shape")
|
|
386
443
|
};
|
|
387
444
|
let mut binds = Binds::new();
|
|
445
|
+
let label = format!("method '{}.{}'", class_name, name);
|
|
446
|
+
applyTypeArgs(&label, Some(&class_name), name, type_args, &mut call_map, &mut binds, ctx)?;
|
|
388
447
|
if let Some(exp) = expected {
|
|
389
448
|
bindMatch(&ret, exp, &mut binds);
|
|
390
449
|
}
|
|
@@ -393,7 +452,6 @@ pub(crate) fn inferMethodCall(
|
|
|
393
452
|
.get(&(Some(class_name.to_string()), name.to_string()))
|
|
394
453
|
.copied()
|
|
395
454
|
.unwrap_or(params.len());
|
|
396
|
-
let label = format!("method '{}.{}'", class_name, name);
|
|
397
455
|
checkCallArgs(&label, ¶ms, args, required, env, ctx, &mut binds)?;
|
|
398
456
|
recordCall(Some(&class_name), name, call_map);
|
|
399
457
|
recordDispatch(&resolveRecorded(obj_ty), name);
|
|
@@ -503,6 +561,7 @@ pub(crate) fn inferOperatorCall(
|
|
|
503
561
|
column: 0,
|
|
504
562
|
tail: ast::TailKind::NotTail,
|
|
505
563
|
recv: None,
|
|
564
|
+
type_args: Vec::new(),
|
|
506
565
|
})
|
|
507
566
|
})
|
|
508
567
|
.clone()
|
compiler/checker/src/callsites.rs
CHANGED
|
@@ -66,6 +66,10 @@ pub(crate) fn recordDispatch(obj_ty: &PlumType, name: &str) {
|
|
|
66
66
|
return;
|
|
67
67
|
}
|
|
68
68
|
let (line, column) = withCheck(|s| s.cur_pos.get());
|
|
69
|
+
// The implementers' copy for trait objects, when the method has `Self` inside a type.
|
|
70
|
+
let dyn_copy = traits.traits.get(tname).and_then(|t| t.method(name)).is_some_and(|m| m.dyn_copy);
|
|
71
|
+
let name = if dyn_copy { plum_core::trait_defaults::dynName(name) } else { name.to_string() };
|
|
72
|
+
let name = name.as_str();
|
|
69
73
|
let mut sites = Vec::new();
|
|
70
74
|
for (ty, (gens, entries)) in &traits.impls {
|
|
71
75
|
if gens.is_empty() {
|
|
@@ -98,7 +102,7 @@ pub(crate) fn recordDispatch(obj_ty: &PlumType, name: &str) {
|
|
|
98
102
|
}
|
|
99
103
|
|
|
100
104
|
/// Matches the pattern `pat` (with `TParam`s) against the concrete `t`, binding the params.
|
|
101
|
-
fn bindParams(pat: &PlumType, t: &PlumType, b: &mut BTreeMap<String, PlumType>) -> bool {
|
|
105
|
+
pub(crate) fn bindParams(pat: &PlumType, t: &PlumType, b: &mut BTreeMap<String, PlumType>) -> bool {
|
|
102
106
|
use PlumType::*;
|
|
103
107
|
match (pat, t) {
|
|
104
108
|
(TParam(p), _) => match b.get(p) {
|
compiler/checker/src/infer.rs
CHANGED
|
@@ -319,6 +319,12 @@ pub(crate) fn inferExprInner(
|
|
|
319
319
|
}
|
|
320
320
|
None => PlumType::TUnit,
|
|
321
321
|
};
|
|
322
|
+
// A closure whose result is expected to be a trait object returns one: its body's
|
|
323
|
+
// value is coerced there as a whole value (`rects.map(|r| r)` into a `List[Shape]`).
|
|
324
|
+
let body_ty = match exp_ret {
|
|
325
|
+
Some(r) if isTraitObject(r) && !hasInferVars(r) && !isTraitObject(&body_ty) && unify(r, &body_ty, ctx).is_ok() => r.clone(),
|
|
326
|
+
_ => body_ty,
|
|
327
|
+
};
|
|
322
328
|
Ok(PlumType::TFun(param_types, Box::new(body_ty)))
|
|
323
329
|
}
|
|
324
330
|
ast::Expr { kind: ast::ExprKind::Not(inner), .. } => {
|
|
@@ -531,6 +537,8 @@ pub(crate) fn inferExprInner(
|
|
|
531
537
|
match callee {
|
|
532
538
|
Ok(PlumType::TFun(param_types, ret)) => {
|
|
533
539
|
let mut binds = Binds::new();
|
|
540
|
+
let label = format!("call '{}'", call.name);
|
|
541
|
+
applyTypeArgs(&label, None, &call.name, &call.type_args, &mut call_map, &mut binds, ctx)?;
|
|
534
542
|
if let Some(exp) = expected {
|
|
535
543
|
bindMatch(&ret, exp, &mut binds);
|
|
536
544
|
}
|
|
@@ -544,7 +552,6 @@ pub(crate) fn inferExprInner(
|
|
|
544
552
|
.copied()
|
|
545
553
|
.filter(|_| isTopLevel)
|
|
546
554
|
.unwrap_or(param_types.len());
|
|
547
|
-
let label = format!("call '{}'", call.name);
|
|
548
555
|
checkCallArgs(&label, ¶m_types, &call.args, required, env, ctx, &mut binds)?;
|
|
549
556
|
checkUnpinned(call, &call_map, ¶m_types, &ret, &binds, ctx)?;
|
|
550
557
|
recordCall(None, &call.name, call_map);
|
|
@@ -620,7 +627,7 @@ pub(crate) fn inferExprInner(
|
|
|
620
627
|
},
|
|
621
628
|
ast::AttrKind::Method(call) => {
|
|
622
629
|
checkStaticUse(&attr.object, &obj_ty, &call.name, ctx)?;
|
|
623
|
-
|
|
630
|
+
inferMethodCallWith(&obj_ty, call.name.as_str(), &call.args, &call.type_args, env, ctx, expected)
|
|
624
631
|
}
|
|
625
632
|
}
|
|
626
633
|
}
|
compiler/checker/src/patterns.rs
CHANGED
|
@@ -91,11 +91,14 @@ pub(crate) fn checkPattern(
|
|
|
91
91
|
}
|
|
92
92
|
}
|
|
93
93
|
ast::CasePattern::As { ty, name } => {
|
|
94
|
-
let target = downcastTarget(ty, ctx)?;
|
|
95
94
|
let subject = resolveRecorded(subject_ty);
|
|
95
|
+
let target = downcastTarget(ty, &subject, ctx)?;
|
|
96
96
|
if isTraitObject(&subject) {
|
|
97
97
|
if isTraitObject(&target) {
|
|
98
|
-
|
|
98
|
+
let what = if target.to_string() == *ty { format!("{ty} is a trait") } else { format!("{ty} is the trait {target} here") };
|
|
99
|
+
return Err(format!(
|
|
100
|
+
"`{ty} as {name}`: {what}; a downcast names a type that implements {subject}, not another trait"
|
|
101
|
+
));
|
|
99
102
|
}
|
|
100
103
|
if !matches!(target, PlumType::TParam(_)) && !implementsTrait(&target, &subject) {
|
|
101
104
|
return Err(format!("`{ty} as {name}`: {ty} does not implement {subject}, so a {subject} is never a {ty}"));
|
|
@@ -143,7 +146,7 @@ pub(crate) fn checkPattern(
|
|
|
143
146
|
|
|
144
147
|
/// The type a downcast pattern `ty as name` binds: a declared non-generic type, or a generic
|
|
145
148
|
/// parameter in scope (its type in an instantiated body).
|
|
146
|
-
fn downcastTarget(ty: &str, ctx: &CheckCtx) -> Result<PlumType, String> {
|
|
149
|
+
fn downcastTarget(ty: &str, subject: &PlumType, ctx: &CheckCtx) -> Result<PlumType, String> {
|
|
147
150
|
if withCheck(|s| s.scope.borrow().isGeneric(ty)) {
|
|
148
151
|
if let Some(t) = typeParamBinding(ty) {
|
|
149
152
|
return Ok(t);
|
|
@@ -155,9 +158,18 @@ fn downcastTarget(ty: &str, ctx: &CheckCtx) -> Result<PlumType, String> {
|
|
|
155
158
|
}
|
|
156
159
|
let declared = ctx.enum_variants.values().find(|i| i.enum_name == ty);
|
|
157
160
|
match declared {
|
|
161
|
+
// A generic implementer takes its arguments from the trait object's.
|
|
158
|
-
Some(info) if !info.generics.is_empty() =>
|
|
162
|
+
Some(info) if !info.generics.is_empty() => match currentTraits().genericDowncast(ty, subject) {
|
|
163
|
+
Some(t) => Ok(t),
|
|
159
|
-
|
|
164
|
+
None if !isTraitObject(subject) => Ok(PlumType::TApp(
|
|
165
|
+
ty.to_string(),
|
|
166
|
+
info.generics.iter().map(|_| freshVar()).collect(),
|
|
160
|
-
|
|
167
|
+
)),
|
|
168
|
+
None => Err(format!(
|
|
169
|
+
"`{ty} as ..`: {ty} is generic and {subject} doesn't fix its type parameters ({}), so a downcast can't tell which {ty} to match",
|
|
170
|
+
info.generics.join(", ")
|
|
171
|
+
)),
|
|
172
|
+
},
|
|
161
173
|
Some(_) => Ok(plumTypeFromName(ty)),
|
|
162
174
|
None if ctx.enum_variants.contains_key(ty) => Err(format!(
|
|
163
175
|
"`{ty} as ..`: {ty} is a variant; a downcast names a type"
|
compiler/checker/src/program.rs
CHANGED
|
@@ -205,6 +205,16 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
205
205
|
let (mut global_env, methods, enum_variants) = buildGlobalTables(source);
|
|
206
206
|
let traits = std::rc::Rc::new(buildTraits(source));
|
|
207
207
|
withCheck(|s| *s.traits.borrow_mut() = traits.clone());
|
|
208
|
+
withCheck(|s| {
|
|
209
|
+
*s.fn_generics.borrow_mut() = source
|
|
210
|
+
.items
|
|
211
|
+
.iter()
|
|
212
|
+
.filter_map(|i| match i {
|
|
213
|
+
ast::Item::Fn(f) => Some(((f.type_param.clone(), f.name.clone()), f.generics.clone())),
|
|
214
|
+
_ => None,
|
|
215
|
+
})
|
|
216
|
+
.collect()
|
|
217
|
+
});
|
|
208
218
|
errors.extend(checkTraitDecls(source, &traits, &methods));
|
|
209
219
|
errors.extend(selfOutsideTrait(source));
|
|
210
220
|
// Shared fields of subtyped traits; codegen fills them in (see `addTraitParams`).
|
|
@@ -298,6 +308,7 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
298
308
|
}
|
|
299
309
|
}
|
|
300
310
|
|
|
311
|
+
errors.extend(crate::traits::checkTraitParamDefaults(source, &global_env, &ctx));
|
|
301
312
|
let defaultsAt = plum_core::trait_defaults::defaultPositions(source);
|
|
302
313
|
// Roots: every non-generic fn and every test. A generic fn is only
|
|
303
314
|
// name-resolved here (its body is type-checked per instantiation below).
|
|
@@ -311,7 +322,9 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
311
322
|
let mut local_errors = checkFn(f, &global_env, &ctx);
|
|
312
323
|
// A trait default's copy in an implementer: its errors are the default's own,
|
|
313
324
|
// reported once where the trait's default is checked.
|
|
325
|
+
if plum_core::trait_defaults::isDynCopy(f) {
|
|
326
|
+
dynErrors(f, &mut local_errors);
|
|
314
|
-
if plum_core::trait_defaults::isDefaultCopy(f, &defaultsAt.0, &defaultsAt.1) {
|
|
327
|
+
} else if plum_core::trait_defaults::isDefaultCopy(f, &defaultsAt.0, &defaultsAt.1) {
|
|
315
328
|
local_errors.clear();
|
|
316
329
|
}
|
|
317
330
|
if !fnGenericNames(f, &ctx).is_empty() {
|
|
@@ -377,7 +390,9 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
377
390
|
withCheck(|s| { let l = &s.cur_pos; l.set((f.line, f.column)) });
|
|
378
391
|
let saved = withCheck(|s| { let r = &s.record; r.borrow_mut().replace(HashMap::new()) });
|
|
379
392
|
let mut errs = checkFn(f, &global_env, &ctx);
|
|
393
|
+
if plum_core::trait_defaults::isDynCopy(f) {
|
|
394
|
+
dynErrors(f, &mut errs);
|
|
380
|
-
if plum_core::trait_defaults::isDefaultCopy(f, &defaultsAt.0, &defaultsAt.1) {
|
|
395
|
+
} else if plum_core::trait_defaults::isDefaultCopy(f, &defaultsAt.0, &defaultsAt.1) {
|
|
381
396
|
errs.clear();
|
|
382
397
|
}
|
|
383
398
|
let own = withCheck(|s| { let r = &s.record; std::mem::replace(&mut *r.borrow_mut(), saved) });
|
|
@@ -412,3 +427,16 @@ pub(crate) fn checkSourceInner(source: &ast::Source) -> (CheckResult<()>, TypedI
|
|
|
412
427
|
};
|
|
413
428
|
(result, inst.info)
|
|
414
429
|
}
|
|
430
|
+
|
|
431
|
+
/// The errors of a method's `$dyn` copy (`plum_core::trait_defaults`), said as the method's:
|
|
432
|
+
/// it was checked again with `Self` inside a parameter or the result as the trait object.
|
|
433
|
+
fn dynErrors(f: &ast::Fn, errors: &mut [CheckError]) {
|
|
434
|
+
let name = f.name.trim_end_matches(plum_core::trait_defaults::DYN_SUFFIX);
|
|
435
|
+
let owner = f.type_param.clone().unwrap_or_default();
|
|
436
|
+
for e in errors.iter_mut() {
|
|
437
|
+
let msg = e.message.replacen(&format!("fn '{}'", f.name), &format!("fn '{name}'"), 1);
|
|
438
|
+
e.message = format!(
|
|
439
|
+
"{owner}.{name} can't be called on a trait object: with Self inside a parameter or the result as the trait object, {msg}"
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
}
|
compiler/checker/src/state.rs
CHANGED
|
@@ -80,6 +80,9 @@ pub(crate) struct CheckState {
|
|
|
80
80
|
/// Set while `unify` compares the parts of a type (`List[Actor]` against `List[Orb]`): a
|
|
81
81
|
/// trait object accepts an implementer only as a whole value, not inside another type.
|
|
82
82
|
pub(crate) no_coerce: Cell<bool>,
|
|
83
|
+
/// Each fn's and method's own declared generics, in order ((owner, name) -> names), for
|
|
84
|
+
/// a call's explicit type arguments (`findAs[Orb](..)`).
|
|
85
|
+
pub(crate) fn_generics: RefCell<HashMap<(Option<String>, String), Vec<String>>>,
|
|
83
86
|
}
|
|
84
87
|
|
|
85
88
|
thread_local! {
|
compiler/checker/src/traits.rs
CHANGED
|
@@ -20,6 +20,12 @@ pub struct TraitMethodInfo {
|
|
|
20
20
|
pub hasSelf: bool,
|
|
21
21
|
/// Arguments a call must give (the params before the first with a default).
|
|
22
22
|
pub minRequired: usize,
|
|
23
|
+
/// Each parameter's default as the trait declares it (`dx: Int = 1`): a call on a
|
|
24
|
+
/// trait object that leaves the argument out gets it.
|
|
25
|
+
pub defaults: Vec<Option<ast::Expr>>,
|
|
26
|
+
/// A call on a trait object runs each implementer's `$dyn` copy of the method
|
|
27
|
+
/// (`plum_core::trait_defaults::needsDynCopy`: `Self` inside another type).
|
|
28
|
+
pub dyn_copy: bool,
|
|
23
29
|
pub line: usize,
|
|
24
30
|
pub column: usize,
|
|
25
31
|
}
|
|
@@ -122,6 +128,25 @@ impl Traits {
|
|
|
122
128
|
}
|
|
123
129
|
}
|
|
124
130
|
|
|
131
|
+
/// The type `Box as b` binds on the trait object `subject` when `Box` is generic: its
|
|
132
|
+
/// arguments are the ones its `is` entry gives for the subject's (`Box[M] is Actor[M]` on
|
|
133
|
+
/// an `Actor[Msg]`: `Box[Msg]`). `None` when the entry doesn't fix every argument.
|
|
134
|
+
pub fn genericDowncast(&self, ty: &str, subject: &PlumType) -> Option<PlumType> {
|
|
135
|
+
let (name, args) = self.traitObject(subject)?;
|
|
136
|
+
let (gens, entries) = self.impls.get(ty)?;
|
|
137
|
+
if gens.is_empty() {
|
|
138
|
+
return None;
|
|
139
|
+
}
|
|
140
|
+
entries.iter().filter(|e| e.trait_name == name && e.args.len() == args.len()).find_map(|e| {
|
|
141
|
+
let mut b = BTreeMap::new();
|
|
142
|
+
if !e.args.iter().zip(args).all(|(p, t)| crate::callsites::bindParams(p, t, &mut b)) {
|
|
143
|
+
return None;
|
|
144
|
+
}
|
|
145
|
+
let targs: Option<Vec<PlumType>> = gens.iter().map(|g| b.get(g).cloned()).collect();
|
|
146
|
+
Some(PlumType::TApp(ty.to_string(), targs?))
|
|
147
|
+
})
|
|
148
|
+
}
|
|
149
|
+
|
|
125
150
|
/// The signature of trait method `method` of the trait object `tr`, with `Self` as `self_ty`.
|
|
126
151
|
pub fn methodSig(&self, tr: &PlumType, method: &str, self_ty: &PlumType) -> Option<PlumType> {
|
|
127
152
|
let (name, args) = self.traitObject(tr)?;
|
|
@@ -223,6 +248,13 @@ pub fn buildTraits(source: &ast::Source) -> Traits {
|
|
|
223
248
|
hasDefault: m.hasDefault,
|
|
224
249
|
hasSelf: m.sig.has_self,
|
|
225
250
|
minRequired: minRequired(&m.sig),
|
|
251
|
+
dyn_copy: plum_core::trait_defaults::needsDynCopy(&m.sig),
|
|
252
|
+
defaults: m
|
|
253
|
+
.sig
|
|
254
|
+
.params
|
|
255
|
+
.iter()
|
|
256
|
+
.map(|p| p.default.clone().filter(|_| matches!(p.ty, ast::ParamType::Type(_))))
|
|
257
|
+
.collect(),
|
|
226
258
|
line: m.sig.line,
|
|
227
259
|
column: m.sig.column,
|
|
228
260
|
}
|
|
@@ -654,3 +686,45 @@ pub(crate) fn joinTrait(expected: Option<&PlumType>, vals: &[PlumType], ctx: &Ch
|
|
|
654
686
|
}
|
|
655
687
|
None
|
|
656
688
|
}
|
|
689
|
+
|
|
690
|
+
/// Checks the parameter defaults of every trait method (`fun moved(self, dx: Int = 1)`) and
|
|
691
|
+
/// records their types: a call on a trait object that leaves an argument out compiles the
|
|
692
|
+
/// trait's default. A default runs at the call, where the implementer is not known, so its
|
|
693
|
+
/// parameter's type can't mention `Self` or the trait's parameters.
|
|
694
|
+
pub(crate) fn checkTraitParamDefaults(source: &ast::Source, global_env: &TypeEnv, ctx: &CheckCtx) -> Vec<CheckError> {
|
|
695
|
+
let mut errors = Vec::new();
|
|
696
|
+
for item in &source.items {
|
|
697
|
+
let ast::Item::Trait(t) = item else { continue };
|
|
698
|
+
let mut scopeNames: Vec<String> = t.generics.iter().map(|g| g.name.clone()).collect();
|
|
699
|
+
scopeNames.push(ast::SELF_TYPE.to_string());
|
|
700
|
+
for m in &t.methods {
|
|
701
|
+
for p in &m.sig.params {
|
|
702
|
+
let (Some(d), ast::ParamType::Type(_)) = (&p.default, &p.ty) else { continue };
|
|
703
|
+
let saved = setScope(Scope::of(&scopeNames, &m.sig), None);
|
|
704
|
+
let declared = paramTypeG(&p.ty);
|
|
705
|
+
restoreScope(saved);
|
|
706
|
+
let mut free = Vec::new();
|
|
707
|
+
freeTParams(&declared, &mut free);
|
|
708
|
+
let say = |msg: String| format!("trait {} method '{}': default of parameter '{}': {}", t.name, m.sig.name, p.name, msg);
|
|
709
|
+
if let Some(g) = free.first() {
|
|
710
|
+
errors.push(CheckError::at(
|
|
711
|
+
m.sig.line,
|
|
712
|
+
m.sig.column,
|
|
713
|
+
say(format!("its type mentions {g}, which the call on a trait object doesn't know; drop the default, or give the parameter a concrete type")),
|
|
714
|
+
));
|
|
715
|
+
continue;
|
|
716
|
+
}
|
|
717
|
+
let (r, pos, resolution) = withFailure(|| inferExprWith(d, global_env, ctx, Some(&declared)));
|
|
718
|
+
match r {
|
|
719
|
+
Ok(ty) => {
|
|
720
|
+
if let Err(msg) = unifyArg(&declared, &ty, d, ctx) {
|
|
721
|
+
errors.push(failureError(spanOf(d), false, (m.sig.line, m.sig.column), say(msg)));
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
Err(msg) => errors.push(failureError(pos, resolution, (m.sig.line, m.sig.column), say(msg))),
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
errors
|
|
730
|
+
}
|
compiler/checker/src/unification.rs
CHANGED
|
@@ -211,8 +211,17 @@ pub fn unify(t1: &PlumType, t2: &PlumType, ctx: &CheckCtx) -> Result<(), String>
|
|
|
211
211
|
// A trait object accepts a value of any type that implements the trait (never the
|
|
212
212
|
// other way round: `Type as name` in a `match` is the only downcast).
|
|
213
213
|
(expected, actual) if isTraitObject(expected) => {
|
|
214
|
+
// An implementer whose open arguments an earlier coercion already fixed.
|
|
215
|
+
let resolved = if hasInferVars(actual) { resolveRecorded(actual) } else { actual.clone() };
|
|
216
|
+
let actual = &resolved;
|
|
214
217
|
let implements = implementsTrait(actual, expected);
|
|
215
218
|
if implements && !withCheck(|s| s.no_coerce.get()) {
|
|
219
|
+
// A generic implementer whose own arguments are still open (`bx := Box(id: 1)`,
|
|
220
|
+
// later put in a `List[Actor[Msg]]`) takes them from the trait's: recorded, so
|
|
221
|
+
// the value's earlier construction resolves to `Box[Msg]`.
|
|
222
|
+
if hasInferVars(actual) {
|
|
223
|
+
bindMatch(actual, expected, &mut Binds::new());
|
|
224
|
+
}
|
|
216
225
|
Ok(())
|
|
217
226
|
} else if implements {
|
|
218
227
|
Err(format!(
|
compiler/checker/tests/checker/traits_tests.rs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
//! Traits: conformance, trait objects, `Self`, downcasts and bounds.
|
|
3
3
|
use plum_checker::types::PlumType;
|
|
4
4
|
|
|
5
|
-
const PRE: &str = "import std/Str\nimport std/Int\nimport std/Float\nimport std/List\n\nfun show(s: Str) = Unit\n\n";
|
|
5
|
+
const PRE: &str = "import std/Str\nimport std/Int\nimport std/Float\nimport std/List\nimport std/Option\n\nfun show(s: Str) = Unit\n\n";
|
|
6
6
|
|
|
7
7
|
const ACTOR: &str = "trait Actor =
|
|
8
8
|
fun key(self) -> Int
|
|
@@ -556,3 +556,90 @@ fn traitsCompile() {
|
|
|
556
556
|
let source = plum_test_support::load("traits", &format!("{PRE}{ACTOR}fun main() = show(\"x\")\n")).unwrap();
|
|
557
557
|
plum_test_support::compileSource(&source).unwrap_or_else(|e| panic!("{e}"));
|
|
558
558
|
}
|
|
559
|
+
|
|
560
|
+
#[test]
|
|
561
|
+
fn explicitTypeArguments() {
|
|
562
|
+
let gen = "fun pick[T](a: Actor) -> Option[T] = match a
|
|
563
|
+
T as t => Some(t)
|
|
564
|
+
_ => None
|
|
565
|
+
|
|
566
|
+
fun two[A, B](a: A, b: B) -> Int = 2
|
|
567
|
+
|
|
568
|
+
fun plain(a: Int) -> Int = a
|
|
569
|
+
";
|
|
570
|
+
ok(&format!(
|
|
571
|
+
"{ACTOR}{gen}
|
|
572
|
+
fun main() =
|
|
573
|
+
o: Actor := Orb(id: 1, vx: 2.0)
|
|
574
|
+
_ := pick[Orb](o).isSome()
|
|
575
|
+
_ := two[Int, Str](1, \"a\")
|
|
576
|
+
"
|
|
577
|
+
));
|
|
578
|
+
fails(
|
|
579
|
+
&format!("{ACTOR}{gen}\nfun main() =\n _ := two[Int](1, \"a\")\n"),
|
|
580
|
+
"takes 2 type argument(s), got 1",
|
|
581
|
+
);
|
|
582
|
+
fails(
|
|
583
|
+
&format!("{ACTOR}{gen}\nfun main() =\n _ := two[Int, Int](1, \"a\")\n"),
|
|
584
|
+
"call 'two' arg 1",
|
|
585
|
+
);
|
|
586
|
+
fails(
|
|
587
|
+
&format!("{ACTOR}{gen}\nfun main() =\n _ := plain[Int](1)\n"),
|
|
588
|
+
"call 'plain': takes 0 type argument(s), got 1",
|
|
589
|
+
);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
const GEN: &str = "enum Msg = Hit | Miss
|
|
593
|
+
|
|
594
|
+
trait Thing[M] =
|
|
595
|
+
fun key(self) -> Int
|
|
596
|
+
|
|
597
|
+
struct Box[M](id: Int) is Thing[M] =
|
|
598
|
+
fun key(self) -> Int = self.id
|
|
599
|
+
|
|
600
|
+
";
|
|
601
|
+
|
|
602
|
+
#[test]
|
|
603
|
+
fn bareGenericImplementerIsPinnedByItsFirstCoercion() {
|
|
604
|
+
ok(&format!("{GEN}fun main() =\n bx := Box(id: 1)\n xs: List[Thing[Msg]] := [bx]\n show(\"{{xs.length()}}\")\n"));
|
|
605
|
+
fails(
|
|
606
|
+
&format!("{GEN}fun main() =\n bx := Box(id: 1)\n xs: List[Thing[Msg]] := [bx]\n ys: List[Thing[Int]] := [bx]\n show(\"{{xs.length()}}\")\n"),
|
|
607
|
+
"Box[Msg] does not implement Thing[Int]",
|
|
608
|
+
);
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
#[test]
|
|
612
|
+
fn traitParameterDefaults() {
|
|
613
|
+
ok("trait Mover =\n fun moved(self, dx: Int = 1) -> Int\n\nstruct P(x: Int) is Mover =\n fun moved(self, dx: Int = 1) -> Int = self.x + dx\n\nfun main() =\n m: Mover := P(x: 1)\n show(\"{m.moved()}\")\n");
|
|
614
|
+
fails(
|
|
615
|
+
"trait Pick[M] =\n fun pick(self, m: Option[M] = None) -> Int\n\nfun main() = Unit\n",
|
|
616
|
+
"its type mentions M",
|
|
617
|
+
);
|
|
618
|
+
fails(
|
|
619
|
+
"trait Mover =\n fun moved(self, dx: Int = \"no\") -> Int\n\nfun main() = Unit\n",
|
|
620
|
+
"trait Mover method 'moved': default of parameter 'dx'",
|
|
621
|
+
);
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
#[test]
|
|
625
|
+
fn selfInsideATypeIsCheckedForTraitObjects() {
|
|
626
|
+
let tr = "trait Splits =\n fun split(self) -> List[Self]\n\n";
|
|
627
|
+
ok(&format!("{tr}struct C(id: Int) is Splits =\n fun split(self) -> List[C] = [C(id: 1)]\n\nfun main() =\n s: Splits := C(id: 1)\n show(\"{{s.split().length()}}\")\n"));
|
|
628
|
+
fails(
|
|
629
|
+
&format!("{tr}struct C(id: Int) is Splits =\n fun split(self) -> List[C] =\n xs: List[C] := [C(id: 1)]\n xs\n\nfun main() = Unit\n"),
|
|
630
|
+
"C.split can't be called on a trait object",
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
#[test]
|
|
635
|
+
fn downcastToAGenericImplementer() {
|
|
636
|
+
ok(&format!("{GEN}fun idOf(t: Thing[Msg]) -> Int = match t\n Box as b => b.id\n _ => 0\n\nfun main() = show(\"{{idOf(Box(id: 1))}}\")\n"));
|
|
637
|
+
fails(
|
|
638
|
+
&format!("{GEN}struct Two[A, B](id: Int) is Thing[A] =\n fun key(self) -> Int = self.id\n\nfun idOf(t: Thing[Msg]) -> Int = match t\n Two as b => b.id\n _ => 0\n\nfun main() = Unit\n"),
|
|
639
|
+
"doesn't fix its type parameters (A, B)",
|
|
640
|
+
);
|
|
641
|
+
fails(
|
|
642
|
+
&format!("{ACTOR}trait Named =\n fun name(self) -> Str\n\nfun asT[T](a: Actor) -> Int = match a\n T as t => 1\n _ => 0\n\nfun main() =\n n: Option[Named] := None\n _ := n\n show(\"{{asT[Named](Orb(id: 1, vx: 0.0))}}\")\n"),
|
|
643
|
+
"T is the trait Named here",
|
|
644
|
+
);
|
|
645
|
+
}
|
compiler/core/src/ast.rs
CHANGED
|
@@ -165,7 +165,17 @@ 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
|
+
// A trait method's parameter defaults: compiled at a call on a trait object.
|
|
169
|
+
Item::Trait(t) => {
|
|
170
|
+
for m in &mut t.methods {
|
|
171
|
+
for p in &mut m.sig.params {
|
|
172
|
+
if let Some(d) = &mut p.default {
|
|
173
|
+
numberExpr(d, false);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
168
|
-
Item::Enum(_)
|
|
178
|
+
Item::Enum(_) => {}
|
|
169
179
|
}
|
|
170
180
|
}
|
|
171
181
|
}
|
|
@@ -1063,6 +1073,9 @@ pub struct FnCall {
|
|
|
1063
1073
|
/// `closure_spec::stampReceivers` before the optimisation passes; the stamp travels with the
|
|
1064
1074
|
/// call when a pass copies or inlines it. `None` when unknown (or not a method call).
|
|
1065
1075
|
pub recv: Option<String>,
|
|
1076
|
+
/// Explicit type arguments (`findAs[Orb](xs, 1)`, `t.updateAs[Orb](..)`): the callee's
|
|
1077
|
+
/// own declared generics, in order. Empty unless the source wrote them.
|
|
1078
|
+
pub type_args: Vec<Type>,
|
|
1066
1079
|
}
|
|
1067
1080
|
|
|
1068
1081
|
/// How a call in tail position is made (see `tail.rs`). `NotTail` is the default.
|
compiler/core/src/ctors.rs
CHANGED
|
@@ -333,6 +333,7 @@ pub fn lowerCtors(source: &mut Source) -> Vec<String> {
|
|
|
333
333
|
column: column,
|
|
334
334
|
tail: TailKind::NotTail,
|
|
335
335
|
recv: None,
|
|
336
|
+
type_args: Vec::new(),
|
|
336
337
|
}),
|
|
337
338
|
})),
|
|
338
339
|
0,
|
|
@@ -448,6 +449,7 @@ fn rewriteCall(e: &mut Expr, plans: &HashMap<String, Plan>, errors: &mut Vec<Str
|
|
|
448
449
|
column: 0,
|
|
449
450
|
tail: TailKind::NotTail,
|
|
450
451
|
recv: None,
|
|
452
|
+
type_args: Vec::new(),
|
|
451
453
|
})
|
|
452
454
|
.at(e);
|
|
453
455
|
}
|
compiler/core/src/drive.rs
CHANGED
|
@@ -368,6 +368,7 @@ impl Tcx {
|
|
|
368
368
|
column: 0,
|
|
369
369
|
tail: TailKind::NotTail,
|
|
370
370
|
recv: None,
|
|
371
|
+
type_args: Vec::new(),
|
|
371
372
|
}),
|
|
372
373
|
}))
|
|
373
374
|
} else if let Some(t) = &self.callee.type_param {
|
|
@@ -380,6 +381,7 @@ impl Tcx {
|
|
|
380
381
|
column: 0,
|
|
381
382
|
tail: TailKind::NotTail,
|
|
382
383
|
recv: None,
|
|
384
|
+
type_args: Vec::new(),
|
|
383
385
|
}),
|
|
384
386
|
}))
|
|
385
387
|
} else {
|
|
@@ -390,6 +392,7 @@ impl Tcx {
|
|
|
390
392
|
column: 0,
|
|
391
393
|
tail: TailKind::NotTail,
|
|
392
394
|
recv: None,
|
|
395
|
+
type_args: Vec::new(),
|
|
393
396
|
})
|
|
394
397
|
}
|
|
395
398
|
}
|
|
@@ -1105,6 +1108,7 @@ impl Driver {
|
|
|
1105
1108
|
column: 0,
|
|
1106
1109
|
tail: TailKind::NotTail,
|
|
1107
1110
|
recv: None,
|
|
1111
|
+
type_args: Vec::new(),
|
|
1108
1112
|
});
|
|
1109
1113
|
return true;
|
|
1110
1114
|
}
|
|
@@ -1892,6 +1896,7 @@ impl Driver {
|
|
|
1892
1896
|
column: 0,
|
|
1893
1897
|
tail: TailKind::NotTail,
|
|
1894
1898
|
recv: None,
|
|
1899
|
+
type_args: Vec::new(),
|
|
1895
1900
|
}));
|
|
1896
1901
|
self.origins.insert(name.clone(), anc);
|
|
1897
1902
|
self.fused.push(f);
|
compiler/core/src/forms.rs
CHANGED
|
@@ -181,7 +181,7 @@ pub fn forStmt(binders: Vec<String>, source: Expr, sourceText: String, body: Blo
|
|
|
181
181
|
|
|
182
182
|
fn loopStmt(name: &str, rest: Vec<Expr>, line: usize, column: usize) -> Stmt {
|
|
183
183
|
let args = std::iter::once(Expr::Int(0)).chain(rest).map(Arg::Positional).collect();
|
|
184
|
-
Stmt::Expr(Expr::FnCall(FnCall { name: name.to_string(), args, line, column, tail: TailKind::NotTail, recv: None }), line, column)
|
|
184
|
+
Stmt::Expr(Expr::FnCall(FnCall { name: name.to_string(), args, line, column, tail: TailKind::NotTail, recv: None, type_args: Vec::new() }), line, column)
|
|
185
185
|
}
|
|
186
186
|
|
|
187
187
|
/// The loop a statement is, if it is one.
|
|
@@ -301,6 +301,7 @@ fn method(obj: &str, name: &str, args: Vec<Expr>) -> Expr {
|
|
|
301
301
|
column: 0,
|
|
302
302
|
tail: TailKind::NotTail,
|
|
303
303
|
recv: None,
|
|
304
|
+
type_args: Vec::new(),
|
|
304
305
|
}),
|
|
305
306
|
}))
|
|
306
307
|
}
|
|
@@ -504,6 +505,7 @@ fn callOf(name: &str, args: Vec<Expr>, line: usize, column: usize) -> Stmt {
|
|
|
504
505
|
column: 0,
|
|
505
506
|
tail: TailKind::NotTail,
|
|
506
507
|
recv: None,
|
|
508
|
+
type_args: Vec::new(),
|
|
507
509
|
}),
|
|
508
510
|
line,
|
|
509
511
|
column,
|
compiler/core/src/loader.rs
CHANGED
|
@@ -378,7 +378,7 @@ fn parseText(path: &Path, text: &str) -> Loaded_<Source> {
|
|
|
378
378
|
path.display().to_string(),
|
|
379
379
|
err.start.row + 1,
|
|
380
380
|
err.start.column + 1,
|
|
381
|
-
err.message(),
|
|
381
|
+
format!("{}{}", err.message(), groupingHint(text, err.start)),
|
|
382
382
|
)]);
|
|
383
383
|
}
|
|
384
384
|
let ap = AstParser::new(&text);
|
|
@@ -395,6 +395,32 @@ fn parseText(path: &Path, text: &str) -> Loaded_<Source> {
|
|
|
395
395
|
Ok(source)
|
|
396
396
|
}
|
|
397
397
|
|
|
398
|
+
/// `(a == b)` where a value starts: grouping is `{ }` in Plum, `( )` is only for calls.
|
|
399
|
+
/// A hint line when the error sits just after a `(` that no callee name or `]` precedes.
|
|
400
|
+
pub fn groupingHint(text: &str, at: tree_sitter::Point) -> String {
|
|
401
|
+
let Some(line) = text.lines().nth(at.row) else { return String::new() };
|
|
402
|
+
let Some(before) = line.get(..at.column.min(line.len())) else { return String::new() };
|
|
403
|
+
let head = if line[before.len()..].starts_with('(') {
|
|
404
|
+
before
|
|
405
|
+
} else {
|
|
406
|
+
let Some(head) = before.trim_end().strip_suffix('(') else { return String::new() };
|
|
407
|
+
head
|
|
408
|
+
};
|
|
409
|
+
let head = head.trim_end();
|
|
410
|
+
let word: String = {
|
|
411
|
+
let mut w: Vec<char> = head.chars().rev().take_while(|c| c.is_alphanumeric() || *c == '_').collect();
|
|
412
|
+
w.reverse();
|
|
413
|
+
w.into_iter().collect()
|
|
414
|
+
};
|
|
415
|
+
let keyword = ["assert", "return", "if", "then", "else", "match", "crash", "when", "while", "range"];
|
|
416
|
+
let callee = !word.is_empty() && !keyword.contains(&word.as_str());
|
|
417
|
+
if callee || head.ends_with(']') || head.ends_with(')') {
|
|
418
|
+
return String::new();
|
|
419
|
+
}
|
|
420
|
+
"\n hint: grouping uses `{ }` in Plum (`( )` is only for calls): write `{a == b}`, not `(a == b)`"
|
|
421
|
+
.to_string()
|
|
422
|
+
}
|
|
423
|
+
|
|
398
424
|
/// A syntax error pinned to the token tree-sitter could not fit.
|
|
399
425
|
#[derive(Debug, Clone, PartialEq)]
|
|
400
426
|
pub struct SyntaxError {
|
compiler/core/src/parser.rs
CHANGED
|
@@ -1477,7 +1477,8 @@ impl<'a> AstParser<'a> {
|
|
|
1477
1477
|
})
|
|
1478
1478
|
.unwrap_or_else(|| self.missing(node));
|
|
1479
1479
|
let member = named.get(1).map(|n| self.text(*n)).unwrap_or_default();
|
|
1480
|
+
let type_args = self.typeArguments(node);
|
|
1480
|
-
let attr = match
|
|
1481
|
+
let attr = match node.child_by_field_name("arguments") {
|
|
1481
1482
|
Some(args_node) => {
|
|
1482
1483
|
let mut acursor = args_node.walk();
|
|
1483
1484
|
let args = args_node
|
|
@@ -1491,6 +1492,7 @@ impl<'a> AstParser<'a> {
|
|
|
1491
1492
|
column: pos.column + 1,
|
|
1492
1493
|
tail: TailKind::NotTail,
|
|
1493
1494
|
recv: None,
|
|
1495
|
+
type_args,
|
|
1494
1496
|
})
|
|
1495
1497
|
}
|
|
1496
1498
|
None => AttrKind::Field(member),
|
|
@@ -1524,6 +1526,7 @@ impl<'a> AstParser<'a> {
|
|
|
1524
1526
|
column,
|
|
1525
1527
|
tail: TailKind::NotTail,
|
|
1526
1528
|
recv: None,
|
|
1529
|
+
type_args: Vec::new(),
|
|
1527
1530
|
}),
|
|
1528
1531
|
}))
|
|
1529
1532
|
};
|
|
@@ -1580,15 +1583,23 @@ impl<'a> AstParser<'a> {
|
|
|
1580
1583
|
Expr::Question(Box::new(value))
|
|
1581
1584
|
}
|
|
1582
1585
|
|
|
1586
|
+
/// A call's explicit `[A, B]` type arguments (its `generics` field), empty if none.
|
|
1587
|
+
fn typeArguments(&self, node: Node) -> Vec<Type> {
|
|
1588
|
+
let Some(g) = node.child_by_field_name("generics") else { return Vec::new() };
|
|
1589
|
+
let mut cursor = g.walk();
|
|
1590
|
+
g.named_children(&mut cursor).map(|t| self.parseTypeOrFn(t)).collect()
|
|
1591
|
+
}
|
|
1592
|
+
|
|
1583
1593
|
fn parseFnCall(&self, node: Node) -> FnCall {
|
|
1584
1594
|
// fn_call: var_identifier fn_argument_list (the callee lexes as var_identifier
|
|
1585
1595
|
// to avoid an identifier-token tie with all-lowercase, no-underscore names)
|
|
1586
1596
|
let name = node
|
|
1587
|
-
.
|
|
1597
|
+
.child_by_field_name("function")
|
|
1588
1598
|
.map(|n| self.text(n))
|
|
1589
1599
|
.unwrap_or_default();
|
|
1600
|
+
let type_args = self.typeArguments(node);
|
|
1590
1601
|
let args = node
|
|
1591
|
-
.
|
|
1602
|
+
.child_by_field_name("arguments")
|
|
1592
1603
|
.map(|args_node| {
|
|
1593
1604
|
let mut cursor = args_node.walk();
|
|
1594
1605
|
args_node
|
|
@@ -1605,6 +1616,7 @@ impl<'a> AstParser<'a> {
|
|
|
1605
1616
|
column: pos.column + 1,
|
|
1606
1617
|
tail: TailKind::NotTail,
|
|
1607
1618
|
recv: None,
|
|
1619
|
+
type_args,
|
|
1608
1620
|
}
|
|
1609
1621
|
}
|
|
1610
1622
|
|
|
@@ -1643,6 +1655,7 @@ impl<'a> AstParser<'a> {
|
|
|
1643
1655
|
column: pos.column + 1,
|
|
1644
1656
|
tail: TailKind::NotTail,
|
|
1645
1657
|
recv: None,
|
|
1658
|
+
type_args: Vec::new(),
|
|
1646
1659
|
}))
|
|
1647
1660
|
}
|
|
1648
1661
|
_ => {
|
compiler/core/src/trait_defaults.rs
CHANGED
|
@@ -78,6 +78,7 @@ pub fn expandDefaults(src: &Source) -> Option<Source> {
|
|
|
78
78
|
}
|
|
79
79
|
}
|
|
80
80
|
}
|
|
81
|
+
addDynCopies(src, &traits, &mut owned, &mut added);
|
|
81
82
|
if added.is_empty() {
|
|
82
83
|
return None;
|
|
83
84
|
}
|
|
@@ -86,6 +87,86 @@ pub fn expandDefaults(src: &Source) -> Option<Source> {
|
|
|
86
87
|
Some(out)
|
|
87
88
|
}
|
|
88
89
|
|
|
90
|
+
/// The suffix of a method's copy for calls on a trait object (`split$dyn`).
|
|
91
|
+
pub const DYN_SUFFIX: &str = "$dyn";
|
|
92
|
+
|
|
93
|
+
/// The name of `method`'s copy for calls on a trait object.
|
|
94
|
+
pub fn dynName(method: &str) -> String {
|
|
95
|
+
format!("{method}{DYN_SUFFIX}")
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/// Whether `f` is a copy for calls on a trait object (`addDynCopies`).
|
|
99
|
+
pub fn isDynCopy(f: &Fn) -> bool {
|
|
100
|
+
f.name.ends_with(DYN_SUFFIX)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/// `Self` inside another type (`List[Self]`, `Option[Self]`), not `Self` alone.
|
|
104
|
+
fn nestedSelf(t: &Type) -> bool {
|
|
105
|
+
t.mentionsSelf() && !(t.name == SELF_TYPE && t.generics.is_empty())
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
fn nestedSelfParam(t: &ParamType) -> bool {
|
|
109
|
+
match t {
|
|
110
|
+
ParamType::Type(t) => nestedSelf(t),
|
|
111
|
+
ParamType::Fn(ps, r) => ps.iter().any(|p| p.mentionsSelf()) || r.as_ref().is_some_and(|r| r.mentionsSelf()),
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/// Whether a call on a trait object of the trait method `sig` runs the implementer's
|
|
116
|
+
/// `$dyn` copy: some parameter or the result has `Self` inside another type. `List[Orb]` and
|
|
117
|
+
/// `List[Actor]` are different values, so the copy is the method checked again with that
|
|
118
|
+
/// `Self` as the trait object: `[Orb(..)]` in it builds a `List[Actor]` at once.
|
|
119
|
+
pub fn needsDynCopy(sig: &Fn) -> bool {
|
|
120
|
+
sig.params.iter().any(|p| nestedSelfParam(&p.ty)) || sig.returns.as_ref().is_some_and(nestedSelf)
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/// For each implementer and each trait method that `needsDynCopy`, a copy of the type's
|
|
124
|
+
/// method (its own or its copy of the default) named `dynName`, whose parameters and
|
|
125
|
+
/// result that have `Self` inside another type have the trait object there instead.
|
|
126
|
+
fn addDynCopies(src: &Source, traits: &HashMap<&str, &Trait>, owned: &mut HashSet<(String, String)>, added: &mut Vec<Item>) {
|
|
127
|
+
let mut copies: Vec<Item> = Vec::new();
|
|
128
|
+
for item in &src.items {
|
|
129
|
+
let Item::Enum(e) = item else { continue };
|
|
130
|
+
for entry in &e.implements {
|
|
131
|
+
let Some(t) = traits.get(entry.name.as_str()) else { continue };
|
|
132
|
+
if t.generics.len() != entry.generics.len() {
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
let mut subst: HashMap<String, Type> =
|
|
136
|
+
t.generics.iter().map(|g| g.name.clone()).zip(entry.generics.iter().cloned()).collect();
|
|
137
|
+
subst.insert(SELF_TYPE.to_string(), entry.clone());
|
|
138
|
+
for m in t.methods.iter().filter(|m| needsDynCopy(&m.sig)) {
|
|
139
|
+
let key = (e.name.clone(), dynName(&m.sig.name));
|
|
140
|
+
if owned.contains(&key) {
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
let own = src.items.iter().chain(added.iter()).find_map(|i| match i {
|
|
144
|
+
Item::Fn(f) if f.type_param.as_deref() == Some(e.name.as_str()) && f.name == m.sig.name => Some(f),
|
|
145
|
+
_ => None,
|
|
146
|
+
});
|
|
147
|
+
let Some(own) = own else { continue };
|
|
148
|
+
if own.params.len() != m.sig.params.len() {
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
let mut f = own.clone();
|
|
152
|
+
f.name = key.1.clone();
|
|
153
|
+
for (p, sp) in f.params.iter_mut().zip(&m.sig.params) {
|
|
154
|
+
if nestedSelfParam(&sp.ty) {
|
|
155
|
+
p.ty = substParam(&sp.ty, &subst);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if let Some(r) = m.sig.returns.as_ref().filter(|r| nestedSelf(r)) {
|
|
159
|
+
f.returns = Some(substType(r, &subst));
|
|
160
|
+
}
|
|
161
|
+
refreshFnIds(&mut f);
|
|
162
|
+
owned.insert(key);
|
|
163
|
+
copies.push(Item::Fn(f));
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
added.extend(copies);
|
|
168
|
+
}
|
|
169
|
+
|
|
89
170
|
/// Whether `f` is a copy `expandDefaults` made: a method of a type at the position of a
|
|
90
171
|
/// default body of a trait. `defaultsAt` is `defaultPositions` of the program.
|
|
91
172
|
pub fn isDefaultCopy(f: &Fn, defaultsAt: &HashSet<(String, usize, usize, String)>, traitNames: &HashSet<String>) -> bool {
|
compiler/core/src/uniqueness.rs
CHANGED
|
@@ -955,6 +955,66 @@ impl An {
|
|
|
955
955
|
}
|
|
956
956
|
}
|
|
957
957
|
|
|
958
|
+
// ---------- liveness after a downcast ----------
|
|
959
|
+
|
|
960
|
+
/// Whether `x` may be used after the match `target` runs, when `target` is in `stmts`
|
|
961
|
+
/// (`None`: it isn't). Through blocks, `if` and `match` arms the rest of each enclosing
|
|
962
|
+
/// block counts; a loop around it, or any other expression around it, counts as a use.
|
|
963
|
+
fn liveAfterMatch(stmts: &[Stmt], target: &Match, x: &str) -> Option<bool> {
|
|
964
|
+
for (i, s) in stmts.iter().enumerate() {
|
|
965
|
+
if let Some(inner) = liveInStmt(s, target, x) {
|
|
966
|
+
return Some(inner || mentionsVar(&stmts[i + 1..], x));
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
None
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
fn liveInStmt(s: &Stmt, target: &Match, x: &str) -> Option<bool> {
|
|
973
|
+
let found = match &s.kind {
|
|
974
|
+
StmtKind::Match(m) if std::ptr::eq(m, target) => return Some(false),
|
|
975
|
+
StmtKind::Match(m) => m.cases.iter().find_map(|c| liveAfterMatch(&c.body.stmts, target, x)),
|
|
976
|
+
StmtKind::If(i) => std::iter::once(&i.body)
|
|
977
|
+
.chain(i.else_ifs.iter().map(|e| &e.body))
|
|
978
|
+
.chain(i.else_.iter())
|
|
979
|
+
.find_map(|b| liveAfterMatch(&b.stmts, target, x)),
|
|
980
|
+
StmtKind::Expr(e, _, _) | StmtKind::Return(Some(e)) => liveInExpr(e, target, x),
|
|
981
|
+
StmtKind::Assign(a) if a.values.len() == 1 => liveInExpr(&a.values[0], target, x),
|
|
982
|
+
_ => None,
|
|
983
|
+
};
|
|
984
|
+
found.or_else(|| containsMatch(s, target).then_some(true))
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
fn liveInExpr(e: &Expr, target: &Match, x: &str) -> Option<bool> {
|
|
988
|
+
match &e.kind {
|
|
989
|
+
ExprKind::Block(b) => liveAfterMatch(&b.stmts, target, x),
|
|
990
|
+
_ => None,
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
fn containsMatch(s: &Stmt, target: &Match) -> bool {
|
|
995
|
+
let mut found = false;
|
|
996
|
+
walkStmt(s, &mut |n| {
|
|
997
|
+
if let Node::S(Stmt { kind: StmtKind::Match(m), .. }) = n {
|
|
998
|
+
found |= std::ptr::eq(m, target);
|
|
999
|
+
}
|
|
1000
|
+
!found
|
|
1001
|
+
});
|
|
1002
|
+
found
|
|
1003
|
+
}
|
|
1004
|
+
|
|
1005
|
+
fn mentionsVar(ss: &[Stmt], x: &str) -> bool {
|
|
1006
|
+
let mut found = false;
|
|
1007
|
+
for s in ss {
|
|
1008
|
+
walkStmt(s, &mut |n| {
|
|
1009
|
+
if let Node::E(e) = n {
|
|
1010
|
+
found |= isVar(e, x);
|
|
1011
|
+
}
|
|
1012
|
+
!found
|
|
1013
|
+
});
|
|
1014
|
+
}
|
|
1015
|
+
found
|
|
1016
|
+
}
|
|
1017
|
+
|
|
958
1018
|
// ---------- per-variable scan ----------
|
|
959
1019
|
|
|
960
1020
|
struct Scan<'a> {
|
|
@@ -1076,8 +1136,8 @@ impl<'a> Scan<'a> {
|
|
|
1076
1136
|
let Some(x) = m.subjects.get(k).and_then(varName).filter(|x| *x != v && !others) else {
|
|
1077
1137
|
return Some(Err(format!("`{v}` is bound by a downcast of a value that is not a variable")));
|
|
1078
1138
|
};
|
|
1079
|
-
if !tail {
|
|
1139
|
+
if !tail && liveAfterMatch(&self.an.units[self.unit].block.stmts, m, x) != Some(false) {
|
|
1080
|
-
return Some(Err(format!("`{
|
|
1140
|
+
return Some(Err(format!("`{x}` may be used after the match that downcasts it to `{v}`")));
|
|
1081
1141
|
}
|
|
1082
1142
|
let mut usedInArm = false;
|
|
1083
1143
|
let mut seen = |n: Node| {
|
|
@@ -1128,6 +1188,12 @@ impl<'a> Scan<'a> {
|
|
|
1128
1188
|
self.expr(val, false, true);
|
|
1129
1189
|
}
|
|
1130
1190
|
}
|
|
1191
|
+
// `b := match a / Ship as s => .. / _ => a`: a block value whose
|
|
1192
|
+
// result may be the variable moves it into `n` when nothing after
|
|
1193
|
+
// reads it (a downcast in another arm may write it in place).
|
|
1194
|
+
AssignTarget::Var(_) if !live && matches!(val.kind, ExprKind::Block(_)) => {
|
|
1195
|
+
self.expr(val, true, false)
|
|
1196
|
+
}
|
|
1131
1197
|
AssignTarget::Var(n) => self.operand(val, live, format!("`{v}` is also held by `{n}`")),
|
|
1132
1198
|
AssignTarget::Field(o, f) => {
|
|
1133
1199
|
if !self.bare(o) {
|
compiler/core/tests/core/loader_test.rs
CHANGED
|
@@ -680,3 +680,18 @@ fn returnBreakAndContinueAreParseErrors() {
|
|
|
680
680
|
let err = parseErrorOf("import std/Int\n\nfun f(n: Int) =\n for i := range n\n continue\n");
|
|
681
681
|
assert!(err.contains(":5:5:") && err.contains("`continue` is gone"), "{err}");
|
|
682
682
|
}
|
|
683
|
+
|
|
684
|
+
#[test]
|
|
685
|
+
fn parenGroupingGetsAHintToUseBraces() {
|
|
686
|
+
for src in [
|
|
687
|
+
"fun f(a: Int, l: Int) -> Bool =\n (a == l) == false\n",
|
|
688
|
+
"fun f(a: Int, l: Int) -> Bool =\n !(a == l)\n",
|
|
689
|
+
"test \"t\"\n assert (1 == 2) == false\n",
|
|
690
|
+
] {
|
|
691
|
+
let err = parseErrorOf(src);
|
|
692
|
+
assert!(err.contains("hint: grouping uses `{ }`"), "{src}: {err}");
|
|
693
|
+
}
|
|
694
|
+
// A call's `(` is not grouping: no hint.
|
|
695
|
+
let err = parseErrorOf("fun f() =\n x := foo(* 2)\n");
|
|
696
|
+
assert!(!err.contains("grouping"), "{err}");
|
|
697
|
+
}
|
compiler/tooling/tree-sitter-plum/grammar.js
CHANGED
|
@@ -625,13 +625,18 @@ module.exports = grammar({
|
|
|
625
625
|
// pick between two identifier tokens that could both match the same text — that
|
|
626
626
|
// choice was ambiguous and broke `object.method(args)` parsing.
|
|
627
627
|
attribute: ($) =>
|
|
628
|
+
// Right-assoc: a `[` after `x.f` continues the call's type arguments.
|
|
628
|
-
prec(
|
|
629
|
+
prec.right(
|
|
629
630
|
PREC.call,
|
|
630
631
|
seq(
|
|
631
632
|
field("object", $.primary_expression),
|
|
632
633
|
".",
|
|
633
634
|
field("member", choice($.fn_identifier, $.type_identifier)),
|
|
635
|
+
// `xs.findAs[Orb](1)`: explicit type arguments, only before an argument list.
|
|
636
|
+
optional(seq(
|
|
637
|
+
optional(field("generics", $.type_arguments)),
|
|
634
|
-
|
|
638
|
+
field("arguments", $.fn_argument_list),
|
|
639
|
+
)),
|
|
635
640
|
),
|
|
636
641
|
),
|
|
637
642
|
|
|
@@ -654,13 +659,23 @@ module.exports = grammar({
|
|
|
654
659
|
// the parser could see the following `(`.
|
|
655
660
|
fn_call: ($) =>
|
|
656
661
|
prec(PREC.call, seq(
|
|
662
|
+
choice(
|
|
663
|
+
seq(
|
|
664
|
+
field("function", $.var_identifier),
|
|
665
|
+
// `findAs[Orb](xs, 1)`: explicit type arguments for a generic fn.
|
|
666
|
+
optional(field("generics", $.type_arguments)),
|
|
667
|
+
),
|
|
657
|
-
|
|
668
|
+
field("function", $.type_identifier),
|
|
669
|
+
),
|
|
658
670
|
field(
|
|
659
671
|
"arguments",
|
|
660
672
|
$.fn_argument_list,
|
|
661
673
|
),
|
|
662
674
|
)),
|
|
663
675
|
|
|
676
|
+
// `[Orb]`, `[Int, Str]`: a call's explicit type arguments.
|
|
677
|
+
type_arguments: ($) => seq("[", commaSep1(choice($.type, $.fn_value_type)), "]"),
|
|
678
|
+
|
|
664
679
|
fn_argument_list: ($) =>
|
|
665
680
|
seq(
|
|
666
681
|
"(",
|
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
CHANGED
|
@@ -189,3 +189,52 @@ fun f(a: Actor) -> Int =
|
|
|
189
189
|
(expression
|
|
190
190
|
(primary_expression
|
|
191
191
|
(integer)))))))))
|
|
192
|
+
|
|
193
|
+
================================================================================
|
|
194
|
+
explicit type arguments on calls
|
|
195
|
+
================================================================================
|
|
196
|
+
|
|
197
|
+
fun main() =
|
|
198
|
+
a := findAs[Orb](xs, 1)
|
|
199
|
+
b := s.updateAs[Orb](1, f)
|
|
200
|
+
|
|
201
|
+
--------------------------------------------------------------------------------
|
|
202
|
+
|
|
203
|
+
(source
|
|
204
|
+
(fn
|
|
205
|
+
(fn_identifier)
|
|
206
|
+
(body
|
|
207
|
+
(assign
|
|
208
|
+
(var_identifier)
|
|
209
|
+
(expression
|
|
210
|
+
(primary_expression
|
|
211
|
+
(fn_call
|
|
212
|
+
(var_identifier)
|
|
213
|
+
(type_arguments
|
|
214
|
+
(type
|
|
215
|
+
(type_identifier)))
|
|
216
|
+
(fn_argument_list
|
|
217
|
+
(expression
|
|
218
|
+
(primary_expression
|
|
219
|
+
(var_identifier)))
|
|
220
|
+
(expression
|
|
221
|
+
(primary_expression
|
|
222
|
+
(integer))))))))
|
|
223
|
+
(assign
|
|
224
|
+
(var_identifier)
|
|
225
|
+
(expression
|
|
226
|
+
(primary_expression
|
|
227
|
+
(attribute
|
|
228
|
+
(primary_expression
|
|
229
|
+
(var_identifier))
|
|
230
|
+
(fn_identifier)
|
|
231
|
+
(type_arguments
|
|
232
|
+
(type
|
|
233
|
+
(type_identifier)))
|
|
234
|
+
(fn_argument_list
|
|
235
|
+
(expression
|
|
236
|
+
(primary_expression
|
|
237
|
+
(integer)))
|
|
238
|
+
(expression
|
|
239
|
+
(primary_expression
|
|
240
|
+
(var_identifier)))))))))))
|
compiler/wasm-codegen/src/construct.rs
CHANGED
|
@@ -249,6 +249,7 @@ pub(crate) fn compileInterpolatedString(
|
|
|
249
249
|
column: 0,
|
|
250
250
|
tail: ast::TailKind::NotTail,
|
|
251
251
|
recv: None,
|
|
252
|
+
type_args: Vec::new(),
|
|
252
253
|
};
|
|
253
254
|
if plum_checker::nominalName(&other)
|
|
254
255
|
.is_some_and(|n| ctx.func_ids.contains_key(&format!("{}::toStr", n)))
|
compiler/wasm-codegen/src/expr.rs
CHANGED
|
@@ -483,6 +483,7 @@ pub(crate) fn compileExpr(
|
|
|
483
483
|
column: 0,
|
|
484
484
|
tail: ast::TailKind::NotTail,
|
|
485
485
|
recv: None,
|
|
486
|
+
type_args: Vec::new(),
|
|
486
487
|
};
|
|
487
488
|
compileMethodCall(
|
|
488
489
|
&object,
|
compiler/wasm-codegen/src/fnbody.rs
CHANGED
|
@@ -64,8 +64,8 @@ impl<'a> Collector<'a> {
|
|
|
64
64
|
self.bind(n, ty.clone());
|
|
65
65
|
}
|
|
66
66
|
}
|
|
67
|
-
ast::CasePattern::As { ty, name } => {
|
|
67
|
+
ast::CasePattern::As { ty: named, name } => {
|
|
68
|
-
self.bind(name, asPatternType(ty, &self.types.subst));
|
|
68
|
+
self.bind(name, asPatternType(named, ty, &self.types.subst));
|
|
69
69
|
}
|
|
70
70
|
ast::CasePattern::Class { name, fields, .. } => {
|
|
71
71
|
let key = patKey(pat);
|
|
@@ -506,6 +506,8 @@ pub(crate) fn compileFnBodyImpl(
|
|
|
506
506
|
Instruction::Loop(blockTypeFor(result_vt)).encode(&mut body);
|
|
507
507
|
}
|
|
508
508
|
match &f.body {
|
|
509
|
+
// `fun nop(x: Int) = Unit`: a Unit fn returns nothing, so its `Unit` pushes nothing.
|
|
510
|
+
ast::FnBody::Expr(e) if result_vt.is_none() && isUnitLiteral(e, &local_ctx) => {}
|
|
509
511
|
ast::FnBody::Expr(e) => {
|
|
510
512
|
compileExpr(e, &mut body, &local_ctx, state)?;
|
|
511
513
|
}
|
compiler/wasm-codegen/src/matching.rs
CHANGED
|
@@ -3,6 +3,11 @@
|
|
|
3
3
|
use crate::*;
|
|
4
4
|
|
|
5
5
|
/// Returns true if the expression leaves a value on the wasm stack.
|
|
6
|
+
/// `Unit` written as a value.
|
|
7
|
+
pub(crate) fn isUnitLiteral(expr: &ast::Expr, ctx: &LocalCtx) -> bool {
|
|
8
|
+
matches!(&expr.kind, ast::ExprKind::TypeName(n) if n == "Unit" && !ctx.enum_variants.contains_key(n))
|
|
9
|
+
}
|
|
10
|
+
|
|
6
11
|
pub(crate) fn exprHasResult(expr: &ast::Expr, ctx: &LocalCtx) -> bool {
|
|
7
12
|
match expr {
|
|
8
13
|
ast::Expr { kind: ast::ExprKind::Question(_), .. } | ast::Expr { kind: ast::ExprKind::Bang(_), .. }
|
compiler/wasm-codegen/src/stmts.rs
CHANGED
|
@@ -413,6 +413,8 @@ pub(crate) fn compileStmt(
|
|
|
413
413
|
Instruction::End.encode(body);
|
|
414
414
|
Instruction::End.encode(body);
|
|
415
415
|
}
|
|
416
|
+
// A statement `Unit` (a Unit fn's last line) does nothing.
|
|
417
|
+
ast::Stmt { kind: ast::StmtKind::Expr(e, ..), .. } if isUnitLiteral(e, ctx) => {}
|
|
416
418
|
ast::Stmt { kind: ast::StmtKind::Expr(e, ..), .. } => {
|
|
417
419
|
let has_result = exprHasResult(e, ctx);
|
|
418
420
|
compileExpr(e, body, ctx, state)?;
|
compiler/wasm-codegen/src/traits.rs
CHANGED
|
@@ -132,10 +132,18 @@ fn dispatcherSig(obj: &PlumType, method: &str, traits: &Traits, reg: &GcTypeRegi
|
|
|
132
132
|
leafTypes(p, reg, &mut vts);
|
|
133
133
|
}
|
|
134
134
|
let ret_vt = if matches!(*ret, PlumType::TUnit) { Vec::new() } else { flatValtypes(&ret, reg) };
|
|
135
|
+
// The trait's own parameter defaults (closed expressions the checker typed).
|
|
136
|
+
let defaults = traits
|
|
137
|
+
.traitObject(obj)
|
|
138
|
+
.and_then(|(name, _)| traits.traits.get(name))
|
|
139
|
+
.and_then(|t| t.method(method))
|
|
140
|
+
.map(|m| m.defaults.clone())
|
|
141
|
+
.unwrap_or_default();
|
|
142
|
+
let param_defaults = (0..params.len()).map(|i| defaults.get(i).cloned().flatten()).collect();
|
|
135
143
|
Ok(FuncSig {
|
|
136
144
|
params: vts,
|
|
137
145
|
ret: ret_vt,
|
|
138
|
-
param_defaults
|
|
146
|
+
param_defaults,
|
|
139
147
|
decl_params: params,
|
|
140
148
|
decl_ret: *ret,
|
|
141
149
|
inst: None,
|
|
@@ -167,18 +175,26 @@ impl<'a> Setup<'a> {
|
|
|
167
175
|
continue;
|
|
168
176
|
}
|
|
169
177
|
};
|
|
178
|
+
// `Self` inside a parameter or the result: each type's `$dyn` copy, which has the
|
|
179
|
+
// trait object there (`plum_core::trait_defaults::needsDynCopy`).
|
|
180
|
+
let dyn_copy = traits
|
|
181
|
+
.traitObject(&obj)
|
|
182
|
+
.and_then(|(n, _)| traits.traits.get(n))
|
|
183
|
+
.and_then(|t| t.method(&method))
|
|
184
|
+
.is_some_and(|m| m.dyn_copy);
|
|
185
|
+
let target = if dyn_copy { plum_core::trait_defaults::dynName(&method) } else { method.clone() };
|
|
170
186
|
let mut b: Vec<u8> = vec![0u8];
|
|
171
187
|
for c in implementersOf(&obj, ®, &traits) {
|
|
172
188
|
let (Some(tag), Some((f, csig))) = (
|
|
173
189
|
tagIdx(&c, ®),
|
|
174
|
-
implementerMethod(&c, &
|
|
190
|
+
implementerMethod(&c, &target, &self.func_ids, &self.func_sigs, &self.inst_funcs, &self.inst_index),
|
|
175
191
|
) else {
|
|
176
192
|
self.dispatch_errors.push(format!("codegen: {c} has no compiled method '{method}' for a call on {obj}"));
|
|
177
193
|
continue;
|
|
178
194
|
};
|
|
179
195
|
if csig.params.len() != sig.params.len() || !csig.ret.iter().zip(&sig.ret).all(|(a, b)| a == b || isRefTo(*b, *a)) || csig.ret.len() != sig.ret.len() {
|
|
180
196
|
self.dispatch_errors.push(format!(
|
|
181
|
-
"codegen: {c}.{
|
|
197
|
+
"internal codegen error: {c}.{target} doesn't fit the dispatcher of {obj}.{method}"
|
|
182
198
|
));
|
|
183
199
|
continue;
|
|
184
200
|
}
|
|
@@ -299,14 +315,20 @@ pub(crate) enum AsTarget {
|
|
|
299
315
|
Test(u32, PlumType),
|
|
300
316
|
}
|
|
301
317
|
|
|
302
|
-
/// The type a downcast pattern names: a declared type,
|
|
318
|
+
/// The type a downcast pattern names: a declared type, (in an instantiated body) the type a
|
|
303
|
-
///
|
|
319
|
+
/// generic parameter stands for, or a generic implementer with the arguments the trait
|
|
320
|
+
/// object `subject` gives it (`Box as b` on an `Actor[Msg]`: `Box[Msg]`).
|
|
304
|
-
pub(crate) fn asPatternType(ty: &str, subst: &Subst) -> PlumType {
|
|
321
|
+
pub(crate) fn asPatternType(ty: &str, subject: &PlumType, subst: &Subst) -> PlumType {
|
|
322
|
+
if let Some(t) = subst.get(ty) {
|
|
323
|
+
return t.clone();
|
|
324
|
+
}
|
|
325
|
+
programTraits()
|
|
326
|
+
.genericDowncast(ty, subject)
|
|
305
|
-
|
|
327
|
+
.unwrap_or_else(|| plum_checker::plumTypeFromName(ty))
|
|
306
328
|
}
|
|
307
329
|
|
|
308
330
|
pub(crate) fn asTarget(ty: &str, subject: &PlumType, subst: &Subst, reg: &GcTypeRegistry) -> AsTarget {
|
|
309
|
-
let target = asPatternType(ty, subst);
|
|
331
|
+
let target = asPatternType(ty, subject, subst);
|
|
310
332
|
if canonTy(&target) == canonTy(subject) {
|
|
311
333
|
return AsTarget::Always(target);
|
|
312
334
|
}
|
compiler/wasm-codegen/tests/wasm_codegen/fusion_alloc_test.rs
CHANGED
|
@@ -784,3 +784,44 @@ fun main() -> Int = total(run(Node(a: rock(), rest: build(10)), 100))
|
|
|
784
784
|
assert_eq!(newsIn(©ing, "Ship.step"), 1);
|
|
785
785
|
assert_eq!(runInt(&engine(false), ©ing).0, 1058);
|
|
786
786
|
}
|
|
787
|
+
|
|
788
|
+
/// A downcast whose match is not the result still moves the subject when the subject is
|
|
789
|
+
/// not used after the match: the spread in the arm reuses the ship.
|
|
790
|
+
#[test]
|
|
791
|
+
fn downcast_in_a_match_value_is_in_place() {
|
|
792
|
+
let body = "fun still(a: Actor) -> Int =
|
|
793
|
+
b := match a
|
|
794
|
+
Ship as s => Ship(..s, x: 0)
|
|
795
|
+
_ => a
|
|
796
|
+
b.key() * 10
|
|
797
|
+
|
|
798
|
+
fun main() -> Int =
|
|
799
|
+
still(Ship(label: \"b\", x: 4, y: 7)) + still(rock())
|
|
800
|
+
";
|
|
801
|
+
let src = load("trait_downcast_value", &format!("{PRE}{ACTORS}{body}"));
|
|
802
|
+
let wasm = compileFbip(&src, true);
|
|
803
|
+
assert_eq!(newsIn(&wasm, "still"), 0, "the arm writes the ship in place");
|
|
804
|
+
assert_eq!(runInt(&engine(false), &wasm).0, 100);
|
|
805
|
+
let copying = compileFbip(&src, false);
|
|
806
|
+
assert!(newsIn(©ing, "still") >= 1, "--no-fbip: the arm copies");
|
|
807
|
+
assert_eq!(runInt(&engine(false), ©ing).0, 100);
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/// The subject read after the match keeps the arm's spread a copy.
|
|
811
|
+
#[test]
|
|
812
|
+
fn downcast_subject_used_after_the_match_is_a_copy() {
|
|
813
|
+
let body = "fun still(a: Actor) -> Int =
|
|
814
|
+
b := match a
|
|
815
|
+
Ship as s => Ship(..s, x: 0)
|
|
816
|
+
_ => a
|
|
817
|
+
b.key() * 100 + a.key()
|
|
818
|
+
|
|
819
|
+
fun main() -> Int =
|
|
820
|
+
_ := rock()
|
|
821
|
+
still(Ship(label: \"b\", x: 4, y: 7))
|
|
822
|
+
";
|
|
823
|
+
let src = load("trait_downcast_after", &format!("{PRE}{ACTORS}{body}"));
|
|
824
|
+
let wasm = compileFbip(&src, true);
|
|
825
|
+
assert!(newsIn(&wasm, "still") >= 1, "the subject is read after the match: a copy");
|
|
826
|
+
assert_eq!(runInt(&engine(false), &wasm).0, 711);
|
|
827
|
+
}
|
tests/traits/limits.plum
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Str
|
|
3
|
+
import std/List
|
|
4
|
+
import std/Option
|
|
5
|
+
|
|
6
|
+
# Generic implementers pinned by a later use, trait defaults on parameters through
|
|
7
|
+
# dispatch, `Self` inside another type, and downcasts to a generic implementer.
|
|
8
|
+
|
|
9
|
+
enum Msg = Hit | Miss
|
|
10
|
+
|
|
11
|
+
trait Actor[M] =
|
|
12
|
+
fun key(self) -> Int
|
|
13
|
+
fun input(self, e: Int) -> Option[M] = None
|
|
14
|
+
fun moved(self, dx: Int = 1, dy: Int = 2) -> Int = self.key() + dx + dy
|
|
15
|
+
fun split(self) -> List[Self] = [self]
|
|
16
|
+
fun next(self) -> Option[Self] = None
|
|
17
|
+
fun merge(self, others: List[Self]) -> Int = self.key() + others.length()
|
|
18
|
+
|
|
19
|
+
struct Box[M](id: Int) is Actor[M] =
|
|
20
|
+
fun key(self) -> Int = self.id
|
|
21
|
+
fun next(self) -> Option[Box[M]] = Some(Box(id: self.id + 1))
|
|
22
|
+
|
|
23
|
+
struct Btn[M](id: Int, on: M) is Actor[M] =
|
|
24
|
+
fun key(self) -> Int = self.id
|
|
25
|
+
fun input(self, e: Int) -> Option[M] = if e == self.id then Some(self.on) else None
|
|
26
|
+
fun moved(self, dx: Int = 10, dy: Int = 20) -> Int = self.key() + dx * 100 + dy
|
|
27
|
+
|
|
28
|
+
struct Cell(id: Int) is Actor[Msg] =
|
|
29
|
+
fun key(self) -> Int = self.id
|
|
30
|
+
fun split(self) -> List[Cell] = [Cell(id: self.id), Cell(id: self.id + 10)]
|
|
31
|
+
|
|
32
|
+
fun onOf(a: Actor[Msg]) -> Option[Msg] = match a
|
|
33
|
+
Btn as b => Some(b.on)
|
|
34
|
+
_ => None
|
|
35
|
+
|
|
36
|
+
fun bump(a: Actor[Msg]) -> Actor[Msg] = match a
|
|
37
|
+
Box as b => Box(..b, id: b.id + 1)
|
|
38
|
+
_ => a
|
|
39
|
+
|
|
40
|
+
test "a generic implementer built bare takes M from its later use"
|
|
41
|
+
bx := Box(id: 1)
|
|
42
|
+
xs: List[Actor[Msg]] := [bx, Btn(id: 2, on: Hit)]
|
|
43
|
+
assert xs.fold(0, |n, a| n + a.key()) == 3
|
|
44
|
+
assert xs.fold(0, |n, a| n + a.input(2).map(|_| 1).unwrapOr(0)) == 1
|
|
45
|
+
|
|
46
|
+
test "a call on a trait object fills in the trait's parameter defaults"
|
|
47
|
+
a: Actor[Msg] := Box(id: 1)
|
|
48
|
+
assert a.moved() == 4
|
|
49
|
+
assert a.moved(5) == 8
|
|
50
|
+
assert a.moved(5, 0) == 6
|
|
51
|
+
b: Actor[Msg] := Btn(id: 1, on: Miss)
|
|
52
|
+
assert b.moved() == 103
|
|
53
|
+
assert Btn(id: 1, on: Miss).moved() == 1021
|
|
54
|
+
|
|
55
|
+
test "Self inside another type through dispatch"
|
|
56
|
+
a: Actor[Msg] := Box(id: 1)
|
|
57
|
+
c: Actor[Msg] := Cell(id: 2)
|
|
58
|
+
assert a.split().length() == 1
|
|
59
|
+
assert c.split().length() == 2
|
|
60
|
+
assert c.split().get(1).unwrap().key() == 12
|
|
61
|
+
assert a.next().unwrap().key() == 2
|
|
62
|
+
assert c.next().isNone()
|
|
63
|
+
xs: List[Actor[Msg]] := [a, c]
|
|
64
|
+
assert a.merge(xs) == 3
|
|
65
|
+
assert Cell(id: 2).split().get(1).unwrap().id == 12
|
|
66
|
+
|
|
67
|
+
test "a downcast to a generic implementer takes its arguments from the trait object"
|
|
68
|
+
a: Actor[Msg] := Btn(id: 1, on: Hit)
|
|
69
|
+
c: Actor[Msg] := Cell(id: 2)
|
|
70
|
+
assert onOf(a).unwrap() == Hit
|
|
71
|
+
assert onOf(c).isNone()
|
|
72
|
+
assert bump(Box(id: 1)).key() == 2
|
|
73
|
+
assert bump(c).key() == 2
|
tests/traits/type_args.plum
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import std/Int
|
|
2
|
+
import std/Float
|
|
3
|
+
import std/Str
|
|
4
|
+
import std/List
|
|
5
|
+
import std/Option
|
|
6
|
+
|
|
7
|
+
# Explicit type arguments on calls: `f[Orb](..)` and `stage.updateAs[Orb](..)`.
|
|
8
|
+
|
|
9
|
+
trait Actor =
|
|
10
|
+
fun key(self) -> Int
|
|
11
|
+
|
|
12
|
+
struct Orb(id: Int, vx: Float) is Actor =
|
|
13
|
+
fun key(self) -> Int = self.id
|
|
14
|
+
|
|
15
|
+
struct Label(id: Int, text: Str) is Actor =
|
|
16
|
+
fun key(self) -> Int = self.id
|
|
17
|
+
|
|
18
|
+
fun findAs[T](xs: List[Actor], id: Int) -> Option[T] = match xs
|
|
19
|
+
Cons(a, rest) =>
|
|
20
|
+
if a.key() == id
|
|
21
|
+
match a
|
|
22
|
+
T as t => Some(t)
|
|
23
|
+
_ => None
|
|
24
|
+
else
|
|
25
|
+
findAs(rest, id)
|
|
26
|
+
Nil => None
|
|
27
|
+
|
|
28
|
+
struct Stage(xs: List[Actor]) =
|
|
29
|
+
fun findAs[T](self, id: Int) -> Option[T] = findAs(self.xs, id)
|
|
30
|
+
|
|
31
|
+
fun updateAs[T](self, id: Int, f: fn(T) -> T) -> Stage =
|
|
32
|
+
Stage(xs: self.xs.map(|a| if a.key() == id
|
|
33
|
+
match a
|
|
34
|
+
T as t =>
|
|
35
|
+
b: Actor := f(t)
|
|
36
|
+
b
|
|
37
|
+
_ => a
|
|
38
|
+
else
|
|
39
|
+
a))
|
|
40
|
+
|
|
41
|
+
fun pair[A, B](a: A, b: B) -> Int = 2
|
|
42
|
+
|
|
43
|
+
fun isA[T](a: Actor) -> Bool = match a
|
|
44
|
+
T as t => true
|
|
45
|
+
_ => false
|
|
46
|
+
|
|
47
|
+
test "a free call with an explicit type argument"
|
|
48
|
+
xs: List[Actor] := [Orb(id: 1, vx: 2.0), Label(id: 2, text: "two")]
|
|
49
|
+
assert findAs[Orb](xs, 1).unwrap().vx == 2.0
|
|
50
|
+
assert findAs[Label](xs, 2).unwrap().text == "two"
|
|
51
|
+
assert findAs[Label](xs, 1).isNone()
|
|
52
|
+
assert pair[Int, Str](1, "a") == 2
|
|
53
|
+
|
|
54
|
+
test "a method call with an explicit type argument"
|
|
55
|
+
s := Stage(xs: [Orb(id: 1, vx: 2.0), Label(id: 2, text: "two")])
|
|
56
|
+
t := s.updateAs[Orb](1, |o| Orb(..o, vx: o.vx * 10.0))
|
|
57
|
+
assert t.findAs[Orb](1).unwrap().vx == 20.0
|
|
58
|
+
u := t.updateAs[Label](1, |l| Label(..l, text: "no"))
|
|
59
|
+
assert u.findAs[Orb](1).unwrap().vx == 20.0
|
|
60
|
+
v := u.updateAs[Label](2, |l| Label(..l, text: "yes"))
|
|
61
|
+
assert v.findAs[Label](2).unwrap().text == "yes"
|
|
62
|
+
|
|
63
|
+
test "a type parameter used only in the body"
|
|
64
|
+
o: Actor := Orb(id: 1, vx: 2.0)
|
|
65
|
+
assert isA[Orb](o)
|
|
66
|
+
assert !isA[Label](o)
|